network_ut.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <library/cpp/testing/unittest/registar.h>
  2. #include "network.h"
  3. #include <library/cpp/messagebus/test/helper/fixed_port.h>
  4. using namespace NBus;
  5. using namespace NBus::NPrivate;
  6. using namespace NBus::NTest;
  7. namespace {
  8. int GetSockPort(SOCKET socket) {
  9. sockaddr_storage addr;
  10. Zero(addr);
  11. socklen_t len = sizeof(addr);
  12. int r = ::getsockname(socket, (sockaddr*)&addr, &len);
  13. UNIT_ASSERT(r >= 0);
  14. if (addr.ss_family == AF_INET) {
  15. sockaddr_in* addr_in = (sockaddr_in*)&addr;
  16. return InetToHost(addr_in->sin_port);
  17. } else if (addr.ss_family == AF_INET6) {
  18. sockaddr_in6* addr_in6 = (sockaddr_in6*)&addr;
  19. return InetToHost(addr_in6->sin6_port);
  20. } else {
  21. UNIT_FAIL("unknown AF");
  22. throw 1;
  23. }
  24. }
  25. }
  26. Y_UNIT_TEST_SUITE(Network) {
  27. Y_UNIT_TEST(BindOnPortConcrete) {
  28. if (!IsFixedPortTestAllowed()) {
  29. return;
  30. }
  31. TVector<TBindResult> r = BindOnPort(FixedPort, false).second;
  32. UNIT_ASSERT_VALUES_EQUAL(size_t(2), r.size());
  33. for (TVector<TBindResult>::iterator i = r.begin(); i != r.end(); ++i) {
  34. UNIT_ASSERT_VALUES_EQUAL(i->Addr.GetPort(), GetSockPort(i->Socket->operator SOCKET()));
  35. }
  36. }
  37. Y_UNIT_TEST(BindOnPortRandom) {
  38. TVector<TBindResult> r = BindOnPort(0, false).second;
  39. UNIT_ASSERT_VALUES_EQUAL(size_t(2), r.size());
  40. for (TVector<TBindResult>::iterator i = r.begin(); i != r.end(); ++i) {
  41. UNIT_ASSERT_VALUES_EQUAL(i->Addr.GetPort(), GetSockPort(i->Socket->operator SOCKET()));
  42. UNIT_ASSERT(i->Addr.GetPort() > 0);
  43. }
  44. UNIT_ASSERT_VALUES_EQUAL(r.at(0).Addr.GetPort(), r.at(1).Addr.GetPort());
  45. }
  46. Y_UNIT_TEST(BindOnBusyPort) {
  47. auto r = BindOnPort(0, false);
  48. UNIT_ASSERT_EXCEPTION_CONTAINS(BindOnPort(r.first, false), TSystemError, "failed to bind on port " + ToString(r.first));
  49. }
  50. }