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..f17f22232 --- /dev/null +++ b/05_stringer/undrewb/main_test.go @@ -0,0 +1,69 @@ +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, want, got) +} + +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, tt.want, got) + }) + } +}