diff options
-rw-r--r-- | chat/chat_test.go | 50 | ||||
-rw-r--r-- | chat/rooms.go | 16 |
2 files changed, 62 insertions, 4 deletions
diff --git a/chat/chat_test.go b/chat/chat_test.go new file mode 100644 index 0000000..b695b44 --- /dev/null +++ b/chat/chat_test.go @@ -0,0 +1,50 @@ +package chat + +import ( + "testing" +) + +func TestJoining(t *testing.T) { + InitRooms(2) + + b1, r1, err := Join("test", "Foo") + if err != nil { + t.Fatalf("Could not join room: %s", err) + } + defer b1.Leave() + + if _, _, err = Join("test", "Foo"); err != NickAlreadyInUse { + t.Fatalf("Got error \"%s\", expected \"%s\"", err, NickAlreadyInUse) + } + + b2, r2, err := Join("test", "Bar") + if err != nil { + t.Fatalf("Could not join room a second time: %s", err) + } + defer b2.Leave() + + // since we joined to the same room, r1 and r2 should be equal + if r1 != r2 { + t.Error("r1 and r2 are not equal") + } + + if _, _, err = Join("test", "Baz"); err != RoomIsFull { + t.Fatalf("Got error \"%s\", expected \"%s\"", err, RoomIsFull) + } +} + +func TestLeaving(t *testing.T) { + InitRooms(10) + + b1, _, err := Join("test", "Foo") + if err != nil { + t.Fatalf("Could not join room: %s", err) + } + + b1.Leave() + + // The room is now empty. It should no longer exist. + if _, ok := rooms["test"]; ok { + t.Error("Room test still exists, although no user is left") + } +} diff --git a/chat/rooms.go b/chat/rooms.go index 1fb831a..1991d77 100644 --- a/chat/rooms.go +++ b/chat/rooms.go @@ -4,16 +4,23 @@ import ( "errors" ) +var ( + NickAlreadyInUse = errors.New("Nickname is already in use") + RoomIsFull = errors.New("Room is full") +) + // Room represents a chatroom. type Room struct { messages chan Message buddies map[string]*Buddy + name string } -func newRoom() (r *Room) { +func newRoom(name string) (r *Room) { r = new(Room) r.messages = make(chan Message) r.buddies = make(map[string]*Buddy) + r.name = name go r.broadcast() return } @@ -26,6 +33,7 @@ func (r *Room) leave(nick string) { delete(r.buddies, nick) if len(r.buddies) == 0 { close(r.messages) + delete(rooms, r.name) } else { r.messages <- Message{ Type: MsgLeave, @@ -65,16 +73,16 @@ func InitRooms(room_limit int) { func Join(room, nick string) (*Buddy, *Room, error) { r, ok := rooms[room] if !ok { - r = newRoom() + r = newRoom(room) rooms[room] = r } if _, there := r.buddies[nick]; there { - return nil, nil, errors.New("Nickname is already in use") + return nil, nil, NickAlreadyInUse } if len(r.buddies) >= perroom { - return nil, nil, errors.New("Room is full") + return nil, nil, RoomIsFull } r.messages <- Message{ |