address_sorter_unittest.cc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/dns/address_sorter.h"
  5. #include "build/build_config.h"
  6. #if BUILDFLAG(IS_WIN)
  7. #include <winsock2.h>
  8. #endif
  9. #include <utility>
  10. #include <vector>
  11. #include "base/bind.h"
  12. #include "base/check.h"
  13. #include "base/test/task_environment.h"
  14. #include "net/base/completion_once_callback.h"
  15. #include "net/base/ip_address.h"
  16. #include "net/base/ip_endpoint.h"
  17. #include "net/base/test_completion_callback.h"
  18. #include "testing/gtest/include/gtest/gtest.h"
  19. #if BUILDFLAG(IS_WIN)
  20. #include "net/base/winsock_init.h"
  21. #endif
  22. namespace net {
  23. namespace {
  24. IPEndPoint MakeEndPoint(const std::string& str) {
  25. IPAddress addr;
  26. CHECK(addr.AssignFromIPLiteral(str));
  27. return IPEndPoint(addr, 0);
  28. }
  29. void OnSortComplete(std::vector<IPEndPoint>* sorted_buf,
  30. CompletionOnceCallback callback,
  31. bool success,
  32. std::vector<IPEndPoint> sorted) {
  33. if (success)
  34. *sorted_buf = std::move(sorted);
  35. std::move(callback).Run(success ? OK : ERR_FAILED);
  36. }
  37. TEST(AddressSorterTest, Sort) {
  38. base::test::TaskEnvironment task_environment;
  39. int expected_result = OK;
  40. #if BUILDFLAG(IS_WIN)
  41. EnsureWinsockInit();
  42. SOCKET sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
  43. if (sock == INVALID_SOCKET) {
  44. expected_result = ERR_FAILED;
  45. } else {
  46. closesocket(sock);
  47. }
  48. #endif
  49. std::unique_ptr<AddressSorter> sorter(AddressSorter::CreateAddressSorter());
  50. std::vector<IPEndPoint> endpoints;
  51. endpoints.push_back(MakeEndPoint("10.0.0.1"));
  52. endpoints.push_back(MakeEndPoint("8.8.8.8"));
  53. endpoints.push_back(MakeEndPoint("::1"));
  54. endpoints.push_back(MakeEndPoint("2001:4860:4860::8888"));
  55. std::vector<IPEndPoint> result;
  56. TestCompletionCallback callback;
  57. sorter->Sort(endpoints,
  58. base::BindOnce(&OnSortComplete, &result, callback.callback()));
  59. EXPECT_EQ(expected_result, callback.WaitForResult());
  60. }
  61. } // namespace
  62. } // namespace net