Skip to content

Commit 2e53dc5

Browse files
Fixing testing examples.
1 parent 60b3878 commit 2e53dc5

8 files changed

Lines changed: 124 additions & 104 deletions

File tree

chapter9/listing01/listing01_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ func TestDownload(t *testing.T) {
3030
defer resp.Body.Close()
3131

3232
if resp.StatusCode == statusCode {
33-
t.Logf("\t\tShould receive a \"%d\" status code. %v",
33+
t.Logf("\t\tShould receive a \"%d\" status. %v",
3434
statusCode, checkMark)
3535
} else {
36-
t.Errorf("\t\tShould receive a \"%d\" status code. %v %v",
36+
t.Errorf("\t\tShould receive a \"%d\" status. %v %v",
3737
statusCode, ballotX, resp.StatusCode)
3838
}
3939
}

chapter9/listing02/listing02_test.go

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,21 @@ import (
99
const checkMark = "\u2713"
1010
const ballotX = "\u2717"
1111

12-
// TestDownload validates the http Get function can download content and
13-
// handles different status conditions properly.
12+
// TestDownload validates the http Get function can download
13+
// content and handles different status conditions properly.
1414
func TestDownload(t *testing.T) {
1515
var urls = []struct {
1616
url string
1717
statusCode int
1818
}{
19-
{"http://www.goinggo.net/feeds/posts/default?alt=rss", http.StatusOK},
20-
{"http://rss.cnn.com/rss/cnn_topstorie.rss", http.StatusNotFound},
19+
{
20+
"http://www.goinggo.net/feeds/posts/default?alt=rss",
21+
http.StatusOK,
22+
},
23+
{
24+
"http://rss.cnn.com/rss/cnn_topstorie.rss",
25+
http.StatusNotFound,
26+
},
2127
}
2228

2329
t.Log("Given the need to test downloading different content.")
@@ -28,19 +34,19 @@ func TestDownload(t *testing.T) {
2834
{
2935
resp, err := http.Get(u.url)
3036
if err != nil {
31-
t.Fatal("\t\tShould be able to make the Get call.",
37+
t.Fatal("\t\tShould be able to Get the url.",
3238
ballotX, err)
3339
}
34-
t.Log("\t\tShould be able to make the Get call.",
40+
t.Log("\t\tShould be able to Get the url.",
3541
checkMark)
3642

3743
defer resp.Body.Close()
3844

3945
if resp.StatusCode == u.statusCode {
40-
t.Logf("\t\tShould receive a \"%d\" status code. %v",
46+
t.Logf("\t\tShould have a \"%d\" status. %v",
4147
u.statusCode, checkMark)
4248
} else {
43-
t.Errorf("\t\tShould receive a \"%d\" status code. %v %v",
49+
t.Errorf("\t\tShould have a \"%d\" status. %v %v",
4450
u.statusCode, ballotX, resp.StatusCode)
4551
}
4652
}

chapter9/listing03/listing03_test.go

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Sample test to show how to mock an HTTP GET call internally.
2+
// Differs slightly from the book to show more.
23
package listing03
34

45
import (
@@ -28,6 +29,17 @@ var feed = `<?xml version="1.0" encoding="UTF-8"?>
2829
</channel>
2930
</rss>`
3031

32+
// mockServer returns a pointer to a server to handle the get call.
33+
func mockServer() *httptest.Server {
34+
f := func(w http.ResponseWriter, r *http.Request) {
35+
w.WriteHeader(200)
36+
w.Header().Set("Content-Type", "application/xml")
37+
fmt.Fprintln(w, feed)
38+
}
39+
40+
return httptest.NewServer(http.HandlerFunc(f))
41+
}
42+
3143
// Item defines the fields associated with the item tag in
3244
// the buoy RSS document.
3345
type Item struct {
@@ -55,21 +67,10 @@ type Document struct {
5567
URI string
5668
}
5769

58-
// mockServer returns a pointer to a server to handle the mock get call.
59-
func mockServer() *httptest.Server {
60-
f := func(w http.ResponseWriter, r *http.Request) {
61-
w.WriteHeader(200)
62-
w.Header().Set("Content-Type", "application/xml")
63-
fmt.Fprintln(w, feed)
64-
}
65-
66-
return httptest.NewServer(http.HandlerFunc(f))
67-
}
68-
69-
// TestDownload validates the http Get function can download content and
70-
// the content can be unmarshaled and clean.
70+
// TestDownload validates the http Get function can download content
71+
// and the content can be unmarshaled and clean.
7172
func TestDownload(t *testing.T) {
72-
statusCode := 200
73+
statusCode := http.StatusOK
7374

7475
server := mockServer()
7576
defer server.Close()
@@ -90,10 +91,10 @@ func TestDownload(t *testing.T) {
9091
defer resp.Body.Close()
9192

9293
if resp.StatusCode != statusCode {
93-
t.Fatalf("\t\tShould receive a \"%d\" status code. %v %v",
94+
t.Fatalf("\t\tShould receive a \"%d\" status. %v %v",
9495
statusCode, ballotX, resp.StatusCode)
9596
}
96-
t.Logf("\t\tShould receive a \"%d\" status code. %v",
97+
t.Logf("\t\tShould receive a \"%d\" status. %v",
9798
statusCode, checkMark)
9899

99100
var d Document

chapter9/listing04/example04_test.go

Lines changed: 0 additions & 54 deletions
This file was deleted.
Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// This sample code implement a simple web service.
2-
package main
1+
package handlers
32

43
import (
54
"encoding/json"
@@ -9,19 +8,6 @@ import (
98
"strconv"
109
)
1110

12-
// main is the entry point for the application.
13-
func main() {
14-
Routes()
15-
16-
log.Println("listener : Started : Listening on: http://localhost:4000")
17-
http.ListenAndServe(":4000", nil)
18-
}
19-
20-
// Routes sets the routes for the web service.
21-
func Routes() {
22-
http.HandleFunc("/sendjson", SendJSON)
23-
}
24-
2511
// SendJSON returns a simple JSON document.
2612
func SendJSON(rw http.ResponseWriter, r *http.Request) {
2713
u := struct {
@@ -34,9 +20,10 @@ func SendJSON(rw http.ResponseWriter, r *http.Request) {
3420

3521
data, err := json.Marshal(&u)
3622
if err != nil {
37-
// We want this error condition to panic so we get a stack trace. This should
38-
// never happen. The http package will catch the panic and provide logging
39-
// and return a 500 back to the caller.
23+
// We want this error condition to panic so we get a stack
24+
// trace. This should never happen. The http package will
25+
// catch the panic and provide logging and return a 500 back
26+
// to the caller.
4027
log.Panic("Unable to unmarshal response", err)
4128
}
4229

chapter9/listing04/example04_example_test.go renamed to chapter9/listing04/handlers/handlers_example_test.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
// Sample test to show how to write a basic example test.
2-
package main_test
2+
package handlers_test
33

44
import (
55
"encoding/json"
66
"fmt"
77
"log"
88
"net/http"
99
"net/http/httptest"
10-
"os"
1110
)
1211

1312
// ExampleSendJSON provides a basic example test example.
1413
func ExampleSendJSON() {
15-
log.SetFlags(0)
16-
log.SetOutput(os.Stdout)
17-
1814
r, _ := http.NewRequest("GET", "/sendjson", nil)
1915
w := httptest.NewRecorder()
2016
http.DefaultServeMux.ServeHTTP(w, r)
@@ -28,7 +24,6 @@ func ExampleSendJSON() {
2824
log.Println("ERROR:", err)
2925
}
3026

31-
// Use fmt to write to stdout to check the output.
3227
fmt.Println(u)
3328
// Output:
3429

chapter9/listing04/listing04.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// This sample code implement a simple web service.
2+
package main
3+
4+
import (
5+
"log"
6+
"net/http"
7+
8+
"github.com/goinaction/code/chapter9/listing04/handlers"
9+
)
10+
11+
// main is the entry point for the application.
12+
func main() {
13+
Routes()
14+
15+
log.Println("listener : Started : Listening on :4000")
16+
http.ListenAndServe(":4000", nil)
17+
}
18+
19+
// Routes sets the routes for the web service.
20+
func Routes() {
21+
http.HandleFunc("/sendjson", handlers.SendJSON)
22+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Sample test to show how to test the execution of an
2+
// internal endpoint.
3+
package main_test
4+
5+
import (
6+
"encoding/json"
7+
"net/http"
8+
"net/http/httptest"
9+
"testing"
10+
11+
ex "github.com/goinaction/code/chapter9/listing04"
12+
)
13+
14+
const checkMark = "\u2713"
15+
const ballotX = "\u2717"
16+
17+
func init() {
18+
ex.Routes()
19+
}
20+
21+
// TestSendJSON testing the sendjson internal endpoint.
22+
func TestSendJSON(t *testing.T) {
23+
t.Log("Given the need to test the SendJSON endpoint.")
24+
{
25+
r, err := http.NewRequest("GET", "/sendjson", nil)
26+
if err != nil {
27+
t.Fatal("\tShould be able to create a request.",
28+
ballotX, err)
29+
}
30+
t.Log("\tShould be able to create a request.",
31+
checkMark)
32+
33+
w := httptest.NewRecorder()
34+
http.DefaultServeMux.ServeHTTP(w, r)
35+
36+
if w.Code != 200 {
37+
t.Fatal("\tShould receive \"200\"", ballotX, w.Code)
38+
}
39+
t.Log("\tShould receive \"200\"", checkMark)
40+
41+
u := struct {
42+
Name string
43+
Email string
44+
}{}
45+
46+
if err := json.NewDecoder(w.Body).Decode(&u); err != nil {
47+
t.Fatal("\tShould decode the response.", ballotX)
48+
}
49+
t.Log("\tShould decode the response.", checkMark)
50+
51+
if u.Name == "Bill" {
52+
t.Log("\tShould have a Name.", checkMark)
53+
} else {
54+
t.Error("\tShould have a Name.", ballotX, u.Name)
55+
}
56+
57+
if u.Email == "[email protected]" {
58+
t.Log("\tShould have an Email.", checkMark)
59+
} else {
60+
t.Error("\tShould have an for Email.", ballotX, u.Email)
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)