|
| 1 | +package runtime |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestGetTraceId(t *testing.T) { |
| 10 | + type args struct { |
| 11 | + ctx context.Context |
| 12 | + } |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + args args |
| 16 | + wantTraceId string |
| 17 | + }{ |
| 18 | + { |
| 19 | + name: "with set traceId", |
| 20 | + args: args{ |
| 21 | + ctx: func() context.Context { |
| 22 | + ctx := context.Background() |
| 23 | + header := http.Header{} |
| 24 | + header.Set(xTraceIdHeader, "my-trace-id") |
| 25 | + httpResp := &http.Response{ |
| 26 | + Header: header, |
| 27 | + } |
| 28 | + ctx = WithCaptureHTTPResponse(ctx, &httpResp) |
| 29 | + return ctx |
| 30 | + }(), |
| 31 | + }, |
| 32 | + wantTraceId: "my-trace-id", |
| 33 | + }, |
| 34 | + { |
| 35 | + name: "without traceId header", |
| 36 | + args: args{ |
| 37 | + ctx: func() context.Context { |
| 38 | + ctx := context.Background() |
| 39 | + httpResp := &http.Response{ |
| 40 | + Header: http.Header{}, |
| 41 | + } |
| 42 | + ctx = WithCaptureHTTPResponse(ctx, &httpResp) |
| 43 | + return ctx |
| 44 | + }(), |
| 45 | + }, |
| 46 | + wantTraceId: "", |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "with empty response", |
| 50 | + args: args{ |
| 51 | + ctx: func() context.Context { |
| 52 | + ctx := context.Background() |
| 53 | + var httpResp *http.Response |
| 54 | + ctx = WithCaptureHTTPResponse(ctx, &httpResp) |
| 55 | + return ctx |
| 56 | + }(), |
| 57 | + }, |
| 58 | + wantTraceId: "", |
| 59 | + }, |
| 60 | + { |
| 61 | + name: "without response in context", |
| 62 | + args: args{ |
| 63 | + ctx: context.Background(), |
| 64 | + }, |
| 65 | + wantTraceId: "", |
| 66 | + }, |
| 67 | + } |
| 68 | + for _, tt := range tests { |
| 69 | + t.Run(tt.name, func(t *testing.T) { |
| 70 | + if gotTraceId := GetTraceId(tt.args.ctx); gotTraceId != tt.wantTraceId { |
| 71 | + t.Errorf("GetTraceId() = %v, want %v", gotTraceId, tt.wantTraceId) |
| 72 | + } |
| 73 | + }) |
| 74 | + } |
| 75 | +} |
0 commit comments