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/proxy/dhcp_proxy_script_fetcher_win.h"
10 #include "base/bind_helpers.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/rand_util.h"
13 #include "base/test/test_timeouts.h"
14 #include "base/threading/platform_thread.h"
15 #include "base/timer/elapsed_timer.h"
16 #include "net/base/completion_callback.h"
17 #include "net/proxy/dhcp_proxy_script_adapter_fetcher_win.h"
18 #include "net/url_request/url_request_test_util.h"
19 #include "testing/gtest/include/gtest/gtest.h"
25 TEST(DhcpProxyScriptFetcherWin
, AdapterNamesAndPacURLFromDhcp
) {
26 // This tests our core Win32 implementation without any of the wrappers
27 // we layer on top to achieve asynchronous and parallel operations.
29 // We don't make assumptions about the environment this unit test is
30 // running in, so it just exercises the code to make sure there
31 // is no crash and no error returned, but does not assert on the number
32 // of interfaces or the information returned via DHCP.
33 std::set
<std::string
> adapter_names
;
34 DhcpProxyScriptFetcherWin::GetCandidateAdapterNames(&adapter_names
);
35 for (std::set
<std::string
>::const_iterator it
= adapter_names
.begin();
36 it
!= adapter_names
.end();
38 const std::string
& adapter_name
= *it
;
39 DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp(adapter_name
);
43 // Helper for RealFetch* tests below.
44 class RealFetchTester
{
47 : context_(new TestURLRequestContext
),
48 fetcher_(new DhcpProxyScriptFetcherWin(context_
.get())),
50 on_completion_is_error_(false) {
51 // Make sure the test ends.
52 timeout_
.Start(FROM_HERE
,
53 base::TimeDelta::FromSeconds(5), this, &RealFetchTester::OnTimeout
);
57 int result
= fetcher_
->Fetch(
59 base::Bind(&RealFetchTester::OnCompletion
, base::Unretained(this)));
60 if (result
!= ERR_IO_PENDING
)
64 void RunTestWithCancel() {
69 void RunTestWithDeferredCancel() {
70 // Put the cancellation into the queue before even running the
71 // test to avoid the chance of one of the adapter fetcher worker
72 // threads completing before cancellation. See http://crbug.com/86756.
73 cancel_timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(0),
74 this, &RealFetchTester::OnCancelTimer
);
78 void OnCompletion(int result
) {
79 if (on_completion_is_error_
) {
80 FAIL() << "Received completion for test in which this is error.";
89 void OnCancelTimer() {
94 void WaitUntilDone() {
96 base::MessageLoop::current()->RunUntilIdle();
98 base::MessageLoop::current()->RunUntilIdle();
101 // Attempts to give worker threads time to finish. This is currently
102 // very simplistic as completion (via completion callback or cancellation)
103 // immediately "detaches" any worker threads, so the best we can do is give
104 // them a little time. If we start running into Valgrind leaks, we can
105 // do something a bit more clever to track worker threads even when the
106 // DhcpProxyScriptFetcherWin state machine has finished.
107 void FinishTestAllowCleanup() {
108 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(30));
111 scoped_ptr
<URLRequestContext
> context_
;
112 scoped_ptr
<DhcpProxyScriptFetcherWin
> fetcher_
;
114 base::string16 pac_text_
;
115 base::OneShotTimer
<RealFetchTester
> timeout_
;
116 base::OneShotTimer
<RealFetchTester
> cancel_timer_
;
117 bool on_completion_is_error_
;
120 TEST(DhcpProxyScriptFetcherWin
, RealFetch
) {
121 // This tests a call to Fetch() with no stubbing out of dependencies.
123 // We don't make assumptions about the environment this unit test is
124 // running in, so it just exercises the code to make sure there
125 // is no crash and no unexpected error returned, but does not assert on
126 // results beyond that.
127 RealFetchTester fetcher
;
130 fetcher
.WaitUntilDone();
131 fetcher
.fetcher_
->GetPacURL().possibly_invalid_spec();
133 fetcher
.FinishTestAllowCleanup();
136 TEST(DhcpProxyScriptFetcherWin
, RealFetchWithCancel
) {
137 // Does a Fetch() with an immediate cancel. As before, just
138 // exercises the code without stubbing out dependencies.
139 RealFetchTester fetcher
;
140 fetcher
.RunTestWithCancel();
141 base::MessageLoop::current()->RunUntilIdle();
143 // Attempt to avoid Valgrind leak reports in case worker thread is
145 fetcher
.FinishTestAllowCleanup();
148 // For RealFetchWithDeferredCancel, below.
149 class DelayingDhcpProxyScriptAdapterFetcher
150 : public DhcpProxyScriptAdapterFetcher
{
152 DelayingDhcpProxyScriptAdapterFetcher(
153 URLRequestContext
* url_request_context
,
154 scoped_refptr
<base::TaskRunner
> task_runner
)
155 : DhcpProxyScriptAdapterFetcher(url_request_context
, task_runner
) {
158 class DelayingDhcpQuery
: public DhcpQuery
{
160 explicit DelayingDhcpQuery()
164 std::string
ImplGetPacURLFromDhcp(
165 const std::string
& adapter_name
) override
{
166 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
167 return DhcpQuery::ImplGetPacURLFromDhcp(adapter_name
);
171 DhcpQuery
* ImplCreateDhcpQuery() override
{
172 return new DelayingDhcpQuery();
176 // For RealFetchWithDeferredCancel, below.
177 class DelayingDhcpProxyScriptFetcherWin
178 : public DhcpProxyScriptFetcherWin
{
180 explicit DelayingDhcpProxyScriptFetcherWin(
181 URLRequestContext
* context
)
182 : DhcpProxyScriptFetcherWin(context
) {
185 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() override
{
186 return new DelayingDhcpProxyScriptAdapterFetcher(url_request_context(),
191 TEST(DhcpProxyScriptFetcherWin
, RealFetchWithDeferredCancel
) {
192 // Does a Fetch() with a slightly delayed cancel. As before, just
193 // exercises the code without stubbing out dependencies, but
194 // introduces a guaranteed 20 ms delay on the worker threads so that
195 // the cancel is called before they complete.
196 RealFetchTester fetcher
;
197 fetcher
.fetcher_
.reset(
198 new DelayingDhcpProxyScriptFetcherWin(fetcher
.context_
.get()));
199 fetcher
.on_completion_is_error_
= true;
200 fetcher
.RunTestWithDeferredCancel();
201 fetcher
.WaitUntilDone();
204 // The remaining tests are to exercise our state machine in various
205 // situations, with actual network access fully stubbed out.
207 class DummyDhcpProxyScriptAdapterFetcher
208 : public DhcpProxyScriptAdapterFetcher
{
210 DummyDhcpProxyScriptAdapterFetcher(URLRequestContext
* context
,
211 scoped_refptr
<base::TaskRunner
> runner
)
212 : DhcpProxyScriptAdapterFetcher(context
, runner
),
215 pac_script_(L
"bingo"),
219 void Fetch(const std::string
& adapter_name
,
220 const CompletionCallback
& callback
) override
{
221 callback_
= callback
;
222 timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(fetch_delay_ms_
),
223 this, &DummyDhcpProxyScriptAdapterFetcher::OnTimer
);
226 void Cancel() override
{
230 bool DidFinish() const override
{
234 int GetResult() const override
{
238 base::string16
GetPacScript() const override
{
243 callback_
.Run(result_
);
246 void Configure(bool did_finish
,
248 base::string16 pac_script
,
249 int fetch_delay_ms
) {
250 did_finish_
= did_finish
;
252 pac_script_
= pac_script
;
253 fetch_delay_ms_
= fetch_delay_ms
;
259 base::string16 pac_script_
;
261 CompletionCallback callback_
;
262 base::OneShotTimer
<DummyDhcpProxyScriptAdapterFetcher
> timer_
;
265 class MockDhcpProxyScriptFetcherWin
: public DhcpProxyScriptFetcherWin
{
267 class MockAdapterQuery
: public AdapterQuery
{
272 ~MockAdapterQuery() override
{}
274 bool ImplGetCandidateAdapterNames(
275 std::set
<std::string
>* adapter_names
) override
{
276 adapter_names
->insert(
277 mock_adapter_names_
.begin(), mock_adapter_names_
.end());
281 std::vector
<std::string
> mock_adapter_names_
;
284 MockDhcpProxyScriptFetcherWin(URLRequestContext
* context
)
285 : DhcpProxyScriptFetcherWin(context
),
286 num_fetchers_created_(0),
287 worker_finished_event_(true, false) {
291 ~MockDhcpProxyScriptFetcherWin() override
{ ResetTestState(); }
293 using DhcpProxyScriptFetcherWin::GetTaskRunner
;
295 // Adds a fetcher object to the queue of fetchers used by
296 // |ImplCreateAdapterFetcher()|, and its name to the list of adapters
297 // returned by ImplGetCandidateAdapterNames.
298 void PushBackAdapter(const std::string
& adapter_name
,
299 DhcpProxyScriptAdapterFetcher
* fetcher
) {
300 adapter_query_
->mock_adapter_names_
.push_back(adapter_name
);
301 adapter_fetchers_
.push_back(fetcher
);
304 void ConfigureAndPushBackAdapter(const std::string
& adapter_name
,
307 base::string16 pac_script
,
308 base::TimeDelta fetch_delay
) {
309 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
310 new DummyDhcpProxyScriptAdapterFetcher(url_request_context(),
312 adapter_fetcher
->Configure(
313 did_finish
, result
, pac_script
, fetch_delay
.InMilliseconds());
314 PushBackAdapter(adapter_name
, adapter_fetcher
.release());
317 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() override
{
318 ++num_fetchers_created_
;
319 return adapter_fetchers_
[next_adapter_fetcher_index_
++];
322 AdapterQuery
* ImplCreateAdapterQuery() override
{
323 DCHECK(adapter_query_
.get());
324 return adapter_query_
.get();
327 base::TimeDelta
ImplGetMaxWait() override
{
331 void ImplOnGetCandidateAdapterNamesDone() override
{
332 worker_finished_event_
.Signal();
335 void ResetTestState() {
336 // Delete any adapter fetcher objects we didn't hand out.
337 std::vector
<DhcpProxyScriptAdapterFetcher
*>::const_iterator it
338 = adapter_fetchers_
.begin();
339 for (; it
!= adapter_fetchers_
.end(); ++it
) {
340 if (num_fetchers_created_
-- <= 0) {
345 next_adapter_fetcher_index_
= 0;
346 num_fetchers_created_
= 0;
347 adapter_fetchers_
.clear();
348 adapter_query_
= new MockAdapterQuery();
349 max_wait_
= TestTimeouts::tiny_timeout();
352 bool HasPendingFetchers() {
353 return num_pending_fetchers() > 0;
356 int next_adapter_fetcher_index_
;
358 // Ownership gets transferred to the implementation class via
359 // ImplCreateAdapterFetcher, but any objects not handed out are
360 // deleted on destruction.
361 std::vector
<DhcpProxyScriptAdapterFetcher
*> adapter_fetchers_
;
363 scoped_refptr
<MockAdapterQuery
> adapter_query_
;
365 base::TimeDelta max_wait_
;
366 int num_fetchers_created_
;
367 base::WaitableEvent worker_finished_event_
;
370 class FetcherClient
{
373 : context_(new TestURLRequestContext
),
374 fetcher_(context_
.get()),
376 result_(ERR_UNEXPECTED
) {
380 int result
= fetcher_
.Fetch(
382 base::Bind(&FetcherClient::OnCompletion
, base::Unretained(this)));
383 ASSERT_EQ(ERR_IO_PENDING
, result
);
386 void RunMessageLoopUntilComplete() {
388 base::MessageLoop::current()->RunUntilIdle();
390 base::MessageLoop::current()->RunUntilIdle();
393 void RunMessageLoopUntilWorkerDone() {
394 DCHECK(fetcher_
.adapter_query_
.get());
395 while (!fetcher_
.worker_finished_event_
.TimedWait(
396 base::TimeDelta::FromMilliseconds(10))) {
397 base::MessageLoop::current()->RunUntilIdle();
401 void OnCompletion(int result
) {
406 void ResetTestState() {
408 result_
= ERR_UNEXPECTED
;
410 fetcher_
.ResetTestState();
413 scoped_refptr
<base::TaskRunner
> GetTaskRunner() {
414 return fetcher_
.GetTaskRunner();
417 scoped_ptr
<URLRequestContext
> context_
;
418 MockDhcpProxyScriptFetcherWin fetcher_
;
421 base::string16 pac_text_
;
424 // We separate out each test's logic so that we can easily implement
425 // the ReuseFetcher test at the bottom.
426 void TestNormalCaseURLConfiguredOneAdapter(FetcherClient
* client
) {
427 TestURLRequestContext context
;
428 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
429 new DummyDhcpProxyScriptAdapterFetcher(&context
,
430 client
->GetTaskRunner()));
431 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
432 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
434 client
->RunMessageLoopUntilComplete();
435 ASSERT_EQ(OK
, client
->result_
);
436 ASSERT_EQ(L
"bingo", client
->pac_text_
);
439 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredOneAdapter
) {
440 FetcherClient client
;
441 TestNormalCaseURLConfiguredOneAdapter(&client
);
444 void TestNormalCaseURLConfiguredMultipleAdapters(FetcherClient
* client
) {
445 client
->fetcher_
.ConfigureAndPushBackAdapter(
446 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
447 base::TimeDelta::FromMilliseconds(1));
448 client
->fetcher_
.ConfigureAndPushBackAdapter(
449 "second", true, OK
, L
"bingo", base::TimeDelta::FromMilliseconds(50));
450 client
->fetcher_
.ConfigureAndPushBackAdapter(
451 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
453 client
->RunMessageLoopUntilComplete();
454 ASSERT_EQ(OK
, client
->result_
);
455 ASSERT_EQ(L
"bingo", client
->pac_text_
);
458 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredMultipleAdapters
) {
459 FetcherClient client
;
460 TestNormalCaseURLConfiguredMultipleAdapters(&client
);
463 void TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(
464 FetcherClient
* client
) {
465 client
->fetcher_
.ConfigureAndPushBackAdapter(
466 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
467 base::TimeDelta::FromMilliseconds(1));
468 // This will time out.
469 client
->fetcher_
.ConfigureAndPushBackAdapter(
470 "second", false, ERR_IO_PENDING
, L
"bingo",
471 TestTimeouts::action_timeout());
472 client
->fetcher_
.ConfigureAndPushBackAdapter(
473 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
475 client
->RunMessageLoopUntilComplete();
476 ASSERT_EQ(OK
, client
->result_
);
477 ASSERT_EQ(L
"rocko", client
->pac_text_
);
480 TEST(DhcpProxyScriptFetcherWin
,
481 NormalCaseURLConfiguredMultipleAdaptersWithTimeout
) {
482 FetcherClient client
;
483 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
486 void TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(
487 FetcherClient
* client
) {
488 client
->fetcher_
.ConfigureAndPushBackAdapter(
489 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
490 base::TimeDelta::FromMilliseconds(1));
491 // This will time out.
492 client
->fetcher_
.ConfigureAndPushBackAdapter(
493 "second", false, ERR_IO_PENDING
, L
"bingo",
494 TestTimeouts::action_timeout());
495 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
497 client
->fetcher_
.ConfigureAndPushBackAdapter(
498 "third", true, ERR_PAC_STATUS_NOT_OK
, L
"",
499 base::TimeDelta::FromMilliseconds(1));
500 client
->fetcher_
.ConfigureAndPushBackAdapter(
501 "fourth", true, ERR_NOT_IMPLEMENTED
, L
"",
502 base::TimeDelta::FromMilliseconds(1));
504 client
->RunMessageLoopUntilComplete();
505 ASSERT_EQ(ERR_PAC_STATUS_NOT_OK
, client
->result_
);
506 ASSERT_EQ(L
"", client
->pac_text_
);
509 TEST(DhcpProxyScriptFetcherWin
,
510 FailureCaseURLConfiguredMultipleAdaptersWithTimeout
) {
511 FetcherClient client
;
512 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
515 void TestFailureCaseNoURLConfigured(FetcherClient
* client
) {
516 client
->fetcher_
.ConfigureAndPushBackAdapter(
517 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
518 base::TimeDelta::FromMilliseconds(1));
519 // This will time out.
520 client
->fetcher_
.ConfigureAndPushBackAdapter(
521 "second", false, ERR_IO_PENDING
, L
"bingo",
522 TestTimeouts::action_timeout());
523 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
525 client
->fetcher_
.ConfigureAndPushBackAdapter(
526 "third", true, ERR_PAC_NOT_IN_DHCP
, L
"",
527 base::TimeDelta::FromMilliseconds(1));
529 client
->RunMessageLoopUntilComplete();
530 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
531 ASSERT_EQ(L
"", client
->pac_text_
);
534 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoURLConfigured
) {
535 FetcherClient client
;
536 TestFailureCaseNoURLConfigured(&client
);
539 void TestFailureCaseNoDhcpAdapters(FetcherClient
* client
) {
541 client
->RunMessageLoopUntilComplete();
542 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
543 ASSERT_EQ(L
"", client
->pac_text_
);
544 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
547 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoDhcpAdapters
) {
548 FetcherClient client
;
549 TestFailureCaseNoDhcpAdapters(&client
);
552 void TestShortCircuitLessPreferredAdapters(FetcherClient
* client
) {
553 // Here we have a bunch of adapters; the first reports no PAC in DHCP,
554 // the second responds quickly with a PAC file, the rest take a long
555 // time. Verify that we complete quickly and do not wait for the slow
556 // adapters, i.e. we finish before timeout.
557 client
->fetcher_
.ConfigureAndPushBackAdapter(
558 "1", true, ERR_PAC_NOT_IN_DHCP
, L
"",
559 base::TimeDelta::FromMilliseconds(1));
560 client
->fetcher_
.ConfigureAndPushBackAdapter(
561 "2", true, OK
, L
"bingo",
562 base::TimeDelta::FromMilliseconds(1));
563 client
->fetcher_
.ConfigureAndPushBackAdapter(
564 "3", true, OK
, L
"wrongo", TestTimeouts::action_max_timeout());
566 // Increase the timeout to ensure the short circuit mechanism has
567 // time to kick in before the timeout waiting for more adapters kicks in.
568 client
->fetcher_
.max_wait_
= TestTimeouts::action_timeout();
570 base::ElapsedTimer timer
;
572 client
->RunMessageLoopUntilComplete();
573 ASSERT_TRUE(client
->fetcher_
.HasPendingFetchers());
574 // Assert that the time passed is definitely less than the wait timer
575 // timeout, to get a second signal that it was the shortcut mechanism
576 // (in OnFetcherDone) that kicked in, and not the timeout waiting for
578 ASSERT_GT(client
->fetcher_
.max_wait_
- (client
->fetcher_
.max_wait_
/ 10),
582 TEST(DhcpProxyScriptFetcherWin
, ShortCircuitLessPreferredAdapters
) {
583 FetcherClient client
;
584 TestShortCircuitLessPreferredAdapters(&client
);
587 void TestImmediateCancel(FetcherClient
* client
) {
588 TestURLRequestContext context
;
589 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
590 new DummyDhcpProxyScriptAdapterFetcher(&context
,
591 client
->GetTaskRunner()));
592 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
593 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
595 client
->fetcher_
.Cancel();
596 client
->RunMessageLoopUntilWorkerDone();
597 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
600 // Regression test to check that when we cancel immediately, no
601 // adapter fetchers get created.
602 TEST(DhcpProxyScriptFetcherWin
, ImmediateCancel
) {
603 FetcherClient client
;
604 TestImmediateCancel(&client
);
607 TEST(DhcpProxyScriptFetcherWin
, ReuseFetcher
) {
608 FetcherClient client
;
610 // The ProxyScriptFetcher interface stipulates that only a single
611 // |Fetch()| may be in flight at once, but allows reuse, so test
612 // that the state transitions correctly from done to start in all
613 // cases we're testing.
615 typedef void (*FetcherClientTestFunction
)(FetcherClient
*);
616 typedef std::vector
<FetcherClientTestFunction
> TestVector
;
617 TestVector test_functions
;
618 test_functions
.push_back(TestNormalCaseURLConfiguredOneAdapter
);
619 test_functions
.push_back(TestNormalCaseURLConfiguredMultipleAdapters
);
620 test_functions
.push_back(
621 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout
);
622 test_functions
.push_back(
623 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout
);
624 test_functions
.push_back(TestFailureCaseNoURLConfigured
);
625 test_functions
.push_back(TestFailureCaseNoDhcpAdapters
);
626 test_functions
.push_back(TestShortCircuitLessPreferredAdapters
);
627 test_functions
.push_back(TestImmediateCancel
);
629 std::random_shuffle(test_functions
.begin(),
630 test_functions
.end(),
631 base::RandGenerator
);
632 for (TestVector::const_iterator it
= test_functions
.begin();
633 it
!= test_functions
.end();
636 client
.ResetTestState();
639 // Re-do the first test to make sure the last test that was run did
640 // not leave things in a bad state.
641 (*test_functions
.begin())(&client
);