-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
85 lines (69 loc) · 2.1 KB
/
main_test.go
File metadata and controls
85 lines (69 loc) · 2.1 KB
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
package main
import (
"context"
"net/http"
"os"
"path/filepath"
"testing"
"time"
)
func TestServer(t *testing.T) {
// Create a temporary directory
//nolint:staticcheck // Ignore as we are testing the server
tempDir := os.TempDir()
// Create an "index" directory
indexDirPath := filepath.Join(tempDir, "docs")
if err := os.MkdirAll(indexDirPath, 0600); err != nil {
t.Fatalf("Failed to create directory %s: %v", indexDirPath, err)
}
// Create necessary files
files := []struct {
name string
content string
}{
{"/index.html", "<html><body>Index</body></html>"},
{"/404.html", "<html><body>404 Not Found</body></html>"},
{"/docs.html", "<html><body>Index</body></html>"},
}
for _, file := range files {
filePath := filepath.Join(tempDir, file.name)
if err := os.MkdirAll(filepath.Dir(filePath), 0600); err != nil {
t.Fatalf("Failed to create dir for file %s: %v", file.name, err)
}
if err := os.WriteFile(filePath, []byte(file.content), 0600); err != nil {
t.Fatalf("Failed to write file %s: %v", file.name, err)
}
}
// Set the environment variable for the static file path
t.Setenv("STATIC_DIR_PATH", tempDir)
go main()
time.Sleep(3 * time.Second)
tests := []struct {
path string
statusCode int
}{
{"/", http.StatusOK},
{"/docs", http.StatusOK},
{"/index", http.StatusOK},
{"/index/", http.StatusOK},
{tempDir + "/index.html", http.StatusNotFound},
{"/index.html", http.StatusOK},
{"/nonexistent", http.StatusNotFound},
}
for _, test := range tests {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:8000"+test.path, http.NoBody)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to perform request: %v", err)
}
if resp.StatusCode != test.statusCode {
t.Errorf("Expected status code %v, got %v for path %v", test.statusCode, resp.StatusCode, test.path)
}
_ = resp.Body.Close()
}
_ = os.RemoveAll(tempDir) //nolint:staticcheck // Intentionally removing test temp directory
}