/*
  tcpipDevice.cpp のテスト
  Satofumi KAMIMURA
  $Id: TcpipDeviceTest.cpp 286 2008-10-20 09:40:22Z satofumi $
*/

#include "TcpipDeviceTest.h"
#include "tcpipServer.h"
#include <memory>

CPPUNIT_TEST_SUITE_REGISTRATION(TcpipDeviceTest);
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(TcpipDeviceTest, "TcpipDeviceTest");

enum { TestPort = 9625 };


void TcpipDeviceTest::connectionTest(void) {
  TcpipServer server;
  server.activate(TestPort);

  TcpipDevice client;
  int ret_value = client.connect("localhost", TestPort);
  CPPUNIT_ASSERT_EQUAL(0, ret_value);

  std::auto_ptr<TcpipDevice> server_socket(server.accept());
  CPPUNIT_ASSERT_EQUAL(true, server_socket->isConnected());
}


void TcpipDeviceTest::transmitTest(void) {
  TcpipServer server;
  server.activate(TestPort);

  TcpipDevice client;
  client.connect("localhost", TestPort);

  // 接続確認
  std::auto_ptr<TcpipDevice> server_socket(server.accept());
  CPPUNIT_ASSERT_EQUAL(true, server_socket->isConnected());

  // クライアントから送信
  CPPUNIT_ASSERT_EQUAL(0, server_socket->checkSocket());
  CPPUNIT_ASSERT_EQUAL(0, server_socket->size());
  client.send("a", 1);
  CPPUNIT_ASSERT_EQUAL(1, server_socket->checkSocket());
  CPPUNIT_ASSERT_EQUAL(1, server_socket->size());

  char ch;
  server_socket->recv(&ch, 1);
  CPPUNIT_ASSERT_EQUAL('a', ch);

  // サーバから送信
  CPPUNIT_ASSERT_EQUAL(0, client.checkSocket());
  CPPUNIT_ASSERT_EQUAL(0, client.size());
  server_socket->send("b", 1);
  CPPUNIT_ASSERT_EQUAL(1, client.checkSocket());
  CPPUNIT_ASSERT_EQUAL(1, client.size());

  client.recv(&ch, 1);
  CPPUNIT_ASSERT_EQUAL('b', ch);
}


void TcpipDeviceTest::timeoutTest(void) {

  TcpipServer server;
  server.activate(TestPort);

  TcpipDevice client;
  client.connect("localhost", TestPort);

  std::auto_ptr<TcpipDevice> server_socket(server.accept());
  CPPUNIT_ASSERT_EQUAL(true, server_socket->isConnected());

  // タイムアウトするか
  char ch;
  client.recv(&ch, 1);
  CPPUNIT_ASSERT_EQUAL(0, client.size());

  // 再受信
  server_socket->send("b", 1);
  CPPUNIT_ASSERT_EQUAL(1, client.size());
  client.recv(&ch, 1);
  CPPUNIT_ASSERT_EQUAL('b', ch);
}
