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