GO testing/ Testing change email

Viewed 42

I am trying to run GO test, and this part is failing. I am using test for the changeEmail function. I can't really find out what is going on.

func TestChangeEmail(t *testing.T) {
    ctx := context.Background()
    InitTestContext(ctx)

    buf := bytes.Buffer{}
    enc := json.NewEncoder(&buf)
    enc.Encode(testProfile)
    // Create the request object with JWT
    req, err := http.NewRequestWithContext(ctx, "PUT", "http://localhost:8080/v1/profile/", &buf)
    if err != nil {
        t.Fatal(err)
    }

    //  // 1) Create the initial profile

    const sqlSelectAll = `SELECT * FROM "profiles" WHERE email = $1 ORDER BY "profiles"."id" LIMIT 1`
    const sqlCreate = `INSERT INTO "profiles" ("created_at","updated_at","deleted_at","display_name","email","email_verified","id") VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING "id"`
    expected := sqlmock.NewRows([]string{"id", "display_name", "email"}).AddRow(testProfile.ID, testProfile.DisplayName, testProfile.Email)
    mock.ExpectQuery(regexp.QuoteMeta(sqlSelectAll)).WithArgs(testProfile.Email).WillReturnError(fmt.Errorf("not found"))
    mock.ExpectBegin()
    mock.ExpectQuery(regexp.QuoteMeta(sqlCreate)).WithArgs(anyTime{}, anyTime{}, nil, testProfile.DisplayName, testProfile.Email, testProfile.EmailVerified, sqlmock.AnyArg()).WillReturnRows(expected)
    mock.ExpectCommit()

    newEmail := "test-changed@gmail.com"
    //  // 2) Change the initial profile's email
    const sqlUpdate = `UPDATE "profiles" SET "email"=$1 WHERE "email"=$2`
    mock.ExpectBegin()
    mock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).WithArgs(newEmail, testProfile.Email).WillReturnResult(sqlmock.NewResult(0, 1))
    mock.ExpectCommit()

    if err := executeAndValidateRequest(req, http.StatusCreated); err != nil {
        t.Error(err)
    }
}

The error I am getting is --- FAIL: TestChangeEmail (0.00s) 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=0x2 addr=0x18 pc=0x102d2fc94]

This is the stack trace below that LeGEC pointed out. I just wanted to add all the info that I could

goroutine 4 [running]:
testing.tRunner.func1.2({0x1050f65e0, 0x105512000})
    /usr/local/go/src/testing/testing.go:1396 +0x1c8
testing.tRunner.func1()
    /usr/local/go/src/testing/testing.go:1399 +0x378
panic({0x1050f65e0, 0x105512000})
    /usr/local/go/src/runtime/panic.go:884 +0x204
gitlab/developers/server/profile.changeEmail({0x105199db8, 0x14000341e80}, 0x14000374600)
    /Users/example/Documents/project/server/profile/handlers.go:75 +0x44
net/http.HandlerFunc.ServeHTTP(0x14000374500?, {0x105199db8?, 0x14000341e80?}, 0x0?)
    /usr/local/go/src/net/http/server.go:2109 +0x38
github.com/gorilla/mux.(*Router).ServeHTTP(0x1400015a480, {0x105199db8, 0x14000341e80}, 0x14000374400)
    /Users/example/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:210 +0x19c
gitlab/developers/server/profile.executeAndValidateRequest(0x14000247ce0?, 0x12?)
    /Users/example/Documents/project/server/profile/handlers_test.go:134 +0xbc
gitlab/developers/server/profile.TestChangeEmail(0x14000156d00)
    /Users/example/Documents/project/server/profile/handlers_test.go:282 +0x89c
testing.tRunner(0x14000156d00, 0x105191b28)
    /usr/local/go/src/testing/testing.go:1446 +0x10c
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:1493 +0x300
FAIL    gitlab/developers/server/profile    0.145s
FAIL
1 Answers

Together with this error message, you have a stack trace which indicates where your code failed.

Read the stack trace from top to bottom :

  • there are a few frames after the panic, because some code and functions get executed to handle the panic itself,
  • then you see the panic itself :
    panic({0x1050f65e0, 0x105512000})
        /usr/local/go/src/runtime/panic.go:884 +0x204
    
    this code is located in the standard library
  • the line right after will tell you what line triggered the panic :
    gitlab/developers/server/profile.changeEmail({0x105199db8, 0x14000341e80}, 0x14000374600)
        /Users/example/Documents/project/server/profile/handlers.go:75 +0x44
    
    the nil pointer dereference was triggered on that line : server/profile/handlers.go:75
  • you also have the sequence of function calls that lead to the execution of that line
    for example : towards the bottom of the stack, you can see that, in your test function TestChangeEmail(), the call that triggered the error was at handlers_test.go:282, the frame on top of that indicates it was the call to executeAndValidateRequest()

You can now debug your code to see if it is a bug in your project, or something that wasn't initialized in your tests.

Related