Skip to content

Instantly share code, notes, and snippets.

@codingconcepts
Created January 4, 2018 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingconcepts/8002f7519afa1755440b49c21bd9a85b to your computer and use it in GitHub Desktop.
Save codingconcepts/8002f7519afa1755440b49c21bd9a85b to your computer and use it in GitHub Desktop.
FizzBuzz web server test
package main
import (
"fmt"
"log"
"net/http"
"strconv"
)
func main() {
log.SetFlags(log.Lshortfile | log.LstdFlags)
http.HandleFunc("/fizzbuzz", fizzbuzz)
log.Print("Server listening. Press CTRL+C to terminate.")
http.ListenAndServe(":1234", nil)
}
func fizzbuzz(w http.ResponseWriter, r *http.Request) {
raw := r.Header.Get("n")
if raw == "" {
http.Error(w, "missing n request header", http.StatusBadRequest)
return
}
n, err := strconv.Atoi(raw)
if err != nil {
http.Error(w, fmt.Sprintf("%q is not a valid number", raw), http.StatusBadRequest)
return
}
if n == 0 {
return
}
for i := 1; i <= n; i++ {
w.Write([]byte(fmt.Sprintf("%s\n", toFizzBuzz(i))))
}
}
func toFizzBuzz(i int) (out string) {
switch {
case i%15 == 0:
return "buzzfizz"
case i%3 == 0:
return "buzz"
case i%5 == 0:
return "fizz"
default:
return strconv.Itoa(i)
}
}
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestToFizzBuzz(t *testing.T) {
cases := []struct {
name string
i int
exp string
}{
{
name: "3",
i: 3,
exp: "buzz",
},
{
name: "5",
i: 5,
exp: "fizz",
},
{
name: "15",
i: 15,
exp: "buzzfizz",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
act := toFizzBuzz(c.i)
if act != c.exp {
t.Fatalf("exp %q but got %q", c.exp, act)
}
})
}
}
func TestFizzBuzz(t *testing.T) {
cases := []struct {
name string
n string
expBody string
expCode int
}{
{
name: "missing request header",
expBody: "missing n request header\n",
expCode: http.StatusBadRequest,
},
{
name: "non-numeric header",
n: "a",
expBody: "\"a\" is not a valid number\n",
expCode: http.StatusBadRequest,
},
{
name: "0",
n: "0",
expCode: http.StatusOK,
},
{
name: "1",
n: "1",
expBody: "1\n",
expCode: http.StatusOK,
},
{
name: "10",
n: "10",
expBody: "1\n2\nbuzz\n4\nfizz\nbuzz\n7\n8\nbuzz\nfizz\n",
expCode: http.StatusOK,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/anything", nil)
if c.n != "" {
req.Header.Set("n", c.n)
}
resp := httptest.NewRecorder()
fizzbuzz(resp, req)
if resp.Code != c.expCode {
t.Fatalf("exp %d but got %d", http.StatusOK, resp.Code)
}
if resp.Body.String() != c.expBody {
t.Fatalf("exp %q but got %q", c.expBody, resp.Body.String())
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment