Don't add an aura tooltip to bubble close buttons on Windows.
[chromium-blink-merge.git] / net / dns / host_resolver_impl_unittest.cc
blobd71db2f1c2243cca86a03f02ace35d7a945a9808
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.
5 #include "net/dns/host_resolver_impl.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/synchronization/condition_variable.h"
19 #include "base/synchronization/lock.h"
20 #include "base/test/test_timeouts.h"
21 #include "base/time/time.h"
22 #include "net/base/address_list.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/dns/dns_client.h"
26 #include "net/dns/dns_test_util.h"
27 #include "net/dns/mock_host_resolver.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 namespace net {
32 namespace {
34 const size_t kMaxJobs = 10u;
35 const size_t kMaxRetryAttempts = 4u;
37 HostResolver::Options DefaultOptions() {
38 HostResolver::Options options;
39 options.max_concurrent_resolves = kMaxJobs;
40 options.max_retry_attempts = kMaxRetryAttempts;
41 options.enable_caching = true;
42 return options;
45 HostResolverImpl::ProcTaskParams DefaultParams(
46 HostResolverProc* resolver_proc) {
47 return HostResolverImpl::ProcTaskParams(resolver_proc, kMaxRetryAttempts);
50 // A HostResolverProc that pushes each host mapped into a list and allows
51 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
52 // it never calls SystemHostResolverCall. By default resolves all hostnames to
53 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
54 class MockHostResolverProc : public HostResolverProc {
55 public:
56 struct ResolveKey {
57 ResolveKey(const std::string& hostname, AddressFamily address_family)
58 : hostname(hostname), address_family(address_family) {}
59 bool operator<(const ResolveKey& other) const {
60 return address_family < other.address_family ||
61 (address_family == other.address_family && hostname < other.hostname);
63 std::string hostname;
64 AddressFamily address_family;
67 typedef std::vector<ResolveKey> CaptureList;
69 MockHostResolverProc()
70 : HostResolverProc(NULL),
71 num_requests_waiting_(0),
72 num_slots_available_(0),
73 requests_waiting_(&lock_),
74 slots_available_(&lock_) {
77 // Waits until |count| calls to |Resolve| are blocked. Returns false when
78 // timed out.
79 bool WaitFor(unsigned count) {
80 base::AutoLock lock(lock_);
81 base::Time start_time = base::Time::Now();
82 while (num_requests_waiting_ < count) {
83 requests_waiting_.TimedWait(TestTimeouts::action_timeout());
84 if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
85 return false;
87 return true;
90 // Signals |count| waiting calls to |Resolve|. First come first served.
91 void SignalMultiple(unsigned count) {
92 base::AutoLock lock(lock_);
93 num_slots_available_ += count;
94 slots_available_.Broadcast();
97 // Signals all waiting calls to |Resolve|. Beware of races.
98 void SignalAll() {
99 base::AutoLock lock(lock_);
100 num_slots_available_ = num_requests_waiting_;
101 slots_available_.Broadcast();
104 void AddRule(const std::string& hostname, AddressFamily family,
105 const AddressList& result) {
106 base::AutoLock lock(lock_);
107 rules_[ResolveKey(hostname, family)] = result;
110 void AddRule(const std::string& hostname, AddressFamily family,
111 const std::string& ip_list) {
112 AddressList result;
113 int rv = ParseAddressList(ip_list, std::string(), &result);
114 DCHECK_EQ(OK, rv);
115 AddRule(hostname, family, result);
118 void AddRuleForAllFamilies(const std::string& hostname,
119 const std::string& ip_list) {
120 AddressList result;
121 int rv = ParseAddressList(ip_list, std::string(), &result);
122 DCHECK_EQ(OK, rv);
123 AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result);
124 AddRule(hostname, ADDRESS_FAMILY_IPV4, result);
125 AddRule(hostname, ADDRESS_FAMILY_IPV6, result);
128 int Resolve(const std::string& hostname,
129 AddressFamily address_family,
130 HostResolverFlags host_resolver_flags,
131 AddressList* addrlist,
132 int* os_error) override {
133 base::AutoLock lock(lock_);
134 capture_list_.push_back(ResolveKey(hostname, address_family));
135 ++num_requests_waiting_;
136 requests_waiting_.Broadcast();
137 while (!num_slots_available_)
138 slots_available_.Wait();
139 DCHECK_GT(num_requests_waiting_, 0u);
140 --num_slots_available_;
141 --num_requests_waiting_;
142 if (rules_.empty()) {
143 int rv = ParseAddressList("127.0.0.1", std::string(), addrlist);
144 DCHECK_EQ(OK, rv);
145 return OK;
147 ResolveKey key(hostname, address_family);
148 if (rules_.count(key) == 0)
149 return ERR_NAME_NOT_RESOLVED;
150 *addrlist = rules_[key];
151 return OK;
154 CaptureList GetCaptureList() const {
155 CaptureList copy;
157 base::AutoLock lock(lock_);
158 copy = capture_list_;
160 return copy;
163 bool HasBlockedRequests() const {
164 base::AutoLock lock(lock_);
165 return num_requests_waiting_ > num_slots_available_;
168 protected:
169 ~MockHostResolverProc() override {}
171 private:
172 mutable base::Lock lock_;
173 std::map<ResolveKey, AddressList> rules_;
174 CaptureList capture_list_;
175 unsigned num_requests_waiting_;
176 unsigned num_slots_available_;
177 base::ConditionVariable requests_waiting_;
178 base::ConditionVariable slots_available_;
180 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc);
183 bool AddressListContains(const AddressList& list, const std::string& address,
184 uint16 port) {
185 IPAddressNumber ip;
186 bool rv = ParseIPLiteralToNumber(address, &ip);
187 DCHECK(rv);
188 return std::find(list.begin(),
189 list.end(),
190 IPEndPoint(ip, port)) != list.end();
193 // A wrapper for requests to a HostResolver.
194 class Request {
195 public:
196 // Base class of handlers to be executed on completion of requests.
197 struct Handler {
198 virtual ~Handler() {}
199 virtual void Handle(Request* request) = 0;
202 Request(const HostResolver::RequestInfo& info,
203 RequestPriority priority,
204 size_t index,
205 HostResolver* resolver,
206 Handler* handler)
207 : info_(info),
208 priority_(priority),
209 index_(index),
210 resolver_(resolver),
211 handler_(handler),
212 quit_on_complete_(false),
213 result_(ERR_UNEXPECTED),
214 handle_(NULL) {}
216 int Resolve() {
217 DCHECK(resolver_);
218 DCHECK(!handle_);
219 list_ = AddressList();
220 result_ = resolver_->Resolve(
221 info_,
222 priority_,
223 &list_,
224 base::Bind(&Request::OnComplete, base::Unretained(this)),
225 &handle_,
226 BoundNetLog());
227 if (!list_.empty())
228 EXPECT_EQ(OK, result_);
229 return result_;
232 int ResolveFromCache() {
233 DCHECK(resolver_);
234 DCHECK(!handle_);
235 return resolver_->ResolveFromCache(info_, &list_, BoundNetLog());
238 void Cancel() {
239 DCHECK(resolver_);
240 DCHECK(handle_);
241 resolver_->CancelRequest(handle_);
242 handle_ = NULL;
245 const HostResolver::RequestInfo& info() const { return info_; }
246 size_t index() const { return index_; }
247 const AddressList& list() const { return list_; }
248 int result() const { return result_; }
249 bool completed() const { return result_ != ERR_IO_PENDING; }
250 bool pending() const { return handle_ != NULL; }
252 bool HasAddress(const std::string& address, uint16 port) const {
253 return AddressListContains(list_, address, port);
256 // Returns the number of addresses in |list_|.
257 unsigned NumberOfAddresses() const {
258 return list_.size();
261 bool HasOneAddress(const std::string& address, uint16 port) const {
262 return HasAddress(address, port) && (NumberOfAddresses() == 1u);
265 // Returns ERR_UNEXPECTED if timed out.
266 int WaitForResult() {
267 if (completed())
268 return result_;
269 base::CancelableClosure closure(base::MessageLoop::QuitClosure());
270 base::MessageLoop::current()->PostDelayedTask(
271 FROM_HERE, closure.callback(), TestTimeouts::action_max_timeout());
272 quit_on_complete_ = true;
273 base::MessageLoop::current()->Run();
274 bool did_quit = !quit_on_complete_;
275 quit_on_complete_ = false;
276 closure.Cancel();
277 if (did_quit)
278 return result_;
279 else
280 return ERR_UNEXPECTED;
283 private:
284 void OnComplete(int rv) {
285 EXPECT_TRUE(pending());
286 EXPECT_EQ(ERR_IO_PENDING, result_);
287 EXPECT_NE(ERR_IO_PENDING, rv);
288 result_ = rv;
289 handle_ = NULL;
290 if (!list_.empty()) {
291 EXPECT_EQ(OK, result_);
292 EXPECT_EQ(info_.port(), list_.front().port());
294 if (handler_)
295 handler_->Handle(this);
296 if (quit_on_complete_) {
297 base::MessageLoop::current()->Quit();
298 quit_on_complete_ = false;
302 HostResolver::RequestInfo info_;
303 RequestPriority priority_;
304 size_t index_;
305 HostResolver* resolver_;
306 Handler* handler_;
307 bool quit_on_complete_;
309 AddressList list_;
310 int result_;
311 HostResolver::RequestHandle handle_;
313 DISALLOW_COPY_AND_ASSIGN(Request);
316 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
317 // which attempt resolves the host.
318 class LookupAttemptHostResolverProc : public HostResolverProc {
319 public:
320 LookupAttemptHostResolverProc(HostResolverProc* previous,
321 int attempt_number_to_resolve,
322 int total_attempts)
323 : HostResolverProc(previous),
324 attempt_number_to_resolve_(attempt_number_to_resolve),
325 current_attempt_number_(0),
326 total_attempts_(total_attempts),
327 total_attempts_resolved_(0),
328 resolved_attempt_number_(0),
329 all_done_(&lock_) {
332 // Test harness will wait for all attempts to finish before checking the
333 // results.
334 void WaitForAllAttemptsToFinish(const base::TimeDelta& wait_time) {
335 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
337 base::AutoLock auto_lock(lock_);
338 while (total_attempts_resolved_ != total_attempts_ &&
339 base::TimeTicks::Now() < end_time) {
340 all_done_.TimedWait(end_time - base::TimeTicks::Now());
345 // All attempts will wait for an attempt to resolve the host.
346 void WaitForAnAttemptToComplete() {
347 base::TimeDelta wait_time = base::TimeDelta::FromSeconds(60);
348 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
350 base::AutoLock auto_lock(lock_);
351 while (resolved_attempt_number_ == 0 && base::TimeTicks::Now() < end_time)
352 all_done_.TimedWait(end_time - base::TimeTicks::Now());
354 all_done_.Broadcast(); // Tell all waiting attempts to proceed.
357 // Returns the number of attempts that have finished the Resolve() method.
358 int total_attempts_resolved() { return total_attempts_resolved_; }
360 // Returns the first attempt that that has resolved the host.
361 int resolved_attempt_number() { return resolved_attempt_number_; }
363 // HostResolverProc methods.
364 int Resolve(const std::string& host,
365 AddressFamily address_family,
366 HostResolverFlags host_resolver_flags,
367 AddressList* addrlist,
368 int* os_error) override {
369 bool wait_for_right_attempt_to_complete = true;
371 base::AutoLock auto_lock(lock_);
372 ++current_attempt_number_;
373 if (current_attempt_number_ == attempt_number_to_resolve_) {
374 resolved_attempt_number_ = current_attempt_number_;
375 wait_for_right_attempt_to_complete = false;
379 if (wait_for_right_attempt_to_complete)
380 // Wait for the attempt_number_to_resolve_ attempt to resolve.
381 WaitForAnAttemptToComplete();
383 int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
384 addrlist, os_error);
387 base::AutoLock auto_lock(lock_);
388 ++total_attempts_resolved_;
391 all_done_.Broadcast(); // Tell all attempts to proceed.
393 // Since any negative number is considered a network error, with -1 having
394 // special meaning (ERR_IO_PENDING). We could return the attempt that has
395 // resolved the host as a negative number. For example, if attempt number 3
396 // resolves the host, then this method returns -4.
397 if (result == OK)
398 return -1 - resolved_attempt_number_;
399 else
400 return result;
403 protected:
404 ~LookupAttemptHostResolverProc() override {}
406 private:
407 int attempt_number_to_resolve_;
408 int current_attempt_number_; // Incremented whenever Resolve is called.
409 int total_attempts_;
410 int total_attempts_resolved_;
411 int resolved_attempt_number_;
413 // All attempts wait for right attempt to be resolve.
414 base::Lock lock_;
415 base::ConditionVariable all_done_;
418 } // namespace
420 class HostResolverImplTest : public testing::Test {
421 public:
422 static const int kDefaultPort = 80;
424 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
426 void CreateResolver() {
427 CreateResolverWithLimitsAndParams(kMaxJobs,
428 DefaultParams(proc_.get()));
431 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
432 // perform no retries.
433 void CreateSerialResolver() {
434 HostResolverImpl::ProcTaskParams params = DefaultParams(proc_.get());
435 params.max_retry_attempts = 0u;
436 CreateResolverWithLimitsAndParams(1u, params);
439 protected:
440 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
441 struct Handler : public Request::Handler {
442 ~Handler() override {}
444 // Proxy functions so that classes derived from Handler can access them.
445 Request* CreateRequest(const HostResolver::RequestInfo& info,
446 RequestPriority priority) {
447 return test->CreateRequest(info, priority);
449 Request* CreateRequest(const std::string& hostname, int port) {
450 return test->CreateRequest(hostname, port);
452 Request* CreateRequest(const std::string& hostname) {
453 return test->CreateRequest(hostname);
455 ScopedVector<Request>& requests() { return test->requests_; }
457 void DeleteResolver() { test->resolver_.reset(); }
459 HostResolverImplTest* test;
462 // testing::Test implementation:
463 void SetUp() override { CreateResolver(); }
465 void TearDown() override {
466 if (resolver_.get())
467 EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
468 EXPECT_FALSE(proc_->HasBlockedRequests());
471 virtual void CreateResolverWithLimitsAndParams(
472 size_t max_concurrent_resolves,
473 const HostResolverImpl::ProcTaskParams& params) {
474 HostResolverImpl::Options options = DefaultOptions();
475 options.max_concurrent_resolves = max_concurrent_resolves;
476 resolver_.reset(new HostResolverImpl(options, NULL));
477 resolver_->set_proc_params_for_test(params);
480 // The Request will not be made until a call to |Resolve()|, and the Job will
481 // not start until released by |proc_->SignalXXX|.
482 Request* CreateRequest(const HostResolver::RequestInfo& info,
483 RequestPriority priority) {
484 Request* req = new Request(
485 info, priority, requests_.size(), resolver_.get(), handler_.get());
486 requests_.push_back(req);
487 return req;
490 Request* CreateRequest(const std::string& hostname,
491 int port,
492 RequestPriority priority,
493 AddressFamily family) {
494 HostResolver::RequestInfo info(HostPortPair(hostname, port));
495 info.set_address_family(family);
496 return CreateRequest(info, priority);
499 Request* CreateRequest(const std::string& hostname,
500 int port,
501 RequestPriority priority) {
502 return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED);
505 Request* CreateRequest(const std::string& hostname, int port) {
506 return CreateRequest(hostname, port, MEDIUM);
509 Request* CreateRequest(const std::string& hostname) {
510 return CreateRequest(hostname, kDefaultPort);
513 void set_handler(Handler* handler) {
514 handler_.reset(handler);
515 handler_->test = this;
518 // Friendship is not inherited, so use proxies to access those.
519 size_t num_running_dispatcher_jobs() const {
520 DCHECK(resolver_.get());
521 return resolver_->num_running_dispatcher_jobs_for_tests();
524 void set_fallback_to_proctask(bool fallback_to_proctask) {
525 DCHECK(resolver_.get());
526 resolver_->fallback_to_proctask_ = fallback_to_proctask;
529 static unsigned maximum_dns_failures() {
530 return HostResolverImpl::kMaximumDnsFailures;
533 scoped_refptr<MockHostResolverProc> proc_;
534 scoped_ptr<HostResolverImpl> resolver_;
535 ScopedVector<Request> requests_;
537 scoped_ptr<Handler> handler_;
540 TEST_F(HostResolverImplTest, AsynchronousLookup) {
541 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
542 proc_->SignalMultiple(1u);
544 Request* req = CreateRequest("just.testing", 80);
545 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
546 EXPECT_EQ(OK, req->WaitForResult());
548 EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80));
550 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
553 TEST_F(HostResolverImplTest, LocalhostLookup) {
554 proc_->SignalMultiple(1u);
555 Request* req = CreateRequest("foo.localhost", 80);
556 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
557 EXPECT_EQ(OK, req->WaitForResult());
559 EXPECT_TRUE(req->HasOneAddress("127.0.0.1", 80));
561 EXPECT_EQ("localhost.", proc_->GetCaptureList()[0].hostname);
564 TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) {
565 proc_->AddRuleForAllFamilies("just.testing", "");
566 proc_->SignalMultiple(1u);
568 Request* req = CreateRequest("just.testing", 80);
569 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
570 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
571 EXPECT_EQ(0u, req->NumberOfAddresses());
572 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
575 TEST_F(HostResolverImplTest, FailedAsynchronousLookup) {
576 proc_->AddRuleForAllFamilies(std::string(),
577 "0.0.0.0"); // Default to failures.
578 proc_->SignalMultiple(1u);
580 Request* req = CreateRequest("just.testing", 80);
581 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
582 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
584 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
586 // Also test that the error is not cached.
587 EXPECT_EQ(ERR_DNS_CACHE_MISS, req->ResolveFromCache());
590 TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) {
591 Request* req0 = CreateRequest("just.testing", 80);
592 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
594 EXPECT_TRUE(proc_->WaitFor(1u));
596 // Resolver is destroyed while job is running on WorkerPool.
597 resolver_.reset();
599 proc_->SignalAll();
601 // To ensure there was no spurious callback, complete with a new resolver.
602 CreateResolver();
603 Request* req1 = CreateRequest("just.testing", 80);
604 EXPECT_EQ(ERR_IO_PENDING, req1->Resolve());
606 proc_->SignalMultiple(2u);
608 EXPECT_EQ(OK, req1->WaitForResult());
610 // This request was canceled.
611 EXPECT_FALSE(req0->completed());
614 #if defined(THREAD_SANITIZER)
615 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
616 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
617 #else
618 #define MAYBE_NumericIPv4Address NumericIPv4Address
619 #endif
620 TEST_F(HostResolverImplTest, MAYBE_NumericIPv4Address) {
621 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
622 Request* req = CreateRequest("127.1.2.3", 5555);
623 EXPECT_EQ(OK, req->Resolve());
625 EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555));
628 #if defined(THREAD_SANITIZER)
629 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
630 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
631 #else
632 #define MAYBE_NumericIPv6Address NumericIPv6Address
633 #endif
634 TEST_F(HostResolverImplTest, MAYBE_NumericIPv6Address) {
635 // Resolve a plain IPv6 address. Don't worry about [brackets], because
636 // the caller should have removed them.
637 Request* req = CreateRequest("2001:db8::1", 5555);
638 EXPECT_EQ(OK, req->Resolve());
640 EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555));
643 #if defined(THREAD_SANITIZER)
644 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
645 #define MAYBE_EmptyHost DISABLED_EmptyHost
646 #else
647 #define MAYBE_EmptyHost EmptyHost
648 #endif
649 TEST_F(HostResolverImplTest, MAYBE_EmptyHost) {
650 Request* req = CreateRequest(std::string(), 5555);
651 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
654 #if defined(THREAD_SANITIZER)
655 // There's a data race in this test that may lead to use-after-free.
656 // If the test starts to crash without ThreadSanitizer it needs to be disabled
657 // globally. See http://crbug.com/268946 (stacks for this test in
658 // crbug.com/333567).
659 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
660 #else
661 #define MAYBE_EmptyDotsHost EmptyDotsHost
662 #endif
663 TEST_F(HostResolverImplTest, MAYBE_EmptyDotsHost) {
664 for (int i = 0; i < 16; ++i) {
665 Request* req = CreateRequest(std::string(i, '.'), 5555);
666 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
670 #if defined(THREAD_SANITIZER)
671 // There's a data race in this test that may lead to use-after-free.
672 // If the test starts to crash without ThreadSanitizer it needs to be disabled
673 // globally. See http://crbug.com/268946.
674 #define MAYBE_LongHost DISABLED_LongHost
675 #else
676 #define MAYBE_LongHost LongHost
677 #endif
678 TEST_F(HostResolverImplTest, MAYBE_LongHost) {
679 Request* req = CreateRequest(std::string(4097, 'a'), 5555);
680 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
683 TEST_F(HostResolverImplTest, DeDupeRequests) {
684 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
685 // blocked, these should all pile up until we signal it.
686 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
687 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
688 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
689 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
690 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
692 proc_->SignalMultiple(2u); // One for "a", one for "b".
694 for (size_t i = 0; i < requests_.size(); ++i) {
695 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
699 TEST_F(HostResolverImplTest, CancelMultipleRequests) {
700 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
701 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
702 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
703 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
704 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
706 // Cancel everything except request for ("a", 82).
707 requests_[0]->Cancel();
708 requests_[1]->Cancel();
709 requests_[2]->Cancel();
710 requests_[4]->Cancel();
712 proc_->SignalMultiple(2u); // One for "a", one for "b".
714 EXPECT_EQ(OK, requests_[3]->WaitForResult());
717 TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) {
718 // Fill up the dispatcher and queue.
719 for (unsigned i = 0; i < kMaxJobs + 1; ++i) {
720 std::string hostname = "a_";
721 hostname[1] = 'a' + i;
722 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve());
723 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 81)->Resolve());
726 EXPECT_TRUE(proc_->WaitFor(kMaxJobs));
728 // Cancel all but last two.
729 for (unsigned i = 0; i < requests_.size() - 2; ++i) {
730 requests_[i]->Cancel();
733 EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1));
735 proc_->SignalAll();
737 size_t num_requests = requests_.size();
738 EXPECT_EQ(OK, requests_[num_requests - 1]->WaitForResult());
739 EXPECT_EQ(OK, requests_[num_requests - 2]->result());
742 TEST_F(HostResolverImplTest, CancelWithinCallback) {
743 struct MyHandler : public Handler {
744 void Handle(Request* req) override {
745 // Port 80 is the first request that the callback will be invoked for.
746 // While we are executing within that callback, cancel the other requests
747 // in the job and start another request.
748 if (req->index() == 0) {
749 // Once "a:80" completes, it will cancel "a:81" and "a:82".
750 requests()[1]->Cancel();
751 requests()[2]->Cancel();
755 set_handler(new MyHandler());
757 for (size_t i = 0; i < 4; ++i) {
758 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
761 proc_->SignalMultiple(2u); // One for "a". One for "finalrequest".
763 EXPECT_EQ(OK, requests_[0]->WaitForResult());
765 Request* final_request = CreateRequest("finalrequest", 70);
766 EXPECT_EQ(ERR_IO_PENDING, final_request->Resolve());
767 EXPECT_EQ(OK, final_request->WaitForResult());
768 EXPECT_TRUE(requests_[3]->completed());
771 TEST_F(HostResolverImplTest, DeleteWithinCallback) {
772 struct MyHandler : public Handler {
773 void Handle(Request* req) override {
774 EXPECT_EQ("a", req->info().hostname());
775 EXPECT_EQ(80, req->info().port());
777 DeleteResolver();
779 // Quit after returning from OnCompleted (to give it a chance at
780 // incorrectly running the cancelled tasks).
781 base::MessageLoop::current()->PostTask(FROM_HERE,
782 base::MessageLoop::QuitClosure());
785 set_handler(new MyHandler());
787 for (size_t i = 0; i < 4; ++i) {
788 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
791 proc_->SignalMultiple(1u); // One for "a".
793 // |MyHandler| will send quit message once all the requests have finished.
794 base::MessageLoop::current()->Run();
797 TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) {
798 struct MyHandler : public Handler {
799 void Handle(Request* req) override {
800 EXPECT_EQ("a", req->info().hostname());
801 EXPECT_EQ(80, req->info().port());
803 DeleteResolver();
805 // Quit after returning from OnCompleted (to give it a chance at
806 // incorrectly running the cancelled tasks).
807 base::MessageLoop::current()->PostTask(FROM_HERE,
808 base::MessageLoop::QuitClosure());
811 set_handler(new MyHandler());
813 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
814 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
815 // HostResolverImpl will be deleted before later Requests can complete.
816 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 81)->Resolve());
817 // Job for 'b' will be aborted before it can complete.
818 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 82)->Resolve());
819 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
821 EXPECT_TRUE(proc_->WaitFor(1u));
823 // Triggering an IP address change.
824 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
826 // |MyHandler| will send quit message once all the requests have finished.
827 base::MessageLoop::current()->Run();
829 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
830 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
831 EXPECT_EQ(ERR_IO_PENDING, requests_[2]->result());
832 EXPECT_EQ(ERR_IO_PENDING, requests_[3]->result());
833 // Clean up.
834 proc_->SignalMultiple(requests_.size());
837 TEST_F(HostResolverImplTest, StartWithinCallback) {
838 struct MyHandler : public Handler {
839 void Handle(Request* req) override {
840 if (req->index() == 0) {
841 // On completing the first request, start another request for "a".
842 // Since caching is disabled, this will result in another async request.
843 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 70)->Resolve());
847 set_handler(new MyHandler());
849 // Turn off caching for this host resolver.
850 HostResolver::Options options = DefaultOptions();
851 options.enable_caching = false;
852 resolver_.reset(new HostResolverImpl(options, NULL));
853 resolver_->set_proc_params_for_test(DefaultParams(proc_.get()));
855 for (size_t i = 0; i < 4; ++i) {
856 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
859 proc_->SignalMultiple(2u); // One for "a". One for the second "a".
861 EXPECT_EQ(OK, requests_[0]->WaitForResult());
862 ASSERT_EQ(5u, requests_.size());
863 EXPECT_EQ(OK, requests_.back()->WaitForResult());
865 EXPECT_EQ(2u, proc_->GetCaptureList().size());
868 TEST_F(HostResolverImplTest, BypassCache) {
869 struct MyHandler : public Handler {
870 void Handle(Request* req) override {
871 if (req->index() == 0) {
872 // On completing the first request, start another request for "a".
873 // Since caching is enabled, this should complete synchronously.
874 std::string hostname = req->info().hostname();
875 EXPECT_EQ(OK, CreateRequest(hostname, 70)->Resolve());
876 EXPECT_EQ(OK, CreateRequest(hostname, 75)->ResolveFromCache());
878 // Ok good. Now make sure that if we ask to bypass the cache, it can no
879 // longer service the request synchronously.
880 HostResolver::RequestInfo info(HostPortPair(hostname, 71));
881 info.set_allow_cached_response(false);
882 EXPECT_EQ(ERR_IO_PENDING,
883 CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
884 } else if (71 == req->info().port()) {
885 // Test is done.
886 base::MessageLoop::current()->Quit();
887 } else {
888 FAIL() << "Unexpected request";
892 set_handler(new MyHandler());
894 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
895 proc_->SignalMultiple(3u); // Only need two, but be generous.
897 // |verifier| will send quit message once all the requests have finished.
898 base::MessageLoop::current()->Run();
899 EXPECT_EQ(2u, proc_->GetCaptureList().size());
902 // Test that IP address changes flush the cache.
903 TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) {
904 proc_->SignalMultiple(2u); // One before the flush, one after.
906 Request* req = CreateRequest("host1", 70);
907 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
908 EXPECT_EQ(OK, req->WaitForResult());
910 req = CreateRequest("host1", 75);
911 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
913 // Flush cache by triggering an IP address change.
914 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
915 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
917 // Resolve "host1" again -- this time it won't be served from cache, so it
918 // will complete asynchronously.
919 req = CreateRequest("host1", 80);
920 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
921 EXPECT_EQ(OK, req->WaitForResult());
924 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
925 TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) {
926 Request* req = CreateRequest("host1", 70);
927 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
929 EXPECT_TRUE(proc_->WaitFor(1u));
930 // Triggering an IP address change.
931 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
932 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
933 proc_->SignalAll();
935 EXPECT_EQ(ERR_NETWORK_CHANGED, req->WaitForResult());
936 EXPECT_EQ(0u, resolver_->GetHostCache()->size());
939 // Obey pool constraints after IP address has changed.
940 TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) {
941 // Runs at most one job at a time.
942 CreateSerialResolver();
943 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a")->Resolve());
944 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b")->Resolve());
945 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("c")->Resolve());
947 EXPECT_TRUE(proc_->WaitFor(1u));
948 // Triggering an IP address change.
949 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
950 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
951 proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it.
953 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
955 EXPECT_EQ(1u, num_running_dispatcher_jobs());
957 EXPECT_FALSE(requests_[1]->completed());
958 EXPECT_FALSE(requests_[2]->completed());
960 EXPECT_EQ(OK, requests_[2]->WaitForResult());
961 EXPECT_EQ(OK, requests_[1]->result());
964 // Tests that a new Request made from the callback of a previously aborted one
965 // will not be aborted.
966 TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) {
967 struct MyHandler : public Handler {
968 void Handle(Request* req) override {
969 // Start new request for a different hostname to ensure that the order
970 // of jobs in HostResolverImpl is not stable.
971 std::string hostname;
972 if (req->index() == 0)
973 hostname = "zzz";
974 else if (req->index() == 1)
975 hostname = "aaa";
976 else if (req->index() == 2)
977 hostname = "eee";
978 else
979 return; // A request started from within MyHandler.
980 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname;
983 set_handler(new MyHandler());
985 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("bbb")->Resolve());
986 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("eee")->Resolve());
987 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ccc")->Resolve());
989 // Wait until all are blocked;
990 EXPECT_TRUE(proc_->WaitFor(3u));
991 // Trigger an IP address change.
992 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
993 // This should abort all running jobs.
994 base::MessageLoop::current()->RunUntilIdle();
995 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
996 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->result());
997 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->result());
998 ASSERT_EQ(6u, requests_.size());
999 // Unblock all calls to proc.
1000 proc_->SignalMultiple(requests_.size());
1001 // Run until the re-started requests finish.
1002 EXPECT_EQ(OK, requests_[3]->WaitForResult());
1003 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1004 EXPECT_EQ(OK, requests_[5]->WaitForResult());
1005 // Verify that results of aborted Jobs were not cached.
1006 EXPECT_EQ(6u, proc_->GetCaptureList().size());
1007 EXPECT_EQ(3u, resolver_->GetHostCache()->size());
1010 // Tests that when the maximum threads is set to 1, requests are dequeued
1011 // in order of priority.
1012 TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) {
1013 CreateSerialResolver();
1015 // Note that at this point the MockHostResolverProc is blocked, so any
1016 // requests we make will not complete.
1017 CreateRequest("req0", 80, LOW);
1018 CreateRequest("req1", 80, MEDIUM);
1019 CreateRequest("req2", 80, MEDIUM);
1020 CreateRequest("req3", 80, LOW);
1021 CreateRequest("req4", 80, HIGHEST);
1022 CreateRequest("req5", 80, LOW);
1023 CreateRequest("req6", 80, LOW);
1024 CreateRequest("req5", 80, HIGHEST);
1026 for (size_t i = 0; i < requests_.size(); ++i) {
1027 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1030 // Unblock the resolver thread so the requests can run.
1031 proc_->SignalMultiple(requests_.size()); // More than needed.
1033 // Wait for all the requests to complete succesfully.
1034 for (size_t i = 0; i < requests_.size(); ++i) {
1035 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1038 // Since we have restricted to a single concurrent thread in the jobpool,
1039 // the requests should complete in order of priority (with the exception
1040 // of the first request, which gets started right away, since there is
1041 // nothing outstanding).
1042 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1043 ASSERT_EQ(7u, capture_list.size());
1045 EXPECT_EQ("req0", capture_list[0].hostname);
1046 EXPECT_EQ("req4", capture_list[1].hostname);
1047 EXPECT_EQ("req5", capture_list[2].hostname);
1048 EXPECT_EQ("req1", capture_list[3].hostname);
1049 EXPECT_EQ("req2", capture_list[4].hostname);
1050 EXPECT_EQ("req3", capture_list[5].hostname);
1051 EXPECT_EQ("req6", capture_list[6].hostname);
1054 // Try cancelling a job which has not started yet.
1055 TEST_F(HostResolverImplTest, CancelPendingRequest) {
1056 CreateSerialResolver();
1058 CreateRequest("req0", 80, LOWEST);
1059 CreateRequest("req1", 80, HIGHEST); // Will cancel.
1060 CreateRequest("req2", 80, MEDIUM);
1061 CreateRequest("req3", 80, LOW);
1062 CreateRequest("req4", 80, HIGHEST); // Will cancel.
1063 CreateRequest("req5", 80, LOWEST); // Will cancel.
1064 CreateRequest("req6", 80, MEDIUM);
1066 // Start all of the requests.
1067 for (size_t i = 0; i < requests_.size(); ++i) {
1068 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1071 // Cancel some requests
1072 requests_[1]->Cancel();
1073 requests_[4]->Cancel();
1074 requests_[5]->Cancel();
1076 // Unblock the resolver thread so the requests can run.
1077 proc_->SignalMultiple(requests_.size()); // More than needed.
1079 // Wait for all the requests to complete succesfully.
1080 for (size_t i = 0; i < requests_.size(); ++i) {
1081 if (!requests_[i]->pending())
1082 continue; // Don't wait for the requests we cancelled.
1083 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1086 // Verify that they called out the the resolver proc (which runs on the
1087 // resolver thread) in the expected order.
1088 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1089 ASSERT_EQ(4u, capture_list.size());
1091 EXPECT_EQ("req0", capture_list[0].hostname);
1092 EXPECT_EQ("req2", capture_list[1].hostname);
1093 EXPECT_EQ("req6", capture_list[2].hostname);
1094 EXPECT_EQ("req3", capture_list[3].hostname);
1097 // Test that when too many requests are enqueued, old ones start to be aborted.
1098 TEST_F(HostResolverImplTest, QueueOverflow) {
1099 CreateSerialResolver();
1101 // Allow only 3 queued jobs.
1102 const size_t kMaxPendingJobs = 3u;
1103 resolver_->SetMaxQueuedJobs(kMaxPendingJobs);
1105 // Note that at this point the MockHostResolverProc is blocked, so any
1106 // requests we make will not complete.
1108 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req0", 80, LOWEST)->Resolve());
1109 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req1", 80, HIGHEST)->Resolve());
1110 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req2", 80, MEDIUM)->Resolve());
1111 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req3", 80, MEDIUM)->Resolve());
1113 // At this point, there are 3 enqueued jobs.
1114 // Insertion of subsequent requests will cause evictions
1115 // based on priority.
1117 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1118 CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself!
1120 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req5", 80, MEDIUM)->Resolve());
1121 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[2]->result());
1122 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req6", 80, HIGHEST)->Resolve());
1123 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[3]->result());
1124 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req7", 80, MEDIUM)->Resolve());
1125 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[5]->result());
1127 // Unblock the resolver thread so the requests can run.
1128 proc_->SignalMultiple(4u);
1130 // The rest should succeed.
1131 EXPECT_EQ(OK, requests_[7]->WaitForResult());
1132 EXPECT_EQ(OK, requests_[0]->result());
1133 EXPECT_EQ(OK, requests_[1]->result());
1134 EXPECT_EQ(OK, requests_[6]->result());
1136 // Verify that they called out the the resolver proc (which runs on the
1137 // resolver thread) in the expected order.
1138 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1139 ASSERT_EQ(4u, capture_list.size());
1141 EXPECT_EQ("req0", capture_list[0].hostname);
1142 EXPECT_EQ("req1", capture_list[1].hostname);
1143 EXPECT_EQ("req6", capture_list[2].hostname);
1144 EXPECT_EQ("req7", capture_list[3].hostname);
1146 // Verify that the evicted (incomplete) requests were not cached.
1147 EXPECT_EQ(4u, resolver_->GetHostCache()->size());
1149 for (size_t i = 0; i < requests_.size(); ++i) {
1150 EXPECT_TRUE(requests_[i]->completed()) << i;
1154 // Tests that after changing the default AddressFamily to IPV4, requests
1155 // with UNSPECIFIED address family map to IPV4.
1156 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv4) {
1157 CreateSerialResolver(); // To guarantee order of resolutions.
1159 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1160 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1162 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1164 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1165 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1166 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1168 // Start all of the requests.
1169 for (size_t i = 0; i < requests_.size(); ++i) {
1170 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1173 proc_->SignalMultiple(requests_.size());
1175 // Wait for all the requests to complete.
1176 for (size_t i = 0u; i < requests_.size(); ++i) {
1177 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1180 // Since the requests all had the same priority and we limited the thread
1181 // count to 1, they should have completed in the same order as they were
1182 // requested. Moreover, request0 and request1 will have been serviced by
1183 // the same job.
1185 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1186 ASSERT_EQ(2u, capture_list.size());
1188 EXPECT_EQ("h1", capture_list[0].hostname);
1189 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[0].address_family);
1191 EXPECT_EQ("h1", capture_list[1].hostname);
1192 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[1].address_family);
1194 // Now check that the correct resolved IP addresses were returned.
1195 EXPECT_TRUE(requests_[0]->HasOneAddress("1.0.0.1", 80));
1196 EXPECT_TRUE(requests_[1]->HasOneAddress("1.0.0.1", 80));
1197 EXPECT_TRUE(requests_[2]->HasOneAddress("::2", 80));
1200 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the
1201 // default family is set to IPv6 and the family of requests is flipped where
1202 // specified.
1203 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv6) {
1204 CreateSerialResolver(); // To guarantee order of resolutions.
1206 // Don't use IPv6 replacements here since some systems don't support it.
1207 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1208 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1210 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6);
1212 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1213 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1214 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1216 // Start all of the requests.
1217 for (size_t i = 0; i < requests_.size(); ++i) {
1218 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1221 proc_->SignalMultiple(requests_.size());
1223 // Wait for all the requests to complete.
1224 for (size_t i = 0u; i < requests_.size(); ++i) {
1225 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1228 // Since the requests all had the same priority and we limited the thread
1229 // count to 1, they should have completed in the same order as they were
1230 // requested. Moreover, request0 and request1 will have been serviced by
1231 // the same job.
1233 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1234 ASSERT_EQ(2u, capture_list.size());
1236 EXPECT_EQ("h1", capture_list[0].hostname);
1237 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[0].address_family);
1239 EXPECT_EQ("h1", capture_list[1].hostname);
1240 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[1].address_family);
1242 // Now check that the correct resolved IP addresses were returned.
1243 EXPECT_TRUE(requests_[0]->HasOneAddress("::2", 80));
1244 EXPECT_TRUE(requests_[1]->HasOneAddress("::2", 80));
1245 EXPECT_TRUE(requests_[2]->HasOneAddress("1.0.0.1", 80));
1248 // Make sure that the address family parameter is respected when raw IPs are
1249 // passed in.
1250 TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs) {
1251 Request* request =
1252 CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1253 EXPECT_EQ(OK, request->Resolve());
1254 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1256 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1257 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1259 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1260 EXPECT_EQ(OK, request->Resolve());
1261 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1263 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1264 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1266 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1267 EXPECT_EQ(OK, request->Resolve());
1268 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1270 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1271 EXPECT_EQ(OK, request->Resolve());
1272 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1275 TEST_F(HostResolverImplTest, ResolveFromCache) {
1276 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1277 proc_->SignalMultiple(1u); // Need only one.
1279 HostResolver::RequestInfo info(HostPortPair("just.testing", 80));
1281 // First hit will miss the cache.
1282 EXPECT_EQ(ERR_DNS_CACHE_MISS,
1283 CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1285 // This time, we fetch normally.
1286 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
1287 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1289 // Now we should be able to fetch from the cache.
1290 EXPECT_EQ(OK, CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1291 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80));
1294 // Test the retry attempts simulating host resolver proc that takes too long.
1295 TEST_F(HostResolverImplTest, MultipleAttempts) {
1296 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1297 // the host. First and second attempt will be forced to sleep until they get
1298 // word that a resolution has completed. The 3rd resolution attempt will try
1299 // to get done ASAP, and won't sleep..
1300 int kAttemptNumberToResolve = 3;
1301 int kTotalAttempts = 3;
1303 scoped_refptr<LookupAttemptHostResolverProc> resolver_proc(
1304 new LookupAttemptHostResolverProc(
1305 NULL, kAttemptNumberToResolve, kTotalAttempts));
1307 HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get());
1309 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1310 // that unit test runs faster. For example, this test finishes in 1.5 secs
1311 // (500ms * 3).
1312 params.unresponsive_delay = base::TimeDelta::FromMilliseconds(500);
1314 resolver_.reset(new HostResolverImpl(DefaultOptions(), NULL));
1315 resolver_->set_proc_params_for_test(params);
1317 // Resolve "host1".
1318 HostResolver::RequestInfo info(HostPortPair("host1", 70));
1319 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1320 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1322 // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
1323 EXPECT_EQ(-4, req->WaitForResult());
1325 resolver_proc->WaitForAllAttemptsToFinish(
1326 base::TimeDelta::FromMilliseconds(60000));
1327 base::MessageLoop::current()->RunUntilIdle();
1329 EXPECT_EQ(resolver_proc->total_attempts_resolved(), kTotalAttempts);
1330 EXPECT_EQ(resolver_proc->resolved_attempt_number(), kAttemptNumberToResolve);
1333 // If a host resolves to a list that includes 127.0.53.53, this is treated as
1334 // an error. 127.0.53.53 is a localhost address, however it has been given a
1335 // special significance by ICANN to help surfance name collision resulting from
1336 // the new gTLDs.
1337 TEST_F(HostResolverImplTest, NameCollision127_0_53_53) {
1338 proc_->AddRuleForAllFamilies("single", "127.0.53.53");
1339 proc_->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53");
1340 proc_->AddRuleForAllFamilies("ipv6", "::127.0.53.53");
1341 proc_->AddRuleForAllFamilies("not_reserved1", "53.53.0.127");
1342 proc_->AddRuleForAllFamilies("not_reserved2", "127.0.53.54");
1343 proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53");
1344 proc_->SignalMultiple(6u);
1346 Request* request;
1348 request = CreateRequest("single");
1349 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1350 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1352 request = CreateRequest("multiple");
1353 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1354 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1356 // Resolving an IP literal of 127.0.53.53 however is allowed.
1357 EXPECT_EQ(OK, CreateRequest("127.0.53.53")->Resolve());
1359 // Moreover the address should not be recognized when embedded in an IPv6
1360 // address.
1361 request = CreateRequest("ipv6");
1362 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1363 EXPECT_EQ(OK, request->WaitForResult());
1365 // Try some other IPs which are similar, but NOT an exact match on
1366 // 127.0.53.53.
1367 request = CreateRequest("not_reserved1");
1368 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1369 EXPECT_EQ(OK, request->WaitForResult());
1371 request = CreateRequest("not_reserved2");
1372 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1373 EXPECT_EQ(OK, request->WaitForResult());
1375 request = CreateRequest("not_reserved3");
1376 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1377 EXPECT_EQ(OK, request->WaitForResult());
1380 DnsConfig CreateValidDnsConfig() {
1381 IPAddressNumber dns_ip;
1382 bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip);
1383 EXPECT_TRUE(rv);
1385 DnsConfig config;
1386 config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort));
1387 EXPECT_TRUE(config.IsValid());
1388 return config;
1391 // Specialized fixture for tests of DnsTask.
1392 class HostResolverImplDnsTest : public HostResolverImplTest {
1393 public:
1394 HostResolverImplDnsTest() : dns_client_(NULL) {}
1396 protected:
1397 // testing::Test implementation:
1398 void SetUp() override {
1399 AddDnsRule("nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, false);
1400 AddDnsRule("nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1401 AddDnsRule("ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1402 AddDnsRule("ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1403 AddDnsRule("4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1404 AddDnsRule("4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, false);
1405 AddDnsRule("6ok", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1406 AddDnsRule("6ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1407 AddDnsRule("4nx", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1408 AddDnsRule("4nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1409 AddDnsRule("empty", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1410 AddDnsRule("empty", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1411 false);
1413 AddDnsRule("slow_nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, true);
1414 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL,
1415 true);
1417 AddDnsRule("4slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1418 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1419 false);
1420 AddDnsRule("6slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1421 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1422 true);
1423 AddDnsRule("4slow_4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1424 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1425 false);
1426 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA,
1427 MockDnsClientRule::TIMEOUT, true);
1428 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1429 false);
1430 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA,
1431 MockDnsClientRule::OK, true);
1432 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA,
1433 MockDnsClientRule::TIMEOUT, false);
1434 CreateResolver();
1437 // HostResolverImplTest implementation:
1438 void CreateResolverWithLimitsAndParams(
1439 size_t max_concurrent_resolves,
1440 const HostResolverImpl::ProcTaskParams& params) override {
1441 HostResolverImpl::Options options = DefaultOptions();
1442 options.max_concurrent_resolves = max_concurrent_resolves;
1443 resolver_.reset(new HostResolverImpl(options, NULL));
1444 resolver_->set_proc_params_for_test(params);
1445 // Disable IPv6 support probing.
1446 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1447 dns_client_ = new MockDnsClient(DnsConfig(), dns_rules_);
1448 resolver_->SetDnsClient(scoped_ptr<DnsClient>(dns_client_));
1451 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply.
1452 void AddDnsRule(const std::string& prefix,
1453 uint16 qtype,
1454 MockDnsClientRule::Result result,
1455 bool delay) {
1456 dns_rules_.push_back(MockDnsClientRule(prefix, qtype, result, delay));
1459 void ChangeDnsConfig(const DnsConfig& config) {
1460 NetworkChangeNotifier::SetDnsConfig(config);
1461 // Notification is delivered asynchronously.
1462 base::MessageLoop::current()->RunUntilIdle();
1465 MockDnsClientRuleList dns_rules_;
1466 // Owned by |resolver_|.
1467 MockDnsClient* dns_client_;
1470 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change.
1472 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags.
1474 // Test successful and fallback resolutions in HostResolverImpl::DnsTask.
1475 TEST_F(HostResolverImplDnsTest, DnsTask) {
1476 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1478 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1479 // All other hostnames will fail in proc_.
1481 // Initially there is no config, so client should not be invoked.
1482 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1483 proc_->SignalMultiple(requests_.size());
1485 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1487 ChangeDnsConfig(CreateValidDnsConfig());
1489 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1490 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve());
1491 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve());
1493 proc_->SignalMultiple(requests_.size());
1495 for (size_t i = 1; i < requests_.size(); ++i)
1496 EXPECT_NE(ERR_UNEXPECTED, requests_[i]->WaitForResult()) << i;
1498 EXPECT_EQ(OK, requests_[1]->result());
1499 // Resolved by MockDnsClient.
1500 EXPECT_TRUE(requests_[1]->HasOneAddress("127.0.0.1", 80));
1501 // Fallback to ProcTask.
1502 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[2]->result());
1503 EXPECT_EQ(OK, requests_[3]->result());
1504 EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.102", 80));
1507 // Test successful and failing resolutions in HostResolverImpl::DnsTask when
1508 // fallback to ProcTask is disabled.
1509 TEST_F(HostResolverImplDnsTest, NoFallbackToProcTask) {
1510 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1511 set_fallback_to_proctask(false);
1513 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1514 // All other hostnames will fail in proc_.
1516 // Set empty DnsConfig.
1517 ChangeDnsConfig(DnsConfig());
1518 // Initially there is no config, so client should not be invoked.
1519 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1520 // There is no config, so fallback to ProcTask must work.
1521 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve());
1522 proc_->SignalMultiple(requests_.size());
1524 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1525 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1526 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.1.102", 80));
1528 ChangeDnsConfig(CreateValidDnsConfig());
1530 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_abort", 80)->Resolve());
1531 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1533 // Simulate the case when the preference or policy has disabled the DNS client
1534 // causing AbortDnsTasks.
1535 resolver_->SetDnsClient(
1536 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1537 ChangeDnsConfig(CreateValidDnsConfig());
1539 // First request is resolved by MockDnsClient, others should fail due to
1540 // disabled fallback to ProcTask.
1541 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1542 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve());
1543 proc_->SignalMultiple(requests_.size());
1545 // Aborted due to Network Change.
1546 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->WaitForResult());
1547 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[3]->WaitForResult());
1548 // Resolved by MockDnsClient.
1549 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1550 EXPECT_TRUE(requests_[4]->HasOneAddress("127.0.0.1", 80));
1551 // Fallback to ProcTask is disabled.
1552 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[5]->WaitForResult());
1555 // Test behavior of OnDnsTaskFailure when Job is aborted.
1556 TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob) {
1557 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1558 ChangeDnsConfig(CreateValidDnsConfig());
1559 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1560 // Abort all jobs here.
1561 CreateResolver();
1562 proc_->SignalMultiple(requests_.size());
1563 // Run to completion.
1564 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1565 // It shouldn't crash during OnDnsTaskFailure callbacks.
1566 EXPECT_EQ(ERR_IO_PENDING, requests_[0]->result());
1568 // Repeat test with Fallback to ProcTask disabled
1569 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1570 set_fallback_to_proctask(false);
1571 ChangeDnsConfig(CreateValidDnsConfig());
1572 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1573 // Abort all jobs here.
1574 CreateResolver();
1575 // Run to completion.
1576 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1577 // It shouldn't crash during OnDnsTaskFailure callbacks.
1578 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
1581 TEST_F(HostResolverImplDnsTest, DnsTaskUnspec) {
1582 ChangeDnsConfig(CreateValidDnsConfig());
1584 proc_->AddRuleForAllFamilies("4nx", "192.168.1.101");
1585 // All other hostnames will fail in proc_.
1587 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1588 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4ok", 80)->Resolve());
1589 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6ok", 80)->Resolve());
1590 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4nx", 80)->Resolve());
1592 proc_->SignalMultiple(requests_.size());
1594 for (size_t i = 0; i < requests_.size(); ++i)
1595 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1597 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1598 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1599 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1600 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1601 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1602 EXPECT_EQ(1u, requests_[2]->NumberOfAddresses());
1603 EXPECT_TRUE(requests_[2]->HasAddress("::1", 80));
1604 EXPECT_EQ(1u, requests_[3]->NumberOfAddresses());
1605 EXPECT_TRUE(requests_[3]->HasAddress("192.168.1.101", 80));
1608 TEST_F(HostResolverImplDnsTest, ServeFromHosts) {
1609 // Initially, use empty HOSTS file.
1610 DnsConfig config = CreateValidDnsConfig();
1611 ChangeDnsConfig(config);
1613 proc_->AddRuleForAllFamilies(std::string(),
1614 std::string()); // Default to failures.
1615 proc_->SignalMultiple(1u); // For the first request which misses.
1617 Request* req0 = CreateRequest("nx_ipv4", 80);
1618 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
1619 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req0->WaitForResult());
1621 IPAddressNumber local_ipv4, local_ipv6;
1622 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1623 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1625 DnsHosts hosts;
1626 hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1627 hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1628 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1629 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1631 // Update HOSTS file.
1632 config.hosts = hosts;
1633 ChangeDnsConfig(config);
1635 Request* req1 = CreateRequest("nx_ipv4", 80);
1636 EXPECT_EQ(OK, req1->Resolve());
1637 EXPECT_TRUE(req1->HasOneAddress("127.0.0.1", 80));
1639 Request* req2 = CreateRequest("nx_ipv6", 80);
1640 EXPECT_EQ(OK, req2->Resolve());
1641 EXPECT_TRUE(req2->HasOneAddress("::1", 80));
1643 Request* req3 = CreateRequest("nx_both", 80);
1644 EXPECT_EQ(OK, req3->Resolve());
1645 EXPECT_TRUE(req3->HasAddress("127.0.0.1", 80) &&
1646 req3->HasAddress("::1", 80));
1648 // Requests with specified AddressFamily.
1649 Request* req4 = CreateRequest("nx_ipv4", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1650 EXPECT_EQ(OK, req4->Resolve());
1651 EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80));
1653 Request* req5 = CreateRequest("nx_ipv6", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1654 EXPECT_EQ(OK, req5->Resolve());
1655 EXPECT_TRUE(req5->HasOneAddress("::1", 80));
1657 // Request with upper case.
1658 Request* req6 = CreateRequest("nx_IPV4", 80);
1659 EXPECT_EQ(OK, req6->Resolve());
1660 EXPECT_TRUE(req6->HasOneAddress("127.0.0.1", 80));
1663 TEST_F(HostResolverImplDnsTest, BypassDnsTask) {
1664 ChangeDnsConfig(CreateValidDnsConfig());
1666 proc_->AddRuleForAllFamilies(std::string(),
1667 std::string()); // Default to failures.
1669 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local", 80)->Resolve());
1670 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local.", 80)->Resolve());
1671 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal", 80)->Resolve());
1672 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal.", 80)->Resolve());
1673 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1675 proc_->SignalMultiple(requests_.size());
1677 for (size_t i = 0; i < 2; ++i)
1678 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[i]->WaitForResult()) << i;
1680 for (size_t i = 2; i < requests_.size(); ++i)
1681 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1684 TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask) {
1685 ChangeDnsConfig(CreateValidDnsConfig());
1687 proc_->AddRuleForAllFamilies(std::string(), std::string());
1689 HostResolver::RequestInfo info_bypass(HostPortPair("ok", 80));
1690 info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY);
1691 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info_bypass, MEDIUM)->Resolve());
1693 HostResolver::RequestInfo info(HostPortPair("ok", 80));
1694 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, MEDIUM)->Resolve());
1696 proc_->SignalMultiple(requests_.size());
1698 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1699 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1702 TEST_F(HostResolverImplDnsTest, DisableDnsClientOnPersistentFailure) {
1703 ChangeDnsConfig(CreateValidDnsConfig());
1705 proc_->AddRuleForAllFamilies(std::string(),
1706 std::string()); // Default to failures.
1708 // Check that DnsTask works.
1709 Request* req = CreateRequest("ok_1", 80);
1710 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1711 EXPECT_EQ(OK, req->WaitForResult());
1713 for (unsigned i = 0; i < maximum_dns_failures(); ++i) {
1714 // Use custom names to require separate Jobs.
1715 std::string hostname = base::StringPrintf("nx_%u", i);
1716 // Ensure fallback to ProcTask succeeds.
1717 proc_->AddRuleForAllFamilies(hostname, "192.168.1.101");
1718 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1721 proc_->SignalMultiple(requests_.size());
1723 for (size_t i = 0; i < requests_.size(); ++i)
1724 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1726 ASSERT_FALSE(proc_->HasBlockedRequests());
1728 // DnsTask should be disabled by now.
1729 req = CreateRequest("ok_2", 80);
1730 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1731 proc_->SignalMultiple(1u);
1732 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
1734 // Check that it is re-enabled after DNS change.
1735 ChangeDnsConfig(CreateValidDnsConfig());
1736 req = CreateRequest("ok_3", 80);
1737 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1738 EXPECT_EQ(OK, req->WaitForResult());
1741 TEST_F(HostResolverImplDnsTest, DontDisableDnsClientOnSporadicFailure) {
1742 ChangeDnsConfig(CreateValidDnsConfig());
1744 // |proc_| defaults to successes.
1746 // 20 failures interleaved with 20 successes.
1747 for (unsigned i = 0; i < 40; ++i) {
1748 // Use custom names to require separate Jobs.
1749 std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i)
1750 : base::StringPrintf("ok_%u", i);
1751 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1754 proc_->SignalMultiple(requests_.size());
1756 for (size_t i = 0; i < requests_.size(); ++i)
1757 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1759 // Make |proc_| default to failures.
1760 proc_->AddRuleForAllFamilies(std::string(), std::string());
1762 // DnsTask should still be enabled.
1763 Request* req = CreateRequest("ok_last", 80);
1764 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1765 EXPECT_EQ(OK, req->WaitForResult());
1768 // Confirm that resolving "localhost" is unrestricted even if there are no
1769 // global IPv6 address. See SystemHostResolverCall for rationale.
1770 // Test both the DnsClient and system host resolver paths.
1771 TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost) {
1772 // Use regular SystemHostResolverCall!
1773 scoped_refptr<HostResolverProc> proc(new SystemHostResolverProc());
1774 resolver_.reset(new HostResolverImpl(DefaultOptions(), NULL));
1775 resolver_->set_proc_params_for_test(DefaultParams(proc.get()));
1777 resolver_->SetDnsClient(
1778 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1779 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1781 // Get the expected output.
1782 AddressList addrlist;
1783 int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist,
1784 NULL);
1785 if (rv != OK)
1786 return;
1788 for (unsigned i = 0; i < addrlist.size(); ++i)
1789 LOG(WARNING) << addrlist[i].ToString();
1791 bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0);
1792 bool saw_ipv6 = AddressListContains(addrlist, "::1", 0);
1793 if (!saw_ipv4 && !saw_ipv6)
1794 return;
1796 HostResolver::RequestInfo info(HostPortPair("localhost", 80));
1797 info.set_address_family(ADDRESS_FAMILY_UNSPECIFIED);
1798 info.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1800 // Try without DnsClient.
1801 ChangeDnsConfig(DnsConfig());
1802 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1803 // It is resolved via getaddrinfo, so expect asynchronous result.
1804 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1805 EXPECT_EQ(OK, req->WaitForResult());
1807 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1808 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1810 // Configure DnsClient with dual-host HOSTS file.
1811 DnsConfig config = CreateValidDnsConfig();
1812 DnsHosts hosts;
1813 IPAddressNumber local_ipv4, local_ipv6;
1814 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1815 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1816 if (saw_ipv4)
1817 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1818 if (saw_ipv6)
1819 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1820 config.hosts = hosts;
1822 ChangeDnsConfig(config);
1823 req = CreateRequest(info, DEFAULT_PRIORITY);
1824 // Expect synchronous resolution from DnsHosts.
1825 EXPECT_EQ(OK, req->Resolve());
1827 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1828 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1831 // Cancel a request with a single DNS transaction active.
1832 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) {
1833 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1834 ChangeDnsConfig(CreateValidDnsConfig());
1836 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1837 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1838 requests_[0]->Cancel();
1840 // Dispatcher state checked in TearDown.
1843 // Cancel a request with a single DNS transaction active and another pending.
1844 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActiveOnePending) {
1845 CreateSerialResolver();
1846 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1847 ChangeDnsConfig(CreateValidDnsConfig());
1849 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1850 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1851 requests_[0]->Cancel();
1853 // Dispatcher state checked in TearDown.
1856 // Cancel a request with two DNS transactions active.
1857 TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) {
1858 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1859 ChangeDnsConfig(CreateValidDnsConfig());
1861 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1862 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1863 requests_[0]->Cancel();
1865 // Dispatcher state checked in TearDown.
1868 // Delete a resolver with some active requests and some queued requests.
1869 TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions) {
1870 // At most 10 Jobs active at once.
1871 CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_.get()));
1873 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1874 ChangeDnsConfig(CreateValidDnsConfig());
1876 // First active job is an IPv4 request.
1877 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1878 ADDRESS_FAMILY_IPV4)->Resolve());
1880 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1881 // active jobs, next one has a single active job, and one pending. Others
1882 // should all be queued.
1883 for (int i = 0; i < 10; ++i) {
1884 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(
1885 base::StringPrintf("ok%i", i))->Resolve());
1887 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1889 resolver_.reset();
1892 // Cancel a request with only the IPv6 transaction active.
1893 TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) {
1894 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1895 ChangeDnsConfig(CreateValidDnsConfig());
1897 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6slow_ok", 80)->Resolve());
1898 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1900 // The IPv4 request should complete, the IPv6 request is still pending.
1901 base::RunLoop().RunUntilIdle();
1902 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1903 requests_[0]->Cancel();
1905 // Dispatcher state checked in TearDown.
1908 // Cancel a request with only the IPv4 transaction pending.
1909 TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending) {
1910 set_fallback_to_proctask(false);
1911 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1912 ChangeDnsConfig(CreateValidDnsConfig());
1914 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1915 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1917 // The IPv6 request should complete, the IPv4 request is still pending.
1918 base::RunLoop().RunUntilIdle();
1919 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1921 requests_[0]->Cancel();
1924 // Test cases where AAAA completes first.
1925 TEST_F(HostResolverImplDnsTest, AAAACompletesFirst) {
1926 set_fallback_to_proctask(false);
1927 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1928 ChangeDnsConfig(CreateValidDnsConfig());
1930 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1931 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4ok", 80)->Resolve());
1932 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4timeout", 80)->Resolve());
1933 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_6timeout", 80)->Resolve());
1935 base::RunLoop().RunUntilIdle();
1936 EXPECT_FALSE(requests_[0]->completed());
1937 EXPECT_FALSE(requests_[1]->completed());
1938 EXPECT_FALSE(requests_[2]->completed());
1939 // The IPv6 of the third request should have failed and resulted in cancelling
1940 // the IPv4 request.
1941 EXPECT_TRUE(requests_[3]->completed());
1942 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[3]->result());
1943 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1945 dns_client_->CompleteDelayedTransactions();
1946 EXPECT_TRUE(requests_[0]->completed());
1947 EXPECT_EQ(OK, requests_[0]->result());
1948 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1949 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1950 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1952 EXPECT_TRUE(requests_[1]->completed());
1953 EXPECT_EQ(OK, requests_[1]->result());
1954 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1955 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1957 EXPECT_TRUE(requests_[2]->completed());
1958 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[2]->result());
1961 // Test the case where only a single transaction slot is available.
1962 TEST_F(HostResolverImplDnsTest, SerialResolver) {
1963 CreateSerialResolver();
1964 set_fallback_to_proctask(false);
1965 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1966 ChangeDnsConfig(CreateValidDnsConfig());
1968 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1969 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1971 base::RunLoop().RunUntilIdle();
1972 EXPECT_TRUE(requests_[0]->completed());
1973 EXPECT_EQ(OK, requests_[0]->result());
1974 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1975 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1976 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1979 // Test the case where the AAAA query is started when another transaction
1980 // completes.
1981 TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) {
1982 CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_.get()));
1983 set_fallback_to_proctask(false);
1984 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1985 ChangeDnsConfig(CreateValidDnsConfig());
1987 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1988 ADDRESS_FAMILY_IPV4)->Resolve());
1989 EXPECT_EQ(ERR_IO_PENDING,
1990 CreateRequest("4slow_ok", 80, MEDIUM)->Resolve());
1991 // An IPv4 request should have been started pending for each job.
1992 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1994 // Request 0's IPv4 request should complete, starting Request 1's IPv6
1995 // request, which should also complete.
1996 base::RunLoop().RunUntilIdle();
1997 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1998 EXPECT_TRUE(requests_[0]->completed());
1999 EXPECT_FALSE(requests_[1]->completed());
2001 dns_client_->CompleteDelayedTransactions();
2002 EXPECT_TRUE(requests_[1]->completed());
2003 EXPECT_EQ(OK, requests_[1]->result());
2004 EXPECT_EQ(2u, requests_[1]->NumberOfAddresses());
2005 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
2006 EXPECT_TRUE(requests_[1]->HasAddress("::1", 80));
2009 // Tests the case that a Job with a single transaction receives an empty address
2010 // list, triggering fallback to ProcTask.
2011 TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) {
2012 ChangeDnsConfig(CreateValidDnsConfig());
2013 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2014 proc_->SignalMultiple(1u);
2015 EXPECT_EQ(ERR_IO_PENDING,
2016 CreateRequest("empty_fallback", 80, MEDIUM,
2017 ADDRESS_FAMILY_IPV4)->Resolve());
2018 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2019 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2022 // Tests the case that a Job with two transactions receives two empty address
2023 // lists, triggering fallback to ProcTask.
2024 TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback) {
2025 ChangeDnsConfig(CreateValidDnsConfig());
2026 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2027 proc_->SignalMultiple(1u);
2028 EXPECT_EQ(ERR_IO_PENDING,
2029 CreateRequest("empty_fallback", 80, MEDIUM,
2030 ADDRESS_FAMILY_UNSPECIFIED)->Resolve());
2031 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2032 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2035 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
2036 TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) {
2037 // At most 3 jobs active at once. This number is important, since we want to
2038 // make sure that aborting the first HostResolverImpl::Job does not trigger
2039 // another DnsTransaction on the second Job when it releases its second
2040 // prioritized dispatcher slot.
2041 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2043 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2044 ChangeDnsConfig(CreateValidDnsConfig());
2046 proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
2047 proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
2048 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2050 // First active job gets two slots.
2051 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx1")->Resolve());
2052 // Next job gets one slot, and waits on another.
2053 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx2")->Resolve());
2054 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2056 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2058 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
2059 // should use a ProcTask.
2060 ChangeDnsConfig(DnsConfig());
2061 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
2062 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->WaitForResult());
2064 // Finish up the third job. Should bypass the DnsClient, and get its results
2065 // from MockHostResolverProc.
2066 EXPECT_FALSE(requests_[2]->completed());
2067 proc_->SignalMultiple(1u);
2068 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2069 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2072 // Tests the case that DnsClient is automatically disabled due to failures
2073 // while there are active DnsTasks.
2074 TEST_F(HostResolverImplDnsTest,
2075 AutomaticallyDisableDnsClientWithPendingRequests) {
2076 // Trying different limits is important for this test: Different limits
2077 // result in different behavior when aborting in-progress DnsTasks. Having
2078 // a DnsTask that has one job active and one in the queue when another job
2079 // occupying two slots has its DnsTask aborted is the case most likely to run
2080 // into problems.
2081 for (size_t limit = 1u; limit < 6u; ++limit) {
2082 CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()));
2084 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2085 ChangeDnsConfig(CreateValidDnsConfig());
2087 // Queue up enough failures to disable DnsTasks. These will all fall back
2088 // to ProcTasks, and succeed there.
2089 for (unsigned i = 0u; i < maximum_dns_failures(); ++i) {
2090 std::string host = base::StringPrintf("nx%u", i);
2091 proc_->AddRuleForAllFamilies(host, "192.168.0.1");
2092 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(host)->Resolve());
2095 // These requests should all bypass DnsTasks, due to the above failures,
2096 // so should end up using ProcTasks.
2097 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2098 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2099 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2100 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2101 proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2102 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok3")->Resolve());
2103 proc_->SignalMultiple(maximum_dns_failures() + 3);
2105 for (size_t i = 0u; i < maximum_dns_failures(); ++i) {
2106 EXPECT_EQ(OK, requests_[i]->WaitForResult());
2107 EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80));
2110 EXPECT_EQ(OK, requests_[maximum_dns_failures()]->WaitForResult());
2111 EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress(
2112 "192.168.0.2", 80));
2113 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 1]->WaitForResult());
2114 EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress(
2115 "192.168.0.3", 80));
2116 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 2]->WaitForResult());
2117 EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress(
2118 "192.168.0.4", 80));
2119 requests_.clear();
2123 // Tests a call to SetDnsClient while there are active DnsTasks.
2124 TEST_F(HostResolverImplDnsTest, ManuallyDisableDnsClientWithPendingRequests) {
2125 // At most 3 jobs active at once. This number is important, since we want to
2126 // make sure that aborting the first HostResolverImpl::Job does not trigger
2127 // another DnsTransaction on the second Job when it releases its second
2128 // prioritized dispatcher slot.
2129 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2131 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2132 ChangeDnsConfig(CreateValidDnsConfig());
2134 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2135 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2136 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2138 // First active job gets two slots.
2139 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2140 // Next job gets one slot, and waits on another.
2141 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2142 // Next one is queued.
2143 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2145 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2147 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2148 // and the next one should be started with a ProcTask.
2149 resolver_->SetDnsClient(scoped_ptr<DnsClient>());
2151 // All three in-progress requests should now be running a ProcTask.
2152 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2153 proc_->SignalMultiple(3u);
2155 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2156 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2157 EXPECT_EQ(OK, requests_[1]->WaitForResult());
2158 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80));
2159 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2160 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2163 } // namespace net