1

I am trying to do unit testing, I am using GraphQL gqlgen for this case with Echo, I have been struggle to do test with my context, I can't add header in my testing due the GraphQL not using the server endpoint here is my code to set the context value

var ctx *http.Request
var echo echo.Context

h := context.WithValue(ctx.Context(), "Token", token)
tk := ctx.WithContext(h)
echo.SetRequest(tk)

I do this on middleware function when I run my server, nothing issue, here is how I call that in my resolver

// c is context.Context
tokenHeader = c.Value("Token")

but in testing I create that codes always got:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1703953]

goroutine 30 [running]:
testing.tRunner.func1.1(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:940 +0x2f5
testing.tRunner.func1(0xc000378900)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:943 +0x3f9
panic(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/runtime/panic.go:969 +0x166
spur/test.TestCredential.func3(0xc000378900)
        /Users/me/Documents/project/test/main_test.go:144 +0x193
testing.tRunner(0xc000378900, 0xc00034fdf0)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:991 +0xdc
created by testing.(*T).Run
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:1042 +0x357

is it possible to set the context value during in test?

here is may full testing code:


func TestCredential(t *testing.T)  {
    config := resolver.Config{
        Resolvers: resolver.New(),
    }

    clientTest := testClient.New(handler.NewDefaultServer(resolver.NewExecutableSchema(config)))

    t.Run("Should Success Change Password", func(t *testing.T) {
        var ctx *http.Request
        var echo echo.Context

        h := context.WithValue(ctx.Context(), "Token", token)
        tk := ctx.WithContext(h)
        echo.SetRequest(tk)


        var respond map[string]interface{}
        mutation := `mutation {
                      changeCredentialConfirmation(
                        currentPassword: ""
                        newChange: "newPassword"
                        isForgotPassword: true
                        isChangePassword: false
                      )
                    }`
        clientTest.MustPost(
            mutation,
            &respond,
        )
        require.True(t, respond["changeCredentialConfirmation"].(bool), "Check your email")
    })
}
Ashwin Shirva
  • 1,331
  • 1
  • 12
  • 31
Weq Iou
  • 233
  • 4
  • 13

0 Answers0