|
| 1 | +// These tests verify that the example server uses its CBOR transport codecs. |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "net" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "sync" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/fxamacker/cbor/v2" |
| 14 | + "goa.design/clue/log" |
| 15 | + concatapi "goa.design/examples/encodings/cbor" |
| 16 | + genconcat "goa.design/examples/encodings/cbor/gen/concat" |
| 17 | +) |
| 18 | + |
| 19 | +// TestHTTPServerUsesCBOR checks the response produced by the configured HTTP |
| 20 | +// server rather than testing the codec functions on their own. |
| 21 | +func TestHTTPServerUsesCBOR(t *testing.T) { |
| 22 | + listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 23 | + if err != nil { |
| 24 | + t.Fatalf("reserve HTTP address: %v", err) |
| 25 | + } |
| 26 | + address := listener.Addr().String() |
| 27 | + if err := listener.Close(); err != nil { |
| 28 | + t.Fatalf("release HTTP address: %v", err) |
| 29 | + } |
| 30 | + |
| 31 | + serverURL := &url.URL{Scheme: "http", Host: address} |
| 32 | + endpoints := genconcat.NewEndpoints(concatapi.NewConcat()) |
| 33 | + logContext := log.Context(context.Background(), log.WithFormat(log.FormatJSON)) |
| 34 | + ctx, cancel := context.WithCancel(logContext) |
| 35 | + var waitGroup sync.WaitGroup |
| 36 | + handleHTTPServer(ctx, serverURL, endpoints, &waitGroup, make(chan error, 1), false) |
| 37 | + t.Cleanup(func() { |
| 38 | + cancel() |
| 39 | + waitGroup.Wait() |
| 40 | + }) |
| 41 | + |
| 42 | + response := waitForHTTPResponse(t, "http://"+address+"/concat/a/b") |
| 43 | + t.Cleanup(func() { |
| 44 | + if err := response.Body.Close(); err != nil { |
| 45 | + t.Errorf("close response body: %v", err) |
| 46 | + } |
| 47 | + }) |
| 48 | + if got := response.Header.Get("Content-Type"); got != "application/cbor" { |
| 49 | + t.Fatalf("Content-Type = %q, want application/cbor", got) |
| 50 | + } |
| 51 | + |
| 52 | + var result string |
| 53 | + if err := cbor.NewDecoder(response.Body).Decode(&result); err != nil { |
| 54 | + t.Fatalf("decode CBOR response: %v", err) |
| 55 | + } |
| 56 | + if result != "ab" { |
| 57 | + t.Fatalf("result = %q, want ab", result) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// waitForHTTPResponse waits until the server accepts requests or the test |
| 62 | +// timeout expires. |
| 63 | +func waitForHTTPResponse(t *testing.T, requestURL string) *http.Response { |
| 64 | + t.Helper() |
| 65 | + |
| 66 | + client := &http.Client{Timeout: 100 * time.Millisecond} |
| 67 | + deadline := time.Now().Add(2 * time.Second) |
| 68 | + for { |
| 69 | + response, err := client.Get(requestURL) |
| 70 | + if err == nil { |
| 71 | + return response |
| 72 | + } |
| 73 | + if time.Now().After(deadline) { |
| 74 | + t.Fatalf("GET %s: %v", requestURL, err) |
| 75 | + } |
| 76 | + time.Sleep(10 * time.Millisecond) |
| 77 | + } |
| 78 | +} |
0 commit comments