aboutsummaryrefslogtreecommitdiff
path: root/utils_test.go
blob: 5eaf0bae4356c6108e44e25563820f41db6c599f (plain) (blame)
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
package main

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/net/html"
)

// TempFile persists contents and returns the path and a clean func
func TempFile(t *testing.T, contents string) (path string, clean func()) {
	content := []byte(contents)
	tmpfile, err := os.CreateTemp("", "sally-tmp")
	if err != nil {
		t.Fatal("Unable to create tmpfile", err)
	}

	if _, err := tmpfile.Write(content); err != nil {
		t.Fatal("Unable to write tmpfile", err)
	}
	if err := tmpfile.Close(); err != nil {
		t.Fatal("Unable to close tmpfile", err)
	}

	return tmpfile.Name(), func() {
		_ = os.Remove(tmpfile.Name())
	}
}

// CreateHandlerFromYAML builds the Sally handler from a yaml config string
func CreateHandlerFromYAML(t *testing.T, content string) (handler http.Handler, clean func()) {
	path, clean := TempFile(t, content)

	config, err := Parse(path)
	if err != nil {
		t.Fatalf("Unable to parse %s: %v", path, err)
	}

	return CreateHandler(config), clean
}

// CallAndRecord makes a GET request to the Sally handler and returns a response recorder
func CallAndRecord(t *testing.T, config string, uri string) *httptest.ResponseRecorder {
	handler, clean := CreateHandlerFromYAML(t, config)
	defer clean()

	req, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		t.Fatalf("Unable to create request to %s: %v", uri, err)
	}

	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	return rr
}

// AssertResponse normalizes and asserts the body from rr against want
func AssertResponse(t *testing.T, rr *httptest.ResponseRecorder, code int, want string) {
	assert.Equal(t, rr.Code, code)
	assert.Equal(t, reformatHTML(t, want), reformatHTML(t, rr.Body.String()))
}

func reformatHTML(t *testing.T, s string) string {
	n, err := html.Parse(strings.NewReader(s))
	require.NoError(t, err)

	var buff bytes.Buffer
	require.NoError(t, html.Render(&buff, n))
	return buff.String()
}