summaryrefslogtreecommitdiff
path: root/template/api/api_test.go
blob: 097a7f5c932979c9186bf2faebe8a2d50b0c28b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package api_test

import (
	"database/sql"
  "io"
	"net/http/httptest"
	"os"
	"strings"
	"testing"

	"git.simponic.xyz/simponic/whois/api"
	"git.simponic.xyz/simponic/whois/args"
	"git.simponic.xyz/simponic/whois/database"
	"git.simponic.xyz/simponic/whois/utils"
)

func setup(t *testing.T) (*sql.DB, *httptest.Server) {
	randomDb := utils.RandomId()

	testDb := database.MakeConn(&randomDb)
	database.Migrate(testDb)

  arguments := &args.Arguments{
    TemplatePath: "../templates",
    StaticPath: "../static",
  }

  mux := api.MakeMux(arguments, testDb)
  testServer := httptest.NewServer(mux)

  t.Cleanup(func() {
		testServer.Close()
		testDb.Close()
		os.Remove(randomDb)
  })
	return testDb, testServer
}

func assertResponseCode(t *testing.T, resp *httptest.ResponseRecorder, statusCode int) {
  if resp.Code != statusCode {
    t.Errorf("code is unexpected: %d, expected %d", resp.Code, statusCode)
  }
}

func assertResponseBody(t *testing.T, resp *httptest.ResponseRecorder, body string) {
  buf := new(strings.Builder)
  _, err := io.Copy(buf, resp.Body)
  if err != nil {
    panic("could not read response body")
  }
  bodyStr := buf.String()
  if bodyStr != body {
    t.Errorf("body is unexpected: %s, expected %s", bodyStr, body)
  }
}

func TestHealthcheck(t *testing.T) {
	_, testServer := setup(t)

  req := httptest.NewRequest("GET", "/health", nil)
  resp := httptest.NewRecorder()
  testServer.Config.Handler.ServeHTTP(resp, req)

  assertResponseCode(t, resp, 200)
  assertResponseBody(t, resp, "healthy")
}

func TestHello(t *testing.T) {
	_, testServer := setup(t)

  req := httptest.NewRequest("GET", "/", nil)
  resp := httptest.NewRecorder()
  testServer.Config.Handler.ServeHTTP(resp, req)

  assertResponseCode(t, resp, 200)
}

func TestCachingStaticFiles(t *testing.T) {
	_, testServer := setup(t)

  req := httptest.NewRequest("GET", "/static/css/styles.css", nil)
  resp := httptest.NewRecorder()
  testServer.Config.Handler.ServeHTTP(resp, req)

  assertResponseCode(t, resp, 200)
  if resp.Header().Get("Cache-Control") != "public, max-age=3600" {
    t.Errorf("client cache will live indefinitely for static files, which is probably not great! %s", resp.Header().Get("Cache-Control"))
  }
}