Skip to content

Commit

Permalink
Fixing testing examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
ardan-bkennedy committed May 12, 2015

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 60b3878 commit 2e53dc5
Showing 8 changed files with 124 additions and 104 deletions.
4 changes: 2 additions & 2 deletions chapter9/listing01/listing01_test.go
Original file line number Diff line number Diff line change
@@ -30,10 +30,10 @@ func TestDownload(t *testing.T) {
defer resp.Body.Close()

if resp.StatusCode == statusCode {
t.Logf("\t\tShould receive a \"%d\" status code. %v",
t.Logf("\t\tShould receive a \"%d\" status. %v",
statusCode, checkMark)
} else {
t.Errorf("\t\tShould receive a \"%d\" status code. %v %v",
t.Errorf("\t\tShould receive a \"%d\" status. %v %v",
statusCode, ballotX, resp.StatusCode)
}
}
22 changes: 14 additions & 8 deletions chapter9/listing02/listing02_test.go
Original file line number Diff line number Diff line change
@@ -9,15 +9,21 @@ import (
const checkMark = "\u2713"
const ballotX = "\u2717"

// TestDownload validates the http Get function can download content and
// handles different status conditions properly.
// TestDownload validates the http Get function can download
// content and handles different status conditions properly.
func TestDownload(t *testing.T) {
var urls = []struct {
url string
statusCode int
}{
{"http://www.goinggo.net/feeds/posts/default?alt=rss", http.StatusOK},
{"http://rss.cnn.com/rss/cnn_topstorie.rss", http.StatusNotFound},
{
"http://www.goinggo.net/feeds/posts/default?alt=rss",
http.StatusOK,
},
{
"http://rss.cnn.com/rss/cnn_topstorie.rss",
http.StatusNotFound,
},
}

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

defer resp.Body.Close()

if resp.StatusCode == u.statusCode {
t.Logf("\t\tShould receive a \"%d\" status code. %v",
t.Logf("\t\tShould have a \"%d\" status. %v",
u.statusCode, checkMark)
} else {
t.Errorf("\t\tShould receive a \"%d\" status code. %v %v",
t.Errorf("\t\tShould have a \"%d\" status. %v %v",
u.statusCode, ballotX, resp.StatusCode)
}
}
33 changes: 17 additions & 16 deletions chapter9/listing03/listing03_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Sample test to show how to mock an HTTP GET call internally.
// Differs slightly from the book to show more.
package listing03

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

// mockServer returns a pointer to a server to handle the get call.
func mockServer() *httptest.Server {
f := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintln(w, feed)
}

return httptest.NewServer(http.HandlerFunc(f))
}

// Item defines the fields associated with the item tag in
// the buoy RSS document.
type Item struct {
@@ -55,21 +67,10 @@ type Document struct {
URI string
}

// mockServer returns a pointer to a server to handle the mock get call.
func mockServer() *httptest.Server {
f := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintln(w, feed)
}

return httptest.NewServer(http.HandlerFunc(f))
}

// TestDownload validates the http Get function can download content and
// the content can be unmarshaled and clean.
// TestDownload validates the http Get function can download content
// and the content can be unmarshaled and clean.
func TestDownload(t *testing.T) {
statusCode := 200
statusCode := http.StatusOK

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

if resp.StatusCode != statusCode {
t.Fatalf("\t\tShould receive a \"%d\" status code. %v %v",
t.Fatalf("\t\tShould receive a \"%d\" status. %v %v",
statusCode, ballotX, resp.StatusCode)
}
t.Logf("\t\tShould receive a \"%d\" status code. %v",
t.Logf("\t\tShould receive a \"%d\" status. %v",
statusCode, checkMark)

var d Document
54 changes: 0 additions & 54 deletions chapter9/listing04/example04_test.go

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// This sample code implement a simple web service.
package main
package handlers

import (
"encoding/json"
@@ -9,19 +8,6 @@ import (
"strconv"
)

// main is the entry point for the application.
func main() {
Routes()

log.Println("listener : Started : Listening on: http://localhost:4000")
http.ListenAndServe(":4000", nil)
}

// Routes sets the routes for the web service.
func Routes() {
http.HandleFunc("/sendjson", SendJSON)
}

// SendJSON returns a simple JSON document.
func SendJSON(rw http.ResponseWriter, r *http.Request) {
u := struct {
@@ -34,9 +20,10 @@ func SendJSON(rw http.ResponseWriter, r *http.Request) {

data, err := json.Marshal(&u)
if err != nil {
// We want this error condition to panic so we get a stack trace. This should
// never happen. The http package will catch the panic and provide logging
// and return a 500 back to the caller.
// We want this error condition to panic so we get a stack
// trace. This should never happen. The http package will
// catch the panic and provide logging and return a 500 back
// to the caller.
log.Panic("Unable to unmarshal response", err)
}

Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
// Sample test to show how to write a basic example test.
package main_test
package handlers_test

import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
)

// ExampleSendJSON provides a basic example test example.
func ExampleSendJSON() {
log.SetFlags(0)
log.SetOutput(os.Stdout)

r, _ := http.NewRequest("GET", "/sendjson", nil)
w := httptest.NewRecorder()
http.DefaultServeMux.ServeHTTP(w, r)
@@ -28,7 +24,6 @@ func ExampleSendJSON() {
log.Println("ERROR:", err)
}

// Use fmt to write to stdout to check the output.
fmt.Println(u)
// Output:
// {Bill [email protected]}
22 changes: 22 additions & 0 deletions chapter9/listing04/listing04.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// This sample code implement a simple web service.
package main

import (
"log"
"net/http"

"github.com/goinaction/code/chapter9/listing04/handlers"
)

// main is the entry point for the application.
func main() {
Routes()

log.Println("listener : Started : Listening on :4000")
http.ListenAndServe(":4000", nil)
}

// Routes sets the routes for the web service.
func Routes() {
http.HandleFunc("/sendjson", handlers.SendJSON)
}
63 changes: 63 additions & 0 deletions chapter9/listing04/listing04_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Sample test to show how to test the execution of an
// internal endpoint.
package main_test

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

ex "github.com/goinaction/code/chapter9/listing04"
)

const checkMark = "\u2713"
const ballotX = "\u2717"

func init() {
ex.Routes()
}

// TestSendJSON testing the sendjson internal endpoint.
func TestSendJSON(t *testing.T) {
t.Log("Given the need to test the SendJSON endpoint.")
{
r, err := http.NewRequest("GET", "/sendjson", nil)
if err != nil {
t.Fatal("\tShould be able to create a request.",
ballotX, err)
}
t.Log("\tShould be able to create a request.",
checkMark)

w := httptest.NewRecorder()
http.DefaultServeMux.ServeHTTP(w, r)

if w.Code != 200 {
t.Fatal("\tShould receive \"200\"", ballotX, w.Code)
}
t.Log("\tShould receive \"200\"", checkMark)

u := struct {
Name string
Email string
}{}

if err := json.NewDecoder(w.Body).Decode(&u); err != nil {
t.Fatal("\tShould decode the response.", ballotX)
}
t.Log("\tShould decode the response.", checkMark)

if u.Name == "Bill" {
t.Log("\tShould have a Name.", checkMark)
} else {
t.Error("\tShould have a Name.", ballotX, u.Name)
}

if u.Email == "[email protected]" {
t.Log("\tShould have an Email.", checkMark)
} else {
t.Error("\tShould have an for Email.", ballotX, u.Email)
}
}
}

0 comments on commit 2e53dc5

Please sign in to comment.