From 425557e8bd5668fc60227037b0c886ee92d5e379 Mon Sep 17 00:00:00 2001 From: Alex Bramley Date: Sun, 21 Aug 2011 13:38:12 +0100 Subject: [PATCH] Create a simple mock that implements net.Conn. --- client/irc_test.go | 14 ------ client/mocknetconn_test.go | 98 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 14 deletions(-) delete mode 100644 client/irc_test.go create mode 100644 client/mocknetconn_test.go diff --git a/client/irc_test.go b/client/irc_test.go deleted file mode 100644 index 1571355..0000000 --- a/client/irc_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package client - -import ( - "testing" -) - -// Not really sure what or how to test something that basically requires a -// connection to an IRC server to function, but we need some tests or when this -// is present in the go package tree builds fail hard :-( -func TestIRC(t *testing.T) { - if c := New("test", "test", "Testing IRC"); c == nil { - t.FailNow() - } -} diff --git a/client/mocknetconn_test.go b/client/mocknetconn_test.go new file mode 100644 index 0000000..89fce62 --- /dev/null +++ b/client/mocknetconn_test.go @@ -0,0 +1,98 @@ +package client + +import ( + "net" + "os" + "testing" +) + +type mockNetConn struct { + *testing.T + + In, Out chan string + in, out chan []byte + + closed bool + rt, wt int64 +} + +func MockNetConn(t *testing.T) (*mockNetConn) { + // Our mock connection is a testing object + m := &mockNetConn{T: t} + + // set known values for conn info + m.closed = false + m.rt = 0 + m.wt = 0 + + // buffer input + m.In = make(chan string, 20) + m.in = make(chan []byte) + go func() { + for !m.closed { + m.in <- []byte(<-m.In) + } + }() + + // buffer output + m.Out = make(chan string) + m.out = make(chan []byte, 20) + go func() { + for !m.closed { + m.Out <- string(<-m.out) + } + }() + return m +} + +// Test helper +func (m *mockNetConn) Expect(e string) { + s := <-m.Out + if e + "\r\n" != s { + m.Errorf("Mock connection received unexpected value.\n\t" + + "Expected: %s\n\tGot: %s", e, s) + } +} + +// Implement net.Conn interface +func (m *mockNetConn) Read(b []byte) (int, os.Error) { + s := <-m.in + copy(b, s) + return len(s), nil +} + +func (m *mockNetConn) Write(s []byte) (int, os.Error) { + b := make([]byte, len(s)) + copy(b, s) + m.out <- b + return len(b), nil +} + +func (m *mockNetConn) Close() os.Error { + m.closed = true + return nil +} + +func (m *mockNetConn) LocalAddr() net.Addr { + return &net.IPAddr{net.IPv4(127,0,0,1)} +} + +func (m *mockNetConn) RemoteAddr() net.Addr { + return &net.IPAddr{net.IPv4(127,0,0,1)} +} + +func (m *mockNetConn) SetTimeout(ns int64) os.Error { + m.rt = ns + m.wt = ns + return nil +} + +func (m *mockNetConn) SetReadTimeout(ns int64) os.Error { + m.rt = ns + return nil +} + +func (m *mockNetConn) SetWriteTimeout(ns int64) os.Error { + m.wt = ns + return nil +}