forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
76 lines (64 loc) · 1.73 KB
/
main_test.go
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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Tests for the sample program to show how to apply basic
// authentication to your web request.
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestIndexHandler(t *testing.T) {
tests := []struct {
Username string
Password string
Want string
StatusCode int
}{
{"username", "password", "Welcome Authorized User!", http.StatusOK},
{"username", "badpassword", "Not authorized", http.StatusUnauthorized},
{"badusername", "badpassword", "Not authorized", http.StatusUnauthorized},
{"", "", "Not authorized", http.StatusUnauthorized},
}
// Start a server to handle these requests.
ts := httptest.NewServer(App())
defer ts.Close()
for _, tt := range tests {
// Create a new request for the GET call.
req, err := http.NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatal(err)
}
// Only apply the credentials if we have them.
if tt.Username != "" {
// Set the username and password into the request.
req.SetBasicAuth(tt.Username, tt.Password)
}
// Create a Client and perform the GET call.
var c http.Client
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != tt.StatusCode {
t.Log("Wanted:", tt.StatusCode)
t.Log("Got :", res.StatusCode)
t.Fatal("Mismatch")
}
// Read in the response from the api call.
b, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
// Validate we received the expected response.
got := strings.TrimSpace(string(b))
want := tt.Want
if got != want {
t.Log("Wanted:", want)
t.Log("Got :", got)
t.Fatal("Mismatch")
}
}
}