From d9597d8feacd1f0a3fb9a22ca41f7f401a5145ec Mon Sep 17 00:00:00 2001 From: "Bucknell, Andrew" Date: Mon, 1 Jul 2019 17:56:01 +1000 Subject: [PATCH] Implement lab05 stringer for anz-bank go-course Update test to fix newline issue --- 05_stringer/undrewb/main.go | 19 +++++++++++ 05_stringer/undrewb/main_test.go | 57 ++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 05_stringer/undrewb/main.go create mode 100644 05_stringer/undrewb/main_test.go diff --git a/05_stringer/undrewb/main.go b/05_stringer/undrewb/main.go new file mode 100644 index 000000000..591e3ed41 --- /dev/null +++ b/05_stringer/undrewb/main.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "io" + "os" +) + +var out io.Writer = os.Stdout + +type IPAddr [4]byte + +func (ip IPAddr) String() string { + return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3]) +} + +func main() { + fmt.Fprintln(out, IPAddr{127, 0, 0, 1}) +} diff --git a/05_stringer/undrewb/main_test.go b/05_stringer/undrewb/main_test.go new file mode 100644 index 000000000..c22df0d5e --- /dev/null +++ b/05_stringer/undrewb/main_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "bytes" + "fmt" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMainOutput(t *testing.T) { + var buf bytes.Buffer + out = &buf + + main() + + want := strconv.Quote("127.0.0.1\n") + got := strconv.Quote(buf.String()) + + assert.Equal(t, got, want) +} + +var stringerData = []struct { + name string + input IPAddr + want string +}{ + {name: "localhost", + input: IPAddr{127, 0, 0, 1}, + want: "127.0.0.1"}, + {name: "four octet addr", + input: IPAddr{68, 2, 44, 125}, + want: "68.2.44.125"}, + {name: "three octet addr", + input: IPAddr{68, 2, 125}, + want: "68.2.125.0"}, + {name: "two octet addr", + input: IPAddr{9, 5}, + want: "9.5.0.0"}, + {name: "one octet addr", + input: IPAddr{144}, + want: "144.0.0.0"}, + {name: "empty", + input: IPAddr{}, + want: "0.0.0.0"}, +} + +func TestStringer(t *testing.T) { + for _, tt := range stringerData { + tt := tt + t.Run(tt.name, func(t *testing.T) { + got := fmt.Sprint(tt.input) + assert.Equal(t, got, tt.want) + }) + } +}