1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
|
package httprc_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/lestrrat-go/httprc/v3"
"github.com/stretchr/testify/require"
)
func TestControllerAdd(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}))
t.Cleanup(srv.Close)
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
t.Cleanup(func() { ctrl.Shutdown(time.Second) })
t.Run("add new resource", func(t *testing.T) {
t.Parallel()
resource, err := httprc.NewResource[map[string]string](
srv.URL+"/test1",
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
require.NoError(t, ctrl.Add(ctx, resource), "adding new resource to controller should succeed")
// Should be able to lookup the resource
found, err := ctrl.Lookup(ctx, srv.URL+"/test1")
require.NoError(t, err)
require.Equal(t, srv.URL+"/test1", found.URL())
})
t.Run("add duplicate resource should fail", func(t *testing.T) {
t.Parallel()
resource1, err := httprc.NewResource[map[string]string](
srv.URL+"/test2",
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
// First add should succeed
require.NoError(t, ctrl.Add(ctx, resource1), "first resource addition should succeed")
resource2, err := httprc.NewResource[map[string]string](
srv.URL+"/test2", // Same URL
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
// Second add should fail
err = ctrl.Add(ctx, resource2)
require.Error(t, err)
})
t.Run("add with canceled context", func(t *testing.T) {
t.Parallel()
canceledCtx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
resource, err := httprc.NewResource[map[string]string](
srv.URL+"/test3",
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
err = ctrl.Add(canceledCtx, resource)
require.Error(t, err)
require.Equal(t, context.Canceled, err)
})
}
func TestControllerLookup(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"path": r.URL.Path})
}))
t.Cleanup(srv.Close)
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
t.Cleanup(func() { ctrl.Shutdown(time.Second) })
t.Run("lookup existing resource", func(t *testing.T) {
t.Parallel()
testURL := srv.URL + "/lookup-test"
resource, err := httprc.NewResource[map[string]string](
testURL,
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
require.NoError(t, ctrl.Add(ctx, resource), "adding resource for lookup test should succeed")
found, err := ctrl.Lookup(ctx, testURL)
require.NoError(t, err)
require.Equal(t, testURL, found.URL())
})
t.Run("lookup non-existent resource", func(t *testing.T) {
t.Parallel()
nonExistentURL := srv.URL + "/does-not-exist"
_, err := ctrl.Lookup(ctx, nonExistentURL)
require.Error(t, err)
})
t.Run("lookup with canceled context", func(t *testing.T) {
t.Parallel()
canceledCtx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
_, err := ctrl.Lookup(canceledCtx, srv.URL+"/any")
require.Error(t, err)
require.Equal(t, context.Canceled, err)
})
}
func TestControllerRemove(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}))
t.Cleanup(srv.Close)
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
t.Cleanup(func() { ctrl.Shutdown(time.Second) })
t.Run("remove existing resource", func(t *testing.T) {
t.Parallel()
testURL := srv.URL + "/remove-test"
resource, err := httprc.NewResource[map[string]string](
testURL,
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
// Add the resource
require.NoError(t, ctrl.Add(ctx, resource), "adding resource for removal test should succeed")
// Verify it exists
_, err = ctrl.Lookup(ctx, testURL)
require.NoError(t, err, "resource should be found after adding")
// Remove it
require.NoError(t, ctrl.Remove(ctx, testURL), "removing existing resource should succeed")
// Verify it's gone
_, err = ctrl.Lookup(ctx, testURL)
require.Error(t, err)
})
t.Run("remove non-existent resource", func(t *testing.T) {
t.Parallel()
nonExistentURL := srv.URL + "/does-not-exist"
err := ctrl.Remove(ctx, nonExistentURL)
require.Error(t, err)
})
t.Run("remove with canceled context", func(t *testing.T) {
t.Parallel()
canceledCtx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
err := ctrl.Remove(canceledCtx, srv.URL+"/any")
require.Error(t, err)
require.Equal(t, context.Canceled, err)
})
}
func TestControllerRefresh(t *testing.T) {
t.Parallel()
var requestCount int
var mu sync.Mutex
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
requestCount++
count := requestCount
mu.Unlock()
json.NewEncoder(w).Encode(map[string]int{"count": count})
}))
t.Cleanup(srv.Close)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
t.Cleanup(func() { ctrl.Shutdown(time.Second) })
t.Run("refresh existing resource", func(t *testing.T) {
t.Parallel()
testURL := srv.URL + "/refresh-test"
resource, err := httprc.NewResource[map[string]int](
testURL,
httprc.JSONTransformer[map[string]int](),
)
require.NoError(t, err)
// Add the resource (this will trigger the first request)
require.NoError(t, ctrl.Add(ctx, resource), "adding resource for refresh test should succeed")
// Get initial count
var data1 map[string]int
require.NoError(t, resource.Get(&data1), "getting initial data should succeed")
initialCount := data1["count"]
// Force refresh
require.NoError(t, ctrl.Refresh(ctx, testURL), "refreshing resource should succeed")
// Get updated count
var data2 map[string]int
require.NoError(t, resource.Get(&data2), "getting updated data should succeed")
newCount := data2["count"]
require.Greater(t, newCount, initialCount, "count should have increased after refresh")
})
t.Run("refresh non-existent resource", func(t *testing.T) {
t.Parallel()
nonExistentURL := srv.URL + "/does-not-exist"
err := ctrl.Refresh(ctx, nonExistentURL)
require.Error(t, err)
})
t.Run("refresh with canceled context", func(t *testing.T) {
t.Parallel()
canceledCtx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
err := ctrl.Refresh(canceledCtx, srv.URL+"/any")
require.Error(t, err)
require.Equal(t, context.Canceled, err)
})
}
func TestControllerShutdown(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}))
t.Cleanup(srv.Close)
t.Run("shutdown with timeout", func(t *testing.T) {
t.Parallel()
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
// Add a resource
resource, err := httprc.NewResource[map[string]string](
srv.URL,
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
require.NoError(t, ctrl.Add(ctx, resource), "adding resource for shutdown test should succeed")
// Shutdown should complete within timeout
require.NoError(t, ctrl.Shutdown(5*time.Second), "shutdown with timeout should succeed")
})
t.Run("shutdown with context", func(t *testing.T) {
t.Parallel()
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
// Add a resource
resource, err := httprc.NewResource[map[string]string](
srv.URL,
httprc.JSONTransformer[map[string]string](),
)
require.NoError(t, err)
require.NoError(t, ctrl.Add(ctx, resource), "adding resource for shutdown context test should succeed")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
require.NoError(t, ctrl.ShutdownContext(shutdownCtx), "shutdown with context should succeed")
})
t.Run("shutdown with canceled context", func(t *testing.T) {
t.Parallel()
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
canceledCtx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
err = ctrl.ShutdownContext(canceledCtx)
require.Error(t, err)
require.Equal(t, context.Canceled, err)
// Clean shutdown with proper context
require.NoError(t, ctrl.Shutdown(time.Second), "clean shutdown should succeed")
})
}
func TestControllerConcurrentOperations(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"url": r.URL.Path})
}))
defer srv.Close()
cl := httprc.NewClient(httprc.WithWorkers(5))
ctrl, err := cl.Start(ctx)
require.NoError(t, err)
t.Cleanup(func() { ctrl.Shutdown(time.Second) })
const numGoroutines = 10
const numOperationsPerGoroutine = 5
var wg sync.WaitGroup
var addedURLs sync.Map
// Concurrent adds
for i := range numGoroutines {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := range numOperationsPerGoroutine {
testURL := fmt.Sprintf("%s/concurrent-test-%d-%d", srv.URL, i, j)
resource, err := httprc.NewResource[map[string]string](
testURL,
httprc.JSONTransformer[map[string]string](),
)
if err != nil {
t.Errorf("failed to create resource: %v", err)
return
}
err = ctrl.Add(ctx, resource)
if err != nil {
t.Errorf("failed to add resource %s: %v", testURL, err)
return
}
addedURLs.Store(testURL, true)
}
}(i)
}
wg.Wait()
// Verify all resources can be looked up
addedURLs.Range(func(key, _ any) bool {
testURL := key.(string)
_, err := ctrl.Lookup(ctx, testURL)
require.NoError(t, err, "should be able to lookup %s", testURL)
return true
})
// Concurrent lookups and refreshes
wg = sync.WaitGroup{}
for i := range numGoroutines {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := range numOperationsPerGoroutine {
testURL := fmt.Sprintf("%s/concurrent-test-%d-%d", srv.URL, i, j)
// Lookup
_, err := ctrl.Lookup(ctx, testURL)
if err != nil {
t.Errorf("failed to lookup resource %s: %v", testURL, err)
return
}
// Refresh
err = ctrl.Refresh(ctx, testURL)
if err != nil {
t.Errorf("failed to refresh resource %s: %v", testURL, err)
return
}
}
}(i)
}
wg.Wait()
}
|