Question

I have a small application, serving connections(like a chat). It catches the connection, grabs login from it, then listens to the data and broadcasts it to each connection, except sender.

The problem is i'm not a very advanced tester and do not know, how this can be tested.

# Handle each connection
def serve(io)
  io.puts("LOGIN\n")
  # Listen for identifier
  user = io.gets.chomp

  ...

  # Add connection to the list
  @mutex.synchronize { @chatters[user] = io }

  # Get and broadcast input until connection returns nil
  loop do

    incoming = io.gets
    broadcast(incoming, io)

  end
end

#Send message out to everyone, but sender
def broadcast(message="", sender)

  # Mutex for safety - GServer uses threads
  @mutex.synchronize do

    @chatters.each do |chatter|

      socket = chatter[1]
      # Do not send to sender
      if sock != sender

        sock.print(message)

      end

    end

  end
end
Was it helpful?

Solution

If you just want to do unit testing, you could use RSpec mocks (or some other mocking framework) to stub your methods and ensure that the logic works the way you expect. If you actually want to drive an integration test, that's a lot more work, and will require that you create a separate reader and writer for the socket so that you can actually test each piece of the conversation independently for expected behavior.

Someone else has apparently blogged about a similar issue to yours. Perhaps that example will help you.

If your question is more about the test cases you should write, instead of about how to test sockets, then you may want to rewrite your question so that answers will be more on-target.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top