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.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 MessageLoop::current()->RunUntilIdle();
104 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_
;
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 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 string16
GetPacScript() const OVERRIDE
{
247 callback_
.Run(result_
);
251 bool did_finish
, int result
, string16 pac_script
, int fetch_delay_ms
) {
252 did_finish_
= did_finish
;
254 pac_script_
= pac_script
;
255 fetch_delay_ms_
= fetch_delay_ms
;
261 string16 pac_script_
;
263 CompletionCallback callback_
;
264 base::OneShotTimer
<DummyDhcpProxyScriptAdapterFetcher
> timer_
;
267 class MockDhcpProxyScriptFetcherWin
: public DhcpProxyScriptFetcherWin
{
269 class MockAdapterQuery
: public AdapterQuery
{
274 virtual ~MockAdapterQuery() {
277 virtual bool ImplGetCandidateAdapterNames(
278 std::set
<std::string
>* adapter_names
) OVERRIDE
{
279 adapter_names
->insert(
280 mock_adapter_names_
.begin(), mock_adapter_names_
.end());
284 std::vector
<std::string
> mock_adapter_names_
;
287 MockDhcpProxyScriptFetcherWin(URLRequestContext
* context
)
288 : DhcpProxyScriptFetcherWin(context
),
289 num_fetchers_created_(0),
290 worker_finished_event_(true, false) {
294 virtual ~MockDhcpProxyScriptFetcherWin() {
298 // Adds a fetcher object to the queue of fetchers used by
299 // |ImplCreateAdapterFetcher()|, and its name to the list of adapters
300 // returned by ImplGetCandidateAdapterNames.
301 void PushBackAdapter(const std::string
& adapter_name
,
302 DhcpProxyScriptAdapterFetcher
* fetcher
) {
303 adapter_query_
->mock_adapter_names_
.push_back(adapter_name
);
304 adapter_fetchers_
.push_back(fetcher
);
307 void ConfigureAndPushBackAdapter(const std::string
& adapter_name
,
311 base::TimeDelta fetch_delay
) {
312 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
313 new DummyDhcpProxyScriptAdapterFetcher(url_request_context()));
314 adapter_fetcher
->Configure(
315 did_finish
, result
, pac_script
, fetch_delay
.InMilliseconds());
316 PushBackAdapter(adapter_name
, adapter_fetcher
.release());
319 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() OVERRIDE
{
320 ++num_fetchers_created_
;
321 return adapter_fetchers_
[next_adapter_fetcher_index_
++];
324 virtual AdapterQuery
* ImplCreateAdapterQuery() OVERRIDE
{
325 DCHECK(adapter_query_
);
326 return adapter_query_
.get();
329 base::TimeDelta
ImplGetMaxWait() OVERRIDE
{
333 void ImplOnGetCandidateAdapterNamesDone() OVERRIDE
{
334 worker_finished_event_
.Signal();
337 void ResetTestState() {
338 // Delete any adapter fetcher objects we didn't hand out.
339 std::vector
<DhcpProxyScriptAdapterFetcher
*>::const_iterator it
340 = adapter_fetchers_
.begin();
341 for (; it
!= adapter_fetchers_
.end(); ++it
) {
342 if (num_fetchers_created_
-- <= 0) {
347 next_adapter_fetcher_index_
= 0;
348 num_fetchers_created_
= 0;
349 adapter_fetchers_
.clear();
350 adapter_query_
= new MockAdapterQuery();
351 max_wait_
= TestTimeouts::tiny_timeout();
354 bool HasPendingFetchers() {
355 return num_pending_fetchers() > 0;
358 int next_adapter_fetcher_index_
;
360 // Ownership gets transferred to the implementation class via
361 // ImplCreateAdapterFetcher, but any objects not handed out are
362 // deleted on destruction.
363 std::vector
<DhcpProxyScriptAdapterFetcher
*> adapter_fetchers_
;
365 scoped_refptr
<MockAdapterQuery
> adapter_query_
;
367 base::TimeDelta max_wait_
;
368 int num_fetchers_created_
;
369 base::WaitableEvent worker_finished_event_
;
372 class FetcherClient
{
375 : context_(new TestURLRequestContext
),
376 fetcher_(context_
.get()),
378 result_(ERR_UNEXPECTED
) {
382 int result
= fetcher_
.Fetch(
384 base::Bind(&FetcherClient::OnCompletion
, base::Unretained(this)));
385 ASSERT_EQ(ERR_IO_PENDING
, result
);
388 void RunMessageLoopUntilComplete() {
390 MessageLoop::current()->RunUntilIdle();
392 MessageLoop::current()->RunUntilIdle();
395 void RunMessageLoopUntilWorkerDone() {
396 DCHECK(fetcher_
.adapter_query_
.get());
397 while (!fetcher_
.worker_finished_event_
.TimedWait(
398 base::TimeDelta::FromMilliseconds(10))) {
399 MessageLoop::current()->RunUntilIdle();
403 void OnCompletion(int result
) {
408 void ResetTestState() {
410 result_
= ERR_UNEXPECTED
;
412 fetcher_
.ResetTestState();
415 scoped_ptr
<URLRequestContext
> context_
;
416 MockDhcpProxyScriptFetcherWin fetcher_
;
422 // We separate out each test's logic so that we can easily implement
423 // the ReuseFetcher test at the bottom.
424 void TestNormalCaseURLConfiguredOneAdapter(FetcherClient
* client
) {
425 TestURLRequestContext context
;
426 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
427 new DummyDhcpProxyScriptAdapterFetcher(&context
));
428 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
429 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
431 client
->RunMessageLoopUntilComplete();
432 ASSERT_EQ(OK
, client
->result_
);
433 ASSERT_EQ(L
"bingo", client
->pac_text_
);
436 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredOneAdapter
) {
437 FetcherClient client
;
438 TestNormalCaseURLConfiguredOneAdapter(&client
);
441 void TestNormalCaseURLConfiguredMultipleAdapters(FetcherClient
* client
) {
442 client
->fetcher_
.ConfigureAndPushBackAdapter(
443 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
444 base::TimeDelta::FromMilliseconds(1));
445 client
->fetcher_
.ConfigureAndPushBackAdapter(
446 "second", true, OK
, L
"bingo", base::TimeDelta::FromMilliseconds(50));
447 client
->fetcher_
.ConfigureAndPushBackAdapter(
448 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
450 client
->RunMessageLoopUntilComplete();
451 ASSERT_EQ(OK
, client
->result_
);
452 ASSERT_EQ(L
"bingo", client
->pac_text_
);
455 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredMultipleAdapters
) {
456 FetcherClient client
;
457 TestNormalCaseURLConfiguredMultipleAdapters(&client
);
460 void TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(
461 FetcherClient
* client
) {
462 client
->fetcher_
.ConfigureAndPushBackAdapter(
463 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
464 base::TimeDelta::FromMilliseconds(1));
465 // This will time out.
466 client
->fetcher_
.ConfigureAndPushBackAdapter(
467 "second", false, ERR_IO_PENDING
, L
"bingo",
468 TestTimeouts::action_timeout());
469 client
->fetcher_
.ConfigureAndPushBackAdapter(
470 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
472 client
->RunMessageLoopUntilComplete();
473 ASSERT_EQ(OK
, client
->result_
);
474 ASSERT_EQ(L
"rocko", client
->pac_text_
);
477 TEST(DhcpProxyScriptFetcherWin
,
478 NormalCaseURLConfiguredMultipleAdaptersWithTimeout
) {
479 FetcherClient client
;
480 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
483 void TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(
484 FetcherClient
* client
) {
485 client
->fetcher_
.ConfigureAndPushBackAdapter(
486 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
487 base::TimeDelta::FromMilliseconds(1));
488 // This will time out.
489 client
->fetcher_
.ConfigureAndPushBackAdapter(
490 "second", false, ERR_IO_PENDING
, L
"bingo",
491 TestTimeouts::action_timeout());
492 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
494 client
->fetcher_
.ConfigureAndPushBackAdapter(
495 "third", true, ERR_PAC_STATUS_NOT_OK
, L
"",
496 base::TimeDelta::FromMilliseconds(1));
497 client
->fetcher_
.ConfigureAndPushBackAdapter(
498 "fourth", true, ERR_NOT_IMPLEMENTED
, L
"",
499 base::TimeDelta::FromMilliseconds(1));
501 client
->RunMessageLoopUntilComplete();
502 ASSERT_EQ(ERR_PAC_STATUS_NOT_OK
, client
->result_
);
503 ASSERT_EQ(L
"", client
->pac_text_
);
506 TEST(DhcpProxyScriptFetcherWin
,
507 FailureCaseURLConfiguredMultipleAdaptersWithTimeout
) {
508 FetcherClient client
;
509 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
512 void TestFailureCaseNoURLConfigured(FetcherClient
* client
) {
513 client
->fetcher_
.ConfigureAndPushBackAdapter(
514 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
515 base::TimeDelta::FromMilliseconds(1));
516 // This will time out.
517 client
->fetcher_
.ConfigureAndPushBackAdapter(
518 "second", false, ERR_IO_PENDING
, L
"bingo",
519 TestTimeouts::action_timeout());
520 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
522 client
->fetcher_
.ConfigureAndPushBackAdapter(
523 "third", true, ERR_PAC_NOT_IN_DHCP
, L
"",
524 base::TimeDelta::FromMilliseconds(1));
526 client
->RunMessageLoopUntilComplete();
527 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
528 ASSERT_EQ(L
"", client
->pac_text_
);
531 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoURLConfigured
) {
532 FetcherClient client
;
533 TestFailureCaseNoURLConfigured(&client
);
536 void TestFailureCaseNoDhcpAdapters(FetcherClient
* client
) {
538 client
->RunMessageLoopUntilComplete();
539 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
540 ASSERT_EQ(L
"", client
->pac_text_
);
541 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
544 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoDhcpAdapters
) {
545 FetcherClient client
;
546 TestFailureCaseNoDhcpAdapters(&client
);
549 void TestShortCircuitLessPreferredAdapters(FetcherClient
* client
) {
550 // Here we have a bunch of adapters; the first reports no PAC in DHCP,
551 // the second responds quickly with a PAC file, the rest take a long
552 // time. Verify that we complete quickly and do not wait for the slow
553 // adapters, i.e. we finish before timeout.
554 client
->fetcher_
.ConfigureAndPushBackAdapter(
555 "1", true, ERR_PAC_NOT_IN_DHCP
, L
"",
556 base::TimeDelta::FromMilliseconds(1));
557 client
->fetcher_
.ConfigureAndPushBackAdapter(
558 "2", true, OK
, L
"bingo",
559 base::TimeDelta::FromMilliseconds(1));
560 client
->fetcher_
.ConfigureAndPushBackAdapter(
561 "3", true, OK
, L
"wrongo", TestTimeouts::action_max_timeout());
563 // Increase the timeout to ensure the short circuit mechanism has
564 // time to kick in before the timeout waiting for more adapters kicks in.
565 client
->fetcher_
.max_wait_
= TestTimeouts::action_timeout();
569 client
->RunMessageLoopUntilComplete();
570 ASSERT_TRUE(client
->fetcher_
.HasPendingFetchers());
571 // Assert that the time passed is definitely less than the wait timer
572 // timeout, to get a second signal that it was the shortcut mechanism
573 // (in OnFetcherDone) that kicked in, and not the timeout waiting for
575 ASSERT_GT(client
->fetcher_
.max_wait_
- (client
->fetcher_
.max_wait_
/ 10),
579 TEST(DhcpProxyScriptFetcherWin
, ShortCircuitLessPreferredAdapters
) {
580 FetcherClient client
;
581 TestShortCircuitLessPreferredAdapters(&client
);
584 void TestImmediateCancel(FetcherClient
* client
) {
585 TestURLRequestContext context
;
586 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
587 new DummyDhcpProxyScriptAdapterFetcher(&context
));
588 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
589 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
591 client
->fetcher_
.Cancel();
592 client
->RunMessageLoopUntilWorkerDone();
593 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
596 // Regression test to check that when we cancel immediately, no
597 // adapter fetchers get created.
598 TEST(DhcpProxyScriptFetcherWin
, ImmediateCancel
) {
599 FetcherClient client
;
600 TestImmediateCancel(&client
);
603 TEST(DhcpProxyScriptFetcherWin
, ReuseFetcher
) {
604 FetcherClient client
;
606 // The ProxyScriptFetcher interface stipulates that only a single
607 // |Fetch()| may be in flight at once, but allows reuse, so test
608 // that the state transitions correctly from done to start in all
609 // cases we're testing.
611 typedef void (*FetcherClientTestFunction
)(FetcherClient
*);
612 typedef std::vector
<FetcherClientTestFunction
> TestVector
;
613 TestVector test_functions
;
614 test_functions
.push_back(TestNormalCaseURLConfiguredOneAdapter
);
615 test_functions
.push_back(TestNormalCaseURLConfiguredMultipleAdapters
);
616 test_functions
.push_back(
617 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout
);
618 test_functions
.push_back(
619 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout
);
620 test_functions
.push_back(TestFailureCaseNoURLConfigured
);
621 test_functions
.push_back(TestFailureCaseNoDhcpAdapters
);
622 test_functions
.push_back(TestShortCircuitLessPreferredAdapters
);
623 test_functions
.push_back(TestImmediateCancel
);
625 std::random_shuffle(test_functions
.begin(),
626 test_functions
.end(),
627 base::RandGenerator
);
628 for (TestVector::const_iterator it
= test_functions
.begin();
629 it
!= test_functions
.end();
632 client
.ResetTestState();
635 // Re-do the first test to make sure the last test that was run did
636 // not leave things in a bad state.
637 (*test_functions
.begin())(&client
);