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

require 'runit/testcase'
require 'socket'

$stdout.sync = true

$skkserv_hostname = "fine"
$skkserv_port = 21178
$skkserv_version = "2.94.12"
class SKKServTest <RUNIT::TestCase
  def setup
    @socket = TCPSocket.open($skkserv_hostname, $skkserv_port)
  end

  def client_end
    @socket.write("0")
  end

  def 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 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 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 client_unknown
    @socket.write("9hoge")
  end

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

  def test_client_request_success
    client_request_success
    client_end
  end

  def test_client_request_failure
    client_request_failure
    client_end
  end

  def test_client_version
    client_version
    client_end
  end

  def test_client_host
    client_host
    client_end
  end

  def test_client_unknown
    client_unknown
    client_end
  end

  def test_request_after_end
    error = false
    begin
      client_end
      client_request_success
    rescue EOFError, Errno::EPIPE
      error = true
    end
    assert(error, "should raise EOFError or EPIPE.")
  end

  def tear_down
    @socket.shutdown
    @socket.close
  end

end

if __FILE__ == $0
  require 'runit/cui/testrunner'
  RUNIT::CUI::TestRunner.run(SKKServTest.suite)
end

# test/skkserv.rb ends here
