# test/skkserv.rb --- test unit for communicate skkserv.rb process

require 'socket'
require 'test/unit/testcase'

$stdout.sync = true

$skkserv_hostname = "localhost"
$skkserv_port = 21178
$skkserv_version = File.open("configure.in") {|f|
  f.grep(/^VERSION=(.+)$/) do $1 end
}[0]
class TestSKKServ <Test::Unit::TestCase
  def setup
    @socket = TCPSocket.open($skkserv_hostname, $skkserv_port)
  end

  def client_end
    @socket.write("0") unless @socket.closed?
  end

  def test_client_request_success
    @socket.write("1ぎおん ")
    assert_equal("1/祇園/擬音/\n", @socket.sysread(1024))
    @socket.write("1あお ")
    assert_equal("1/青/蒼/碧/靜/襖/\n", @socket.sysread(1024))
    @socket.write("1あお\n")
    assert_equal("1/青/蒼/碧/靜/襖/\n", @socket.sysread(1024))
    @socket.write("10698585 ")
    assert_equal("1/北海道情報大学 @ 北海道江別市西野幌５９番地２号/\n",
		 @socket.sysread(1024))
    @socket.write("1やはr ")
    assert_equal("1/柔/軟/和/矢張/\n", @socket.sysread(1024))
  end

  def test_client_request_failure
    @socket.write("1もげ ")
    assert_equal("4もげ ", @socket.sysread(1024))
    @socket.write("1ふげ\n")
    assert_equal("4ふげ\n", @socket.sysread(1024))
    @socket.write("1\001\001 ")
    assert_equal("4\001\001 ", @socket.sysread(1024))
  end

  def test_client_version
    @socket.write("2")
    assert_equal("rskkserv-#{$skkserv_version} ", @socket.sysread(1024))
    @socket.write("2hogemoge")
    assert_equal("rskkserv-#{$skkserv_version} ", @socket.sysread(1024))
  end

  def test_client_unknown
    @socket.write("9hoge")
  end

  def test_client_host
    @socket.write("3")
    assert_equal($skkserv_hostname + ":" << TCPSocket.getaddress($skkserv_hostname) << ": ", @socket.sysread(1024))
  end

  def test_request_after_end
    client_end
    assert_raises(EOFError) do
      @socket.sysread(1024)
    end
  end

  def tear_down
    client_end
    @socket.shutdown
    @socket.close
  end
end

if __FILE__ == $0
  require 'test/unit/ui/console/testrunner'
  Test::Unit::UI::Console::TestRunner.run(TestSKKServ.suite)
end

# test/skkserv.rb ends here
