LpdMessageDispatcherTest.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "LpdMessageDispatcher.h"
  2. #include <cstring>
  3. #include <sstream>
  4. #include <cppunit/extensions/HelperMacros.h>
  5. #include "TestUtil.h"
  6. #include "Exception.h"
  7. #include "util.h"
  8. #include "LpdMessageDispatcher.h"
  9. #include "SocketCore.h"
  10. #include "BtConstants.h"
  11. namespace aria2 {
  12. class LpdMessageDispatcherTest : public CppUnit::TestFixture {
  13. CPPUNIT_TEST_SUITE(LpdMessageDispatcherTest);
  14. CPPUNIT_TEST(testCreateLpdRequest);
  15. CPPUNIT_TEST(testSendMessage);
  16. CPPUNIT_TEST_SUITE_END();
  17. public:
  18. void testCreateLpdRequest();
  19. void testSendMessage();
  20. };
  21. CPPUNIT_TEST_SUITE_REGISTRATION(LpdMessageDispatcherTest);
  22. void LpdMessageDispatcherTest::testCreateLpdRequest()
  23. {
  24. std::string infoHashString = "cd41c7fdddfd034a15a04d7ff881216e01c4ceaf";
  25. CPPUNIT_ASSERT_EQUAL(
  26. std::string("BT-SEARCH * HTTP/1.1\r\n"
  27. "Host: 239.192.152.143:6771\r\n"
  28. "Port: 6000\r\n"
  29. "Infohash: cd41c7fdddfd034a15a04d7ff881216e01c4ceaf\r\n"
  30. "\r\n\r\n"),
  31. bittorrent::createLpdRequest("239.192.152.143", 6771,
  32. fromHex(infoHashString), 6000));
  33. }
  34. void LpdMessageDispatcherTest::testSendMessage()
  35. {
  36. std::shared_ptr<SocketCore> recvsock(new SocketCore(SOCK_DGRAM));
  37. #ifdef __MINGW32__
  38. recvsock->bindWithFamily(LPD_MULTICAST_PORT, AF_INET);
  39. #else // !__MINGW32__
  40. recvsock->bind(LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT, AF_INET);
  41. #endif // !__MINGW32__
  42. recvsock->joinMulticastGroup(LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT, "");
  43. recvsock->setNonBlockingMode();
  44. LpdMessageDispatcher d("cd41c7fdddfd034a15a04d7ff881216e01c4ceaf", 6000,
  45. LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT);
  46. d.init("", 0, 1);
  47. CPPUNIT_ASSERT(d.sendMessage());
  48. unsigned char buf[200];
  49. std::pair<std::string, uint16_t> peer;
  50. ssize_t nbytes;
  51. int trycnt;
  52. for (trycnt = 0; trycnt < 5; ++trycnt) {
  53. nbytes = recvsock->readDataFrom(buf, sizeof(buf), peer);
  54. if (nbytes == 0) {
  55. util::sleep(1);
  56. }
  57. else {
  58. break;
  59. }
  60. }
  61. if (trycnt == 5) {
  62. CPPUNIT_FAIL("[TIMEOUT] No Multicast packet received.");
  63. }
  64. buf[nbytes] = '\0';
  65. std::stringstream temp;
  66. temp << "BT-SEARCH * HTTP/1.1\r\n"
  67. << "Host: " << LPD_MULTICAST_ADDR << ":" << LPD_MULTICAST_PORT << "\r\n"
  68. << "Port: " << d.getPort() << "\r\n"
  69. << "Infohash: " << util::toHex(d.getInfoHash()) << "\r\n"
  70. << "\r\n\r\n";
  71. CPPUNIT_ASSERT_EQUAL(temp.str(), std::string(&buf[0], &buf[nbytes]));
  72. }
  73. } // namespace aria2