views:

93

answers:

3

How to write a program to test another program/script?

I need to test a ruby script that is an echo server; how should I write a program to validate the correct working of the echo server script ?

+1  A: 

You might be interested in Expect and dejaGnu.

rkhayrov
+1  A: 

You could start with something like this for a TCP echo server:

require "socket"

hostname = "localhost"
port = 2000

s = TCPSocket.open(hostname, port)

s.print "something\n"     # was "something"

line = s.gets
line.chop!

if line == "something"
    puts "echo test  passed"
else
    puts "echo test failed: rcvd [#{line}]\n"
end

s.close

Depending of what kind of testing you need, you can grow the test client, use several sockets, multiple threads, a test framework such as Test::Unit, Cucumber ...


EDIT: it works with the following echo server, I just had to add a '\n' to the client data

require 'socket'  

port = 2000

server = TCPServer.open(port)
loop {                         
  client = server.accept
  data = client.gets 
  client.puts data
  client.close
}
philippe
oh sorry, this doesnot work, i tried this client for my echo server.But the concept was the desired one.
matt jack
Well, it works with the server above, I just had to add a `\n` to the exchanged string.
philippe
A: 

Ruby has a built-in unit testing framework called Test::Unit. However, I tend to prefer working with the Rspec BDD framework. Ideally, BDDers like to write the tests before the actual code, but you can certainly write tests after the fact.

Brian