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

#include "TcpipDeviceTest.h"
#include "tcpipServer.h"
#include "tcpip_device.h"

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

enum { TestPort = 9625 };


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

  int id = tcpip_open("127.0.0.1", TestPort);
  CPPUNIT_ASSERT(id >= 0);

  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;
  //int id = tcpip_open("localhost", TestPort);
  int id = tcpip_open("127.0.0.1", 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());
  tcpip_send(id, "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);

  // サーバから送信
  server_socket->send("b", 1);
  int n = tcpip_recv(id, &ch, 1, 0);
  CPPUNIT_ASSERT_EQUAL(1, n);
  CPPUNIT_ASSERT_EQUAL('b', ch);
}


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

  int id = tcpip_open("127.0.0.1", TestPort);

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

  // タイムアウトするか
  char ch;
  int n = tcpip_recv(id, &ch, 1, 1);
  CPPUNIT_ASSERT_EQUAL(0, n);

  // 再受信
  server_socket->send("b", 1);
  n = tcpip_recv(id, &ch, 1, 1);
  CPPUNIT_ASSERT_EQUAL(1, n);
  CPPUNIT_ASSERT_EQUAL('b', ch);
}
