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/perftimer.h"
13 #include "base/rand_util.h"
14 #include "base/test/test_timeouts.h"
15 #include "base/threading/platform_thread.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
;
40 DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp(adapter_name
);
41 printf("Adapter '%s' has PAC URL '%s' configured in DHCP.\n",
47 // Helper for RealFetch* tests below.
48 class RealFetchTester
{
51 : context_(new TestURLRequestContext
),
52 fetcher_(new DhcpProxyScriptFetcherWin(context_
.get())),
54 on_completion_is_error_(false) {
55 // Make sure the test ends.
56 timeout_
.Start(FROM_HERE
,
57 base::TimeDelta::FromSeconds(5), this, &RealFetchTester::OnTimeout
);
61 int result
= fetcher_
->Fetch(
63 base::Bind(&RealFetchTester::OnCompletion
, base::Unretained(this)));
64 if (result
!= ERR_IO_PENDING
)
68 void RunTestWithCancel() {
73 void RunTestWithDeferredCancel() {
74 // Put the cancellation into the queue before even running the
75 // test to avoid the chance of one of the adapter fetcher worker
76 // threads completing before cancellation. See http://crbug.com/86756.
77 cancel_timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(0),
78 this, &RealFetchTester::OnCancelTimer
);
82 void OnCompletion(int result
) {
83 if (on_completion_is_error_
) {
84 FAIL() << "Received completion for test in which this is error.";
87 printf("Result code %d PAC data length %d\n", result
, pac_text_
.size());
95 void OnCancelTimer() {
100 void WaitUntilDone() {
102 base::MessageLoop::current()->RunUntilIdle();
104 base::MessageLoop::current()->RunUntilIdle();
107 // Attempts to give worker threads time to finish. This is currently
108 // very simplistic as completion (via completion callback or cancellation)
109 // immediately "detaches" any worker threads, so the best we can do is give
110 // them a little time. If we start running into Valgrind leaks, we can
111 // do something a bit more clever to track worker threads even when the
112 // DhcpProxyScriptFetcherWin state machine has finished.
113 void FinishTestAllowCleanup() {
114 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(30));
117 scoped_ptr
<URLRequestContext
> context_
;
118 scoped_ptr
<DhcpProxyScriptFetcherWin
> fetcher_
;
120 base::string16 pac_text_
;
121 base::OneShotTimer
<RealFetchTester
> timeout_
;
122 base::OneShotTimer
<RealFetchTester
> cancel_timer_
;
123 bool on_completion_is_error_
;
126 TEST(DhcpProxyScriptFetcherWin
, RealFetch
) {
127 // This tests a call to Fetch() with no stubbing out of dependencies.
129 // We don't make assumptions about the environment this unit test is
130 // running in, so it just exercises the code to make sure there
131 // is no crash and no unexpected error returned, but does not assert on
132 // results beyond that.
133 RealFetchTester fetcher
;
136 fetcher
.WaitUntilDone();
137 printf("PAC URL was %s\n",
138 fetcher
.fetcher_
->GetPacURL().possibly_invalid_spec().c_str());
140 fetcher
.FinishTestAllowCleanup();
143 TEST(DhcpProxyScriptFetcherWin
, RealFetchWithCancel
) {
144 // Does a Fetch() with an immediate cancel. As before, just
145 // exercises the code without stubbing out dependencies.
146 RealFetchTester fetcher
;
147 fetcher
.RunTestWithCancel();
148 base::MessageLoop::current()->RunUntilIdle();
150 // Attempt to avoid Valgrind leak reports in case worker thread is
152 fetcher
.FinishTestAllowCleanup();
155 // For RealFetchWithDeferredCancel, below.
156 class DelayingDhcpProxyScriptAdapterFetcher
157 : public DhcpProxyScriptAdapterFetcher
{
159 explicit DelayingDhcpProxyScriptAdapterFetcher(
160 URLRequestContext
* url_request_context
)
161 : DhcpProxyScriptAdapterFetcher(url_request_context
) {
164 class DelayingDhcpQuery
: public DhcpQuery
{
166 explicit DelayingDhcpQuery()
170 std::string
ImplGetPacURLFromDhcp(
171 const std::string
& adapter_name
) OVERRIDE
{
172 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
173 return DhcpQuery::ImplGetPacURLFromDhcp(adapter_name
);
177 DhcpQuery
* ImplCreateDhcpQuery() OVERRIDE
{
178 return new DelayingDhcpQuery();
182 // For RealFetchWithDeferredCancel, below.
183 class DelayingDhcpProxyScriptFetcherWin
184 : public DhcpProxyScriptFetcherWin
{
186 explicit DelayingDhcpProxyScriptFetcherWin(
187 URLRequestContext
* context
)
188 : DhcpProxyScriptFetcherWin(context
) {
191 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() OVERRIDE
{
192 return new DelayingDhcpProxyScriptAdapterFetcher(url_request_context());
196 TEST(DhcpProxyScriptFetcherWin
, RealFetchWithDeferredCancel
) {
197 // Does a Fetch() with a slightly delayed cancel. As before, just
198 // exercises the code without stubbing out dependencies, but
199 // introduces a guaranteed 20 ms delay on the worker threads so that
200 // the cancel is called before they complete.
201 RealFetchTester fetcher
;
202 fetcher
.fetcher_
.reset(
203 new DelayingDhcpProxyScriptFetcherWin(fetcher
.context_
.get()));
204 fetcher
.on_completion_is_error_
= true;
205 fetcher
.RunTestWithDeferredCancel();
206 fetcher
.WaitUntilDone();
209 // The remaining tests are to exercise our state machine in various
210 // situations, with actual network access fully stubbed out.
212 class DummyDhcpProxyScriptAdapterFetcher
213 : public DhcpProxyScriptAdapterFetcher
{
215 explicit DummyDhcpProxyScriptAdapterFetcher(URLRequestContext
* context
)
216 : DhcpProxyScriptAdapterFetcher(context
),
219 pac_script_(L
"bingo"),
223 void Fetch(const std::string
& adapter_name
,
224 const CompletionCallback
& callback
) OVERRIDE
{
225 callback_
= callback
;
226 timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(fetch_delay_ms_
),
227 this, &DummyDhcpProxyScriptAdapterFetcher::OnTimer
);
230 void Cancel() OVERRIDE
{
234 bool DidFinish() const OVERRIDE
{
238 int GetResult() const OVERRIDE
{
242 base::string16
GetPacScript() const OVERRIDE
{
247 callback_
.Run(result_
);
250 void Configure(bool did_finish
,
252 base::string16 pac_script
,
253 int fetch_delay_ms
) {
254 did_finish_
= did_finish
;
256 pac_script_
= pac_script
;
257 fetch_delay_ms_
= fetch_delay_ms
;
263 base::string16 pac_script_
;
265 CompletionCallback callback_
;
266 base::OneShotTimer
<DummyDhcpProxyScriptAdapterFetcher
> timer_
;
269 class MockDhcpProxyScriptFetcherWin
: public DhcpProxyScriptFetcherWin
{
271 class MockAdapterQuery
: public AdapterQuery
{
276 virtual ~MockAdapterQuery() {
279 virtual bool ImplGetCandidateAdapterNames(
280 std::set
<std::string
>* adapter_names
) OVERRIDE
{
281 adapter_names
->insert(
282 mock_adapter_names_
.begin(), mock_adapter_names_
.end());
286 std::vector
<std::string
> mock_adapter_names_
;
289 MockDhcpProxyScriptFetcherWin(URLRequestContext
* context
)
290 : DhcpProxyScriptFetcherWin(context
),
291 num_fetchers_created_(0),
292 worker_finished_event_(true, false) {
296 virtual ~MockDhcpProxyScriptFetcherWin() {
300 // Adds a fetcher object to the queue of fetchers used by
301 // |ImplCreateAdapterFetcher()|, and its name to the list of adapters
302 // returned by ImplGetCandidateAdapterNames.
303 void PushBackAdapter(const std::string
& adapter_name
,
304 DhcpProxyScriptAdapterFetcher
* fetcher
) {
305 adapter_query_
->mock_adapter_names_
.push_back(adapter_name
);
306 adapter_fetchers_
.push_back(fetcher
);
309 void ConfigureAndPushBackAdapter(const std::string
& adapter_name
,
312 base::string16 pac_script
,
313 base::TimeDelta fetch_delay
) {
314 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
315 new DummyDhcpProxyScriptAdapterFetcher(url_request_context()));
316 adapter_fetcher
->Configure(
317 did_finish
, result
, pac_script
, fetch_delay
.InMilliseconds());
318 PushBackAdapter(adapter_name
, adapter_fetcher
.release());
321 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() OVERRIDE
{
322 ++num_fetchers_created_
;
323 return adapter_fetchers_
[next_adapter_fetcher_index_
++];
326 virtual AdapterQuery
* ImplCreateAdapterQuery() OVERRIDE
{
327 DCHECK(adapter_query_
);
328 return adapter_query_
.get();
331 base::TimeDelta
ImplGetMaxWait() OVERRIDE
{
335 void ImplOnGetCandidateAdapterNamesDone() OVERRIDE
{
336 worker_finished_event_
.Signal();
339 void ResetTestState() {
340 // Delete any adapter fetcher objects we didn't hand out.
341 std::vector
<DhcpProxyScriptAdapterFetcher
*>::const_iterator it
342 = adapter_fetchers_
.begin();
343 for (; it
!= adapter_fetchers_
.end(); ++it
) {
344 if (num_fetchers_created_
-- <= 0) {
349 next_adapter_fetcher_index_
= 0;
350 num_fetchers_created_
= 0;
351 adapter_fetchers_
.clear();
352 adapter_query_
= new MockAdapterQuery();
353 max_wait_
= TestTimeouts::tiny_timeout();
356 bool HasPendingFetchers() {
357 return num_pending_fetchers() > 0;
360 int next_adapter_fetcher_index_
;
362 // Ownership gets transferred to the implementation class via
363 // ImplCreateAdapterFetcher, but any objects not handed out are
364 // deleted on destruction.
365 std::vector
<DhcpProxyScriptAdapterFetcher
*> adapter_fetchers_
;
367 scoped_refptr
<MockAdapterQuery
> adapter_query_
;
369 base::TimeDelta max_wait_
;
370 int num_fetchers_created_
;
371 base::WaitableEvent worker_finished_event_
;
374 class FetcherClient
{
377 : context_(new TestURLRequestContext
),
378 fetcher_(context_
.get()),
380 result_(ERR_UNEXPECTED
) {
384 int result
= fetcher_
.Fetch(
386 base::Bind(&FetcherClient::OnCompletion
, base::Unretained(this)));
387 ASSERT_EQ(ERR_IO_PENDING
, result
);
390 void RunMessageLoopUntilComplete() {
392 base::MessageLoop::current()->RunUntilIdle();
394 base::MessageLoop::current()->RunUntilIdle();
397 void RunMessageLoopUntilWorkerDone() {
398 DCHECK(fetcher_
.adapter_query_
.get());
399 while (!fetcher_
.worker_finished_event_
.TimedWait(
400 base::TimeDelta::FromMilliseconds(10))) {
401 base::MessageLoop::current()->RunUntilIdle();
405 void OnCompletion(int result
) {
410 void ResetTestState() {
412 result_
= ERR_UNEXPECTED
;
414 fetcher_
.ResetTestState();
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 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
431 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
433 client
->RunMessageLoopUntilComplete();
434 ASSERT_EQ(OK
, client
->result_
);
435 ASSERT_EQ(L
"bingo", client
->pac_text_
);
438 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredOneAdapter
) {
439 FetcherClient client
;
440 TestNormalCaseURLConfiguredOneAdapter(&client
);
443 void TestNormalCaseURLConfiguredMultipleAdapters(FetcherClient
* client
) {
444 client
->fetcher_
.ConfigureAndPushBackAdapter(
445 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
446 base::TimeDelta::FromMilliseconds(1));
447 client
->fetcher_
.ConfigureAndPushBackAdapter(
448 "second", true, OK
, L
"bingo", base::TimeDelta::FromMilliseconds(50));
449 client
->fetcher_
.ConfigureAndPushBackAdapter(
450 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
452 client
->RunMessageLoopUntilComplete();
453 ASSERT_EQ(OK
, client
->result_
);
454 ASSERT_EQ(L
"bingo", client
->pac_text_
);
457 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredMultipleAdapters
) {
458 FetcherClient client
;
459 TestNormalCaseURLConfiguredMultipleAdapters(&client
);
462 void TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(
463 FetcherClient
* client
) {
464 client
->fetcher_
.ConfigureAndPushBackAdapter(
465 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
466 base::TimeDelta::FromMilliseconds(1));
467 // This will time out.
468 client
->fetcher_
.ConfigureAndPushBackAdapter(
469 "second", false, ERR_IO_PENDING
, L
"bingo",
470 TestTimeouts::action_timeout());
471 client
->fetcher_
.ConfigureAndPushBackAdapter(
472 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
474 client
->RunMessageLoopUntilComplete();
475 ASSERT_EQ(OK
, client
->result_
);
476 ASSERT_EQ(L
"rocko", client
->pac_text_
);
479 TEST(DhcpProxyScriptFetcherWin
,
480 NormalCaseURLConfiguredMultipleAdaptersWithTimeout
) {
481 FetcherClient client
;
482 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
485 void TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(
486 FetcherClient
* client
) {
487 client
->fetcher_
.ConfigureAndPushBackAdapter(
488 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
489 base::TimeDelta::FromMilliseconds(1));
490 // This will time out.
491 client
->fetcher_
.ConfigureAndPushBackAdapter(
492 "second", false, ERR_IO_PENDING
, L
"bingo",
493 TestTimeouts::action_timeout());
494 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
496 client
->fetcher_
.ConfigureAndPushBackAdapter(
497 "third", true, ERR_PAC_STATUS_NOT_OK
, L
"",
498 base::TimeDelta::FromMilliseconds(1));
499 client
->fetcher_
.ConfigureAndPushBackAdapter(
500 "fourth", true, ERR_NOT_IMPLEMENTED
, L
"",
501 base::TimeDelta::FromMilliseconds(1));
503 client
->RunMessageLoopUntilComplete();
504 ASSERT_EQ(ERR_PAC_STATUS_NOT_OK
, client
->result_
);
505 ASSERT_EQ(L
"", client
->pac_text_
);
508 TEST(DhcpProxyScriptFetcherWin
,
509 FailureCaseURLConfiguredMultipleAdaptersWithTimeout
) {
510 FetcherClient client
;
511 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
514 void TestFailureCaseNoURLConfigured(FetcherClient
* client
) {
515 client
->fetcher_
.ConfigureAndPushBackAdapter(
516 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
517 base::TimeDelta::FromMilliseconds(1));
518 // This will time out.
519 client
->fetcher_
.ConfigureAndPushBackAdapter(
520 "second", false, ERR_IO_PENDING
, L
"bingo",
521 TestTimeouts::action_timeout());
522 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
524 client
->fetcher_
.ConfigureAndPushBackAdapter(
525 "third", true, ERR_PAC_NOT_IN_DHCP
, L
"",
526 base::TimeDelta::FromMilliseconds(1));
528 client
->RunMessageLoopUntilComplete();
529 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
530 ASSERT_EQ(L
"", client
->pac_text_
);
533 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoURLConfigured
) {
534 FetcherClient client
;
535 TestFailureCaseNoURLConfigured(&client
);
538 void TestFailureCaseNoDhcpAdapters(FetcherClient
* client
) {
540 client
->RunMessageLoopUntilComplete();
541 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
542 ASSERT_EQ(L
"", client
->pac_text_
);
543 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
546 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoDhcpAdapters
) {
547 FetcherClient client
;
548 TestFailureCaseNoDhcpAdapters(&client
);
551 void TestShortCircuitLessPreferredAdapters(FetcherClient
* client
) {
552 // Here we have a bunch of adapters; the first reports no PAC in DHCP,
553 // the second responds quickly with a PAC file, the rest take a long
554 // time. Verify that we complete quickly and do not wait for the slow
555 // adapters, i.e. we finish before timeout.
556 client
->fetcher_
.ConfigureAndPushBackAdapter(
557 "1", true, ERR_PAC_NOT_IN_DHCP
, L
"",
558 base::TimeDelta::FromMilliseconds(1));
559 client
->fetcher_
.ConfigureAndPushBackAdapter(
560 "2", true, OK
, L
"bingo",
561 base::TimeDelta::FromMilliseconds(1));
562 client
->fetcher_
.ConfigureAndPushBackAdapter(
563 "3", true, OK
, L
"wrongo", TestTimeouts::action_max_timeout());
565 // Increase the timeout to ensure the short circuit mechanism has
566 // time to kick in before the timeout waiting for more adapters kicks in.
567 client
->fetcher_
.max_wait_
= TestTimeouts::action_timeout();
571 client
->RunMessageLoopUntilComplete();
572 ASSERT_TRUE(client
->fetcher_
.HasPendingFetchers());
573 // Assert that the time passed is definitely less than the wait timer
574 // timeout, to get a second signal that it was the shortcut mechanism
575 // (in OnFetcherDone) that kicked in, and not the timeout waiting for
577 ASSERT_GT(client
->fetcher_
.max_wait_
- (client
->fetcher_
.max_wait_
/ 10),
581 TEST(DhcpProxyScriptFetcherWin
, ShortCircuitLessPreferredAdapters
) {
582 FetcherClient client
;
583 TestShortCircuitLessPreferredAdapters(&client
);
586 void TestImmediateCancel(FetcherClient
* client
) {
587 TestURLRequestContext context
;
588 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
589 new DummyDhcpProxyScriptAdapterFetcher(&context
));
590 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
591 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
593 client
->fetcher_
.Cancel();
594 client
->RunMessageLoopUntilWorkerDone();
595 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
598 // Regression test to check that when we cancel immediately, no
599 // adapter fetchers get created.
600 TEST(DhcpProxyScriptFetcherWin
, ImmediateCancel
) {
601 FetcherClient client
;
602 TestImmediateCancel(&client
);
605 TEST(DhcpProxyScriptFetcherWin
, ReuseFetcher
) {
606 FetcherClient client
;
608 // The ProxyScriptFetcher interface stipulates that only a single
609 // |Fetch()| may be in flight at once, but allows reuse, so test
610 // that the state transitions correctly from done to start in all
611 // cases we're testing.
613 typedef void (*FetcherClientTestFunction
)(FetcherClient
*);
614 typedef std::vector
<FetcherClientTestFunction
> TestVector
;
615 TestVector test_functions
;
616 test_functions
.push_back(TestNormalCaseURLConfiguredOneAdapter
);
617 test_functions
.push_back(TestNormalCaseURLConfiguredMultipleAdapters
);
618 test_functions
.push_back(
619 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout
);
620 test_functions
.push_back(
621 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout
);
622 test_functions
.push_back(TestFailureCaseNoURLConfigured
);
623 test_functions
.push_back(TestFailureCaseNoDhcpAdapters
);
624 test_functions
.push_back(TestShortCircuitLessPreferredAdapters
);
625 test_functions
.push_back(TestImmediateCancel
);
627 std::random_shuffle(test_functions
.begin(),
628 test_functions
.end(),
629 base::RandGenerator
);
630 for (TestVector::const_iterator it
= test_functions
.begin();
631 it
!= test_functions
.end();
634 client
.ResetTestState();
637 // Re-do the first test to make sure the last test that was run did
638 // not leave things in a bad state.
639 (*test_functions
.begin())(&client
);