SocketCoreTest.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "SocketCore.h"
  2. #include "Exception.h"
  3. #include <iostream>
  4. #include <cppunit/extensions/HelperMacros.h>
  5. namespace aria2 {
  6. class SocketCoreTest:public CppUnit::TestFixture {
  7. CPPUNIT_TEST_SUITE(SocketCoreTest);
  8. CPPUNIT_TEST(testWriteAndReadDatagram);
  9. CPPUNIT_TEST_SUITE_END();
  10. public:
  11. void setUp() {}
  12. void tearDown() {}
  13. void testWriteAndReadDatagram();
  14. };
  15. CPPUNIT_TEST_SUITE_REGISTRATION(SocketCoreTest);
  16. void SocketCoreTest::testWriteAndReadDatagram()
  17. {
  18. try {
  19. SocketCore s(SOCK_DGRAM);
  20. s.bind(0);
  21. SocketCore c(SOCK_DGRAM);
  22. c.bind(0);
  23. std::pair<std::string, int32_t> svaddr;
  24. s.getAddrInfo(svaddr);
  25. std::string message1 = "hello world.";
  26. c.writeData(message1.c_str(), message1.size(), "localhost", svaddr.second);
  27. std::string message2 = "chocolate coated pie";
  28. c.writeData(message2.c_str(), message2.size(), "localhost", svaddr.second);
  29. char readbuffer[100];
  30. std::pair<std::string, uint16_t> peer;
  31. {
  32. ssize_t rlength = s.readDataFrom(readbuffer, sizeof(readbuffer), peer);
  33. // commented out because ip address may vary
  34. //CPPUNIT_ASSERT_EQUAL(std::std::string("127.0.0.1"), peer.first);
  35. CPPUNIT_ASSERT_EQUAL((ssize_t)message1.size(), rlength);
  36. readbuffer[rlength] = '\0';
  37. CPPUNIT_ASSERT_EQUAL(message1, std::string(readbuffer));
  38. }
  39. {
  40. ssize_t rlength = s.readDataFrom(readbuffer, sizeof(readbuffer), peer);
  41. CPPUNIT_ASSERT_EQUAL((ssize_t)message2.size(), rlength);
  42. readbuffer[rlength] = '\0';
  43. CPPUNIT_ASSERT_EQUAL(message2, std::string(readbuffer));
  44. }
  45. } catch(Exception* e) {
  46. std::cerr << *e << std::endl;
  47. delete e;
  48. CPPUNIT_FAIL("exception thrown");
  49. }
  50. }
  51. } // namespace aria2