blob: 15bd872bb1d7a866dfda8c4b3704a04bd901ac10 [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
39// Retrieves the data at the specified path. If an error occurs, the test case
40// is terminated and failed.
41func getData(path string, t *testing.T) string {
42 resp, err := http.Get(fmt.Sprintf("http://localhost:8080/%s", path))
43 if err != nil {
44 t.Fatalf("Failed to get data ", err)
45 }
46 // Error out if the return status is anything other than 200 OK.
47 if resp.Status != "200 OK" {
48 t.Fatalf("Received a status code other than 200")
49 }
50 // Read the response body.
51 body, err := ioutil.ReadAll(resp.Body)
52 if err != nil {
53 t.Fatalf("Failed to read body")
54 }
55 // Decode the body and return it.
56 return string(body)
57}