blob: 3524c05221c2fc238c27c4e4ac8fbaf60b5608cd [file] [log] [blame]
Philipp Schrader5562df72022-02-16 20:56:51 -08001package static
2
3import (
4 "fmt"
5 "io/ioutil"
6 "net/http"
7 "testing"
8
9 "github.com/frc971/971-Robot-Code/scouting/webserver/server"
10)
11
12func TestServing(t *testing.T) {
13 cases := []struct {
14 // The path to request from the server.
15 path string
16 // The data that the server is expected to return at the
17 // specified path.
18 expectedData string
19 }{
20 {"/root.txt", "Hello, this is the root page!"},
21 {"/page.txt", "Hello from a page!"},
22 }
23
24 scoutingServer := server.NewScoutingServer()
25 ServePages(scoutingServer, "test_pages")
26 scoutingServer.Start(8080)
27
28 // Go through all the test cases, and run them against the running webserver.
29 for _, c := range cases {
30 dataReceived := getData(c.path, t)
31 if dataReceived != c.expectedData {
32 t.Errorf("Got %q, but expected %q", dataReceived, c.expectedData)
33 }
34 }
35
36 scoutingServer.Stop()
37}
38
Alex Perryb2f76522022-03-30 21:02:05 -070039func TestCache(t *testing.T) {
40 scoutingServer := server.NewScoutingServer()
41 ServePages(scoutingServer, "test_pages")
42 scoutingServer.Start(8080)
43
44 resp, err := http.Get("http://localhost:8080/root.txt")
45 if err != nil {
46 t.Fatalf("Failed to get data ", err)
47 }
48 compareString(resp.Header.Get("Expires"), "Thu, 01 Jan 1970 00:00:00 UTC", t)
49 compareString(resp.Header.Get("Cache-Control"), "no-cache, private, max-age=0", t)
50 compareString(resp.Header.Get("Pragma"), "no-cache", t)
51 compareString(resp.Header.Get("X-Accel-Expires"), "0", t)
52}
53
54func compareString(actual string, expected string, t *testing.T) {
55 if actual != expected {
56 t.Errorf("Expected ", actual, " to equal ", expected)
57 }
58}
59
Philipp Schrader5562df72022-02-16 20:56:51 -080060// Retrieves the data at the specified path. If an error occurs, the test case
61// is terminated and failed.
62func getData(path string, t *testing.T) string {
63 resp, err := http.Get(fmt.Sprintf("http://localhost:8080/%s", path))
64 if err != nil {
65 t.Fatalf("Failed to get data ", err)
66 }
67 // Error out if the return status is anything other than 200 OK.
68 if resp.Status != "200 OK" {
69 t.Fatalf("Received a status code other than 200")
70 }
71 // Read the response body.
72 body, err := ioutil.ReadAll(resp.Body)
73 if err != nil {
74 t.Fatalf("Failed to read body")
75 }
76 // Decode the body and return it.
77 return string(body)
78}