Web API Testing – Fungsi Auth Testing

Setelah handler berhasil kita test, berikutnya fungsi pendukung authentication yang terdapat dalam file cmd/api/auth.go

Pertama kita tambahkan dulu token expired yang digunakan untuk keperluan testing, buka file cmd/api/setup_test.go, lalu tambahkan variable token

package main

import (
	"os"
	"testing"
	"webapp/pkg/repository/dbrepo"
)

var app application
var expiredToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiYXVkIjoiZXhhbXBsZS5jb20iLCJleHAiOjE2NjIzMTU2MDgsImlzcyI6ImV4YW1wbGUuY29tIiwibmFtZSI6IkpvaG4gRG9lIiwic3ViIjoiMSJ9.iuLoqxD5Rlhfso0CfAI5R6_2N2zurR_sMV7jT3616os"

func TestMain(m *testing.M) {
	app.DB = &dbrepo.TestDBRepo{}
	app.Domain = "example.com"
	app.JWTSecret = "2dce505d96a53c5768052ee90f3df2055657518dad489160df9913f66042e160"
	os.Exit(m.Run())
}

Kemudian buat file cmd/api/auth_test.go, berikut code yang kami gunakan untuk melakukan test fungsi-fungsi auth.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
	"webapp/pkg/data"
)

func Test_app_getTokenFromHeaderAndVerify(t *testing.T) {
	testUser := data.User{
		ID:        1,
		FirstName: "Admin",
		LastName:  "User",
		Email:     "admin@example.com",
	}

	tokens, _ := app.generateTokenPair(&testUser)

	var tests = []struct {
		name          string
		token         string
		errorExpected bool
		setHeader     bool
		issuer        string
	}{
		{"valid", fmt.Sprintf("Bearer %s", tokens.Token), false, true, app.Domain},
		{"valid expired", fmt.Sprintf("Bearer %s", expiredToken), true, true, app.Domain},
		{"no header", "", true, false, app.Domain},
		{"invalid token", fmt.Sprintf("Bearer %s1", tokens.Token), true, true, app.Domain},
		{"no bearer", fmt.Sprintf("Bear %s1", tokens.Token), true, true, app.Domain},
		{"three header parts", fmt.Sprintf("Bearer %s 1", tokens.Token), true, true, app.Domain},
		// make sure the next test is the last one to run
		{"wrong issuer", fmt.Sprintf("Bearer %s", tokens.Token), true, true, "anotherdomain.com"},
	}

	for _, e := range tests {
		if e.issuer != app.Domain {
			app.Domain = e.issuer
			tokens, _ = app.generateTokenPair(&testUser)
		}
		req, _ := http.NewRequest("GET", "/", nil)
		if e.setHeader {
			req.Header.Set("Authorization", e.token)
		}

		rr := httptest.NewRecorder()

		_, _, err := app.getTokenFromHeaderAndVerify(rr, req)
		if err != nil && !e.errorExpected {
			t.Errorf("%s: did not expect error, but got one - %s", e.name, err.Error())
		}

		if err == nil && e.errorExpected {
			t.Errorf("%s: expected error, but did not get one", e.name)
		}

		app.Domain = "example.com"
	}
}

Jika kita jalankan test dalam folder cmd/api/, sesuai ekspektasi, test berhasil.

$ go test -v .

=== RUN   Test_app_authenticate
--- PASS: Test_app_authenticate (1.78s)
=== RUN   Test_app_getTokenFromHeaderAndVerify        
--- PASS: Test_app_getTokenFromHeaderAndVerify (0.00s)
PASS
ok      webapp/cmd/api  2.059s

Pada modul selanjutnya kita akan membahas penggunaan middleware dalam API dan membuat testnya.

Sharing is caring:

Leave a Comment