launchdarkly / api-client-go

LaunchDarkly API Client for Go
Other
8 stars 12 forks source link

Make testing easier #4

Closed moshegood closed 3 years ago

moshegood commented 3 years ago

When writing tests for applications that use this library, if the various services were defined as interfaces rather than concrete types it would testing a lot easier. One could then simply create mocks for those services rather than spinning up a test http server.

Happy to do this for one of the services as an example if needed.

eli-darkly commented 3 years ago

@moshegood: this library is automatically generated by swagger-codegen from our OpenAPI spec. Therefore we're stuck with the code structure that swagger-codegen provides; submitting a PR for this repository wouldn't work, since the code would be overwritten the next time it's regenerated.

So, based on the current behavior of swagger-codegen, it is unfortunately necessary to create mock HTTP responses rather than mock services. But I don't think it's necessary to actually make a test HTTP server in order to do that. The Configuration type has an HTTPClient field, so you can provide a client that has a mock Transport to return any kind of responses you want.

pab1it0 commented 2 years ago

@moshegood Here's a simple example on how to initiate NewAPIClient and test against a given response:

    response, err := os.ReadFile("testdata/GetSegment-response.json")
    if err != nil {
        t.Fatal(err)
    }

    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
        io.WriteString(w, string(response))
    }))
    defer ts.Close()

    ldClient := ldapi.NewAPIClient( &ldapi.Configuration{
        BasePath:      ts.URL,
        Host:          "localhost",
        Scheme:        "http",
        DefaultHeader: nil,
        UserAgent:     "",
        HTTPClient:  ts.Client(),
    })