Web App Testing – Middleware

Setelah middleware untuk menampilkan IP address user selesai dibuat, pada modul ini kita akan melakukan testing.

Buat file cmd/web/middleware_test.go, lalu masukan kode berikut:

package main

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func Test_application_addIPToContext(t *testing.T) {
	tests := []struct {
		headerName   string
		heaaderValue string
		addr         string
		emptyaddr    bool
	}{
		{"", "", "", false},
		{"", "", "", true},
		{"X-Forwarded-For", "192.163.1.3", "", false},
		{"", "", "hello:skillplus", false},
	}

	var app application

	//create dummy handler
	nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		//check whether value exists in the context
		val := r.Context().Value(contextUserKey)
		if val == nil {
			t.Error(contextUserKey, "not present")
		}

		//make sure get the string back
		ip, ok := val.(string)
		if !ok {
			t.Error("not string")
		}
		t.Log(ip)
	})

	for _, e := range tests {
		//create handler for test
		handlerToTest := app.addIPToContext(nextHandler)

		req := httptest.NewRequest("GET", "http://testing/", nil)

		if e.emptyaddr {
			req.RemoteAddr = ""
		}

		if len(e.headerName) > 0 {
			req.Header.Add(e.headerName, e.heaaderValue)
		}

		if len(e.addr) > 0 {
			req.RemoteAddr = e.addr
		}

		handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
	}
}

func Test_application_ipFromContext(t *testing.T) {
	//create app var
	var app application

	//get a context
	ctx := context.Background()

	//put somtehing in the context
	ctx = context.WithValue(ctx, contextUserKey, "random")

	//call the function
	ip := app.ipFromContext(ctx)

	//perform test
	if !strings.EqualFold("random", ip) {
		t.Error("wrong value returned from context")
	}
}

Jika kita jalankan test dengan option verbose, sesuai ekspektasi, test berhasil.

$ go test -v ./...

=== RUN   Test_application_handlers
--- PASS: Test_application_handlers (0.04s)      
=== RUN   Test_application_addIPToContext        
    middleware_test.go:39: 192.0.2.1
    middleware_test.go:39: unknown
    middleware_test.go:39: 192.163.1.3
    middleware_test.go:39: hello
--- PASS: Test_application_addIPToContext (0.00s)
=== RUN   Test_application_ipFromContext
--- PASS: Test_application_ipFromContext (0.00s) 
=== RUN   Test_application_routes
--- PASS: Test_application_routes (0.00s)        
PASS
ok      webapp/cmd/web  (cached)
Sharing is caring:

Leave a Comment