summaryrefslogtreecommitdiff
path: root/contrib/fs/file_test.go
blob: ce4d023d8ea1f82a298b7bbfd906c8c84b52be2c (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
package fs_test

import (
	"context"
	"io"
	"net/url"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/contrib/fs"
	"tildegit.org/tjp/sliderule/gemini"
)

func TestFileHandler(t *testing.T) {
	handler := fs.GeminiFileHandler("testdata", "")

	tests := []struct {
		url    string
		status sr.Status
		meta   string
		body   string
	}{
		{
			url:    "gemini://localhost/d",
			status: gemini.StatusNotFound,
		},
		{
			url:    "gemini://localhost/d/",
			status: gemini.StatusNotFound,
		},
		{
			url:    "gemini://localhost/d/index.gmi",
			status: gemini.StatusSuccess,
			meta:   "text/gemini",
			body:   "# This is d\n",
		},
		{
			url:    "gemini://localhost/a/b",
			status: gemini.StatusSuccess,
			meta:   "application/octet-stream",
			body:   "this is file b\n",
		},
		{
			url:    "gemini://localhost/a/c.html",
			status: gemini.StatusSuccess,
			meta:   "text/html; charset=utf-8",
			body:   "",
		},
	}

	for _, test := range tests {
		t.Run(test.url, func(t *testing.T) {
			u, err := url.Parse(test.url)
			require.Nil(t, err)

			request := &sr.Request{URL: u}
			response := handler.Handle(context.Background(), request)

			if response == nil {
				assert.Equal(t, test.status, gemini.StatusNotFound)
				return
			} else {
				assert.Equal(t, test.status, response.Status)
			}

			if test.meta != "" {
				assert.Equal(t, test.meta, response.Meta)
			}
			if test.body != "" {
				body, err := io.ReadAll(response.Body)
				require.Nil(t, err)
				assert.Equal(t, test.body, string(body))
			}
		})
	}
}