h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.04k stars 106 forks source link

Mocked response with 301 status code and location header returns an error #97

Open wxm112 opened 2 years ago

wxm112 commented 2 years ago

When I mocked a response just with 301 status code, I got an error with a message: 301 response missing Location header. After adding the location header, there was another error with a message: gock: cannot match any request.

The code is shown as below:



import (
    "net/http"
    "testing"

    "github.com/stretchr/testify/assert"
    "gopkg.in/h2non/gock.v1"
)

func TestWithLocationHeader(t *testing.T) {
    defer gock.Off()

    gock.New("https://domain.com").
        Get("/path").
        Reply(301).
        SetHeader("Location", "https://domain.com/newpath")

    _, err := http.Get("https://domain.com/path")

    assert.Equal(t, "Get \"https://domain.com/newpath\": gock: cannot match any request", err.Error())
}

func TestWithoutLocationHeader(t *testing.T) {
    defer gock.Off()

    gock.New("https://domain.com").
        Get("/path").
        Reply(301)

    _, err := http.Get("https://domain.com/path")

    assert.Equal(t, "Get \"https://domain.com/path\": 301 response missing Location header", err.Error())
}
westy92 commented 1 year ago

I was able to do the following:

defer gock.Off()

gock.New("https://domain.com/").
    Get("/initial").
    Reply(302).
    SetHeader("Location", "https://domain.com/redirected")

gock.New("https://domain.com/").
    Get("/redirected").
    Reply(200).
    File("test.json")

// call API domain.com/initial and assert you get a 200 with the redirect body

assert.True(t, gock.IsDone())