|
| 1 | +package clihttp_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/DoNewsCode/core" |
| 8 | + "github.com/DoNewsCode/core/clihttp" |
| 9 | + "github.com/DoNewsCode/core/contract" |
| 10 | + "github.com/DoNewsCode/core/observability" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +type mockDoer bool |
| 15 | + |
| 16 | +func (m *mockDoer) Do(req *http.Request) (*http.Response, error) { |
| 17 | + *m = true |
| 18 | + resp := http.Response{} |
| 19 | + return &resp, nil |
| 20 | +} |
| 21 | + |
| 22 | +func TestProviders(t *testing.T) { |
| 23 | + t.Run("no panic", func(t *testing.T) { |
| 24 | + c := core.Default() |
| 25 | + c.Provide(observability.Providers()) |
| 26 | + c.Provide(clihttp.Providers()) |
| 27 | + c.Invoke(func(client *clihttp.Client) {}) |
| 28 | + c.Invoke(func(client contract.HttpDoer) {}) |
| 29 | + }) |
| 30 | + t.Run("panic", func(t *testing.T) { |
| 31 | + defer func() { |
| 32 | + if r := recover(); r != nil { |
| 33 | + return |
| 34 | + } |
| 35 | + t.Fatal("test should panic") |
| 36 | + }() |
| 37 | + c := core.Default() |
| 38 | + c.Provide(clihttp.Providers()) |
| 39 | + c.Invoke(func(client *clihttp.Client) {}) |
| 40 | + }) |
| 41 | + t.Run("replace doer", func(t *testing.T) { |
| 42 | + var mock mockDoer |
| 43 | + c := core.Default() |
| 44 | + c.Provide(observability.Providers()) |
| 45 | + c.Provide(clihttp.Providers(clihttp.WithClientConstructor(func(args clihttp.ClientArgs) (contract.HttpDoer, error) { |
| 46 | + return &mock, nil |
| 47 | + }))) |
| 48 | + c.Invoke(func(client *clihttp.Client) { |
| 49 | + req, _ := http.NewRequest(http.MethodGet, "", nil) |
| 50 | + client.Do(req) |
| 51 | + assert.True(t, bool(mock)) |
| 52 | + }) |
| 53 | + }) |
| 54 | + t.Run("additional options", func(t *testing.T) { |
| 55 | + c := core.Default() |
| 56 | + c.Provide(observability.Providers()) |
| 57 | + c.Provide(clihttp.Providers(clihttp.WithClientOption(clihttp.WithRequestLogThreshold(10)))) |
| 58 | + c.Invoke(func(client *clihttp.Client) {}) |
| 59 | + }) |
| 60 | +} |
0 commit comments