forked from eficode-academy/go-roman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_test.go
72 lines (62 loc) · 2.26 KB
/
http_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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
. "testing"
)
func TestRomanOne(t *T) {
// We first create the http.Handler we wish to test
n := romanGenerator(1)
// We create an http.Request object to test with. The http.Request is
// totally customizable in every way that a real-life http request is, so
// even the most intricate behavior can be tested
r, _ := http.NewRequest("GET", "/roman/?number=1", nil)
// httptest.Recorder implements the http.ResponseWriter interface, and as
// such can be passed into ServeHTTP to receive the response. It will act as
// if all data being given to it is being sent to a real client, when in
// reality it's being buffered for later observation
w := httptest.NewRecorder()
// Pass in our httptest.Recorder and http.Request to our numberDumper. At
// this point the numberDumper will act just as if it was responding to a
// real request
n.ServeHTTP(w, r)
// httptest.Recorder gives a number of fields and methods which can be used
// to observe the response made to our request. Here we check the response
// code
if w.Code != 200 {
t.Fatalf("wrong code returned: %d", w.Code)
}
// We can also get the full body out of the httptest.Recorder, and check
// that its contents are what we expect
body := w.Body.String()
if body != fmt.Sprintf("Here's your number: I\n") {
t.Fatalf("wrong body returned: %s", body)
}
}
func TestRomanTwo(t *T) {
n := romanGenerator(1)
r, _ := http.NewRequest("GET", "/roman/?number=2", nil)
w := httptest.NewRecorder()
n.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("wrong code returned: %d", w.Code)
}
body := w.Body.String()
if body != fmt.Sprintf("Here's your number: II\n") {
t.Fatalf("wrong body returned: %s", body)
}
}
func TestRomanNoNumber(t *T) {
n := romanGenerator(1)
r, _ := http.NewRequest("GET", "/roman/", nil)
w := httptest.NewRecorder()
n.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("wrong code returned: %d", w.Code)
}
body := w.Body.String()
if body != fmt.Sprintf("Please pass the number as parameter in the URL") {
t.Fatalf("wrong body returned: %s", body)
}
}