summaryrefslogtreecommitdiff
path: root/contrib/cgi/cgi_test.go
blob: c265050329424dbbaf431bbc2b9313317b073068 (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
package cgi_test

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"strconv"
	"strings"
	"testing"

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

	"tildegit.org/tjp/gus"
	"tildegit.org/tjp/gus/contrib/cgi"
	"tildegit.org/tjp/gus/gemini"
)

func TestCGIDirectory(t *testing.T) {
	tlsconf, err := gemini.FileTLS("testdata/server.crt", "testdata/server.key")
	require.Nil(t, err)

	handler := cgi.CGIDirectory("/cgi-bin", "./testdata")
	server, err := gemini.NewServer(context.Background(), nil, tlsconf, "tcp", "127.0.0.1:0", handler)
	require.Nil(t, err)

	go func() { assert.Nil(t, server.Serve()) }()
	defer server.Close()

	tests := []struct {
		requestPath  string
		responseCode gus.Status
		responseBody string
	}{
		{
			requestPath:  "/cgi-bin/hello_world",
			responseCode: gemini.StatusSuccess,
			responseBody: "hello, world!\n",
		},
		{
			requestPath:  "/cgi-bin/server.key",
			responseCode: gemini.StatusNotFound,
		},
		{
			requestPath:  "/cgi-bin/non-existent",
			responseCode: gemini.StatusNotFound,
		},
		{
			requestPath:  "/cgi-bin/fails",
			responseCode: gemini.StatusCGIError,
		},
	}

	for _, test := range tests {
		t.Run(test.requestPath, func(t *testing.T) {
			conn, err := tls.Dial(
				server.Network(),
				server.Address(),
				&tls.Config{InsecureSkipVerify: true},
			)
			require.Nil(t, err)

			_, err = fmt.Fprintf(conn, "gemini://%s%s\r\n", server.Address(), test.requestPath)
			require.Nil(t, err)

			response, err := io.ReadAll(conn)
			require.Nil(t, err)

			code, err := strconv.Atoi(string(response[:2]))
			if assert.Nil(t, err) {
				assert.Equal(t, test.responseCode, gus.Status(code))
			}

			_, body, found := strings.Cut(string(response), "\r\n")
			if assert.True(t, found) && test.responseBody != "" {
				assert.Equal(t, test.responseBody, body)
			}
		})
	}
}