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() : DhcpQuery() {}
162 std::string
ImplGetPacURLFromDhcp(
163 const std::string
& adapter_name
) override
{
164 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
165 return DhcpQuery::ImplGetPacURLFromDhcp(adapter_name
);
169 ~DelayingDhcpQuery() override
{}
172 DhcpQuery
* ImplCreateDhcpQuery() override
{
173 return new DelayingDhcpQuery();
177 // For RealFetchWithDeferredCancel, below.
178 class DelayingDhcpProxyScriptFetcherWin
179 : public DhcpProxyScriptFetcherWin
{
181 explicit DelayingDhcpProxyScriptFetcherWin(
182 URLRequestContext
* context
)
183 : DhcpProxyScriptFetcherWin(context
) {
186 DhcpProxyScriptAdapterFetcher
* ImplCreateAdapterFetcher() override
{
187 return new DelayingDhcpProxyScriptAdapterFetcher(url_request_context(),
192 TEST(DhcpProxyScriptFetcherWin
, RealFetchWithDeferredCancel
) {
193 // Does a Fetch() with a slightly delayed cancel. As before, just
194 // exercises the code without stubbing out dependencies, but
195 // introduces a guaranteed 20 ms delay on the worker threads so that
196 // the cancel is called before they complete.
197 RealFetchTester fetcher
;
198 fetcher
.fetcher_
.reset(
199 new DelayingDhcpProxyScriptFetcherWin(fetcher
.context_
.get()));
200 fetcher
.on_completion_is_error_
= true;
201 fetcher
.RunTestWithDeferredCancel();
202 fetcher
.WaitUntilDone();
205 // The remaining tests are to exercise our state machine in various
206 // situations, with actual network access fully stubbed out.
208 class DummyDhcpProxyScriptAdapterFetcher
209 : public DhcpProxyScriptAdapterFetcher
{
211 DummyDhcpProxyScriptAdapterFetcher(URLRequestContext
* context
,
212 scoped_refptr
<base::TaskRunner
> runner
)
213 : DhcpProxyScriptAdapterFetcher(context
, runner
),
216 pac_script_(L
"bingo"),
220 void Fetch(const std::string
& adapter_name
,
221 const CompletionCallback
& callback
) override
{
222 callback_
= callback
;
223 timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(fetch_delay_ms_
),
224 this, &DummyDhcpProxyScriptAdapterFetcher::OnTimer
);
227 void Cancel() override
{
231 bool DidFinish() const override
{
235 int GetResult() const override
{
239 base::string16
GetPacScript() const override
{
244 callback_
.Run(result_
);
247 void Configure(bool did_finish
,
249 base::string16 pac_script
,
250 int fetch_delay_ms
) {
251 did_finish_
= did_finish
;
253 pac_script_
= pac_script
;
254 fetch_delay_ms_
= fetch_delay_ms
;
260 base::string16 pac_script_
;
262 CompletionCallback callback_
;
263 base::OneShotTimer
<DummyDhcpProxyScriptAdapterFetcher
> timer_
;
266 class MockDhcpProxyScriptFetcherWin
: public DhcpProxyScriptFetcherWin
{
268 class MockAdapterQuery
: public AdapterQuery
{
273 bool ImplGetCandidateAdapterNames(
274 std::set
<std::string
>* adapter_names
) override
{
275 adapter_names
->insert(
276 mock_adapter_names_
.begin(), mock_adapter_names_
.end());
280 std::vector
<std::string
> mock_adapter_names_
;
283 ~MockAdapterQuery() override
{}
286 MockDhcpProxyScriptFetcherWin(URLRequestContext
* context
)
287 : DhcpProxyScriptFetcherWin(context
),
288 num_fetchers_created_(0),
289 worker_finished_event_(true, false) {
293 ~MockDhcpProxyScriptFetcherWin() override
{ ResetTestState(); }
295 using DhcpProxyScriptFetcherWin::GetTaskRunner
;
297 // Adds a fetcher object to the queue of fetchers used by
298 // |ImplCreateAdapterFetcher()|, and its name to the list of adapters
299 // returned by ImplGetCandidateAdapterNames.
300 void PushBackAdapter(const std::string
& adapter_name
,
301 DhcpProxyScriptAdapterFetcher
* fetcher
) {
302 adapter_query_
->mock_adapter_names_
.push_back(adapter_name
);
303 adapter_fetchers_
.push_back(fetcher
);
306 void ConfigureAndPushBackAdapter(const std::string
& adapter_name
,
309 base::string16 pac_script
,
310 base::TimeDelta fetch_delay
) {
311 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
312 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 AdapterQuery
* ImplCreateAdapterQuery() override
{
325 DCHECK(adapter_query_
.get());
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 base::MessageLoop::current()->RunUntilIdle();
392 base::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 base::MessageLoop::current()->RunUntilIdle();
403 void OnCompletion(int result
) {
408 void ResetTestState() {
410 result_
= ERR_UNEXPECTED
;
412 fetcher_
.ResetTestState();
415 scoped_refptr
<base::TaskRunner
> GetTaskRunner() {
416 return fetcher_
.GetTaskRunner();
419 scoped_ptr
<URLRequestContext
> context_
;
420 MockDhcpProxyScriptFetcherWin fetcher_
;
423 base::string16 pac_text_
;
426 // We separate out each test's logic so that we can easily implement
427 // the ReuseFetcher test at the bottom.
428 void TestNormalCaseURLConfiguredOneAdapter(FetcherClient
* client
) {
429 TestURLRequestContext context
;
430 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
431 new DummyDhcpProxyScriptAdapterFetcher(&context
,
432 client
->GetTaskRunner()));
433 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
434 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
436 client
->RunMessageLoopUntilComplete();
437 ASSERT_EQ(OK
, client
->result_
);
438 ASSERT_EQ(L
"bingo", client
->pac_text_
);
441 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredOneAdapter
) {
442 FetcherClient client
;
443 TestNormalCaseURLConfiguredOneAdapter(&client
);
446 void TestNormalCaseURLConfiguredMultipleAdapters(FetcherClient
* client
) {
447 client
->fetcher_
.ConfigureAndPushBackAdapter(
448 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
449 base::TimeDelta::FromMilliseconds(1));
450 client
->fetcher_
.ConfigureAndPushBackAdapter(
451 "second", true, OK
, L
"bingo", base::TimeDelta::FromMilliseconds(50));
452 client
->fetcher_
.ConfigureAndPushBackAdapter(
453 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
455 client
->RunMessageLoopUntilComplete();
456 ASSERT_EQ(OK
, client
->result_
);
457 ASSERT_EQ(L
"bingo", client
->pac_text_
);
460 TEST(DhcpProxyScriptFetcherWin
, NormalCaseURLConfiguredMultipleAdapters
) {
461 FetcherClient client
;
462 TestNormalCaseURLConfiguredMultipleAdapters(&client
);
465 void TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(
466 FetcherClient
* client
) {
467 client
->fetcher_
.ConfigureAndPushBackAdapter(
468 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
469 base::TimeDelta::FromMilliseconds(1));
470 // This will time out.
471 client
->fetcher_
.ConfigureAndPushBackAdapter(
472 "second", false, ERR_IO_PENDING
, L
"bingo",
473 TestTimeouts::action_timeout());
474 client
->fetcher_
.ConfigureAndPushBackAdapter(
475 "third", true, OK
, L
"rocko", base::TimeDelta::FromMilliseconds(1));
477 client
->RunMessageLoopUntilComplete();
478 ASSERT_EQ(OK
, client
->result_
);
479 ASSERT_EQ(L
"rocko", client
->pac_text_
);
482 TEST(DhcpProxyScriptFetcherWin
,
483 NormalCaseURLConfiguredMultipleAdaptersWithTimeout
) {
484 FetcherClient client
;
485 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
488 void TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(
489 FetcherClient
* client
) {
490 client
->fetcher_
.ConfigureAndPushBackAdapter(
491 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
492 base::TimeDelta::FromMilliseconds(1));
493 // This will time out.
494 client
->fetcher_
.ConfigureAndPushBackAdapter(
495 "second", false, ERR_IO_PENDING
, L
"bingo",
496 TestTimeouts::action_timeout());
497 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
499 client
->fetcher_
.ConfigureAndPushBackAdapter(
500 "third", true, ERR_PAC_STATUS_NOT_OK
, L
"",
501 base::TimeDelta::FromMilliseconds(1));
502 client
->fetcher_
.ConfigureAndPushBackAdapter(
503 "fourth", true, ERR_NOT_IMPLEMENTED
, L
"",
504 base::TimeDelta::FromMilliseconds(1));
506 client
->RunMessageLoopUntilComplete();
507 ASSERT_EQ(ERR_PAC_STATUS_NOT_OK
, client
->result_
);
508 ASSERT_EQ(L
"", client
->pac_text_
);
511 TEST(DhcpProxyScriptFetcherWin
,
512 FailureCaseURLConfiguredMultipleAdaptersWithTimeout
) {
513 FetcherClient client
;
514 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout(&client
);
517 void TestFailureCaseNoURLConfigured(FetcherClient
* client
) {
518 client
->fetcher_
.ConfigureAndPushBackAdapter(
519 "most_preferred", true, ERR_PAC_NOT_IN_DHCP
, L
"",
520 base::TimeDelta::FromMilliseconds(1));
521 // This will time out.
522 client
->fetcher_
.ConfigureAndPushBackAdapter(
523 "second", false, ERR_IO_PENDING
, L
"bingo",
524 TestTimeouts::action_timeout());
525 // This is the first non-ERR_PAC_NOT_IN_DHCP error and as such
527 client
->fetcher_
.ConfigureAndPushBackAdapter(
528 "third", true, ERR_PAC_NOT_IN_DHCP
, L
"",
529 base::TimeDelta::FromMilliseconds(1));
531 client
->RunMessageLoopUntilComplete();
532 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
533 ASSERT_EQ(L
"", client
->pac_text_
);
536 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoURLConfigured
) {
537 FetcherClient client
;
538 TestFailureCaseNoURLConfigured(&client
);
541 void TestFailureCaseNoDhcpAdapters(FetcherClient
* client
) {
543 client
->RunMessageLoopUntilComplete();
544 ASSERT_EQ(ERR_PAC_NOT_IN_DHCP
, client
->result_
);
545 ASSERT_EQ(L
"", client
->pac_text_
);
546 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
549 TEST(DhcpProxyScriptFetcherWin
, FailureCaseNoDhcpAdapters
) {
550 FetcherClient client
;
551 TestFailureCaseNoDhcpAdapters(&client
);
554 void TestShortCircuitLessPreferredAdapters(FetcherClient
* client
) {
555 // Here we have a bunch of adapters; the first reports no PAC in DHCP,
556 // the second responds quickly with a PAC file, the rest take a long
557 // time. Verify that we complete quickly and do not wait for the slow
558 // adapters, i.e. we finish before timeout.
559 client
->fetcher_
.ConfigureAndPushBackAdapter(
560 "1", true, ERR_PAC_NOT_IN_DHCP
, L
"",
561 base::TimeDelta::FromMilliseconds(1));
562 client
->fetcher_
.ConfigureAndPushBackAdapter(
563 "2", true, OK
, L
"bingo",
564 base::TimeDelta::FromMilliseconds(1));
565 client
->fetcher_
.ConfigureAndPushBackAdapter(
566 "3", true, OK
, L
"wrongo", TestTimeouts::action_max_timeout());
568 // Increase the timeout to ensure the short circuit mechanism has
569 // time to kick in before the timeout waiting for more adapters kicks in.
570 client
->fetcher_
.max_wait_
= TestTimeouts::action_timeout();
572 base::ElapsedTimer timer
;
574 client
->RunMessageLoopUntilComplete();
575 ASSERT_TRUE(client
->fetcher_
.HasPendingFetchers());
576 // Assert that the time passed is definitely less than the wait timer
577 // timeout, to get a second signal that it was the shortcut mechanism
578 // (in OnFetcherDone) that kicked in, and not the timeout waiting for
580 ASSERT_GT(client
->fetcher_
.max_wait_
- (client
->fetcher_
.max_wait_
/ 10),
584 TEST(DhcpProxyScriptFetcherWin
, ShortCircuitLessPreferredAdapters
) {
585 FetcherClient client
;
586 TestShortCircuitLessPreferredAdapters(&client
);
589 void TestImmediateCancel(FetcherClient
* client
) {
590 TestURLRequestContext context
;
591 scoped_ptr
<DummyDhcpProxyScriptAdapterFetcher
> adapter_fetcher(
592 new DummyDhcpProxyScriptAdapterFetcher(&context
,
593 client
->GetTaskRunner()));
594 adapter_fetcher
->Configure(true, OK
, L
"bingo", 1);
595 client
->fetcher_
.PushBackAdapter("a", adapter_fetcher
.release());
597 client
->fetcher_
.Cancel();
598 client
->RunMessageLoopUntilWorkerDone();
599 ASSERT_EQ(0, client
->fetcher_
.num_fetchers_created_
);
602 // Regression test to check that when we cancel immediately, no
603 // adapter fetchers get created.
604 TEST(DhcpProxyScriptFetcherWin
, ImmediateCancel
) {
605 FetcherClient client
;
606 TestImmediateCancel(&client
);
609 TEST(DhcpProxyScriptFetcherWin
, ReuseFetcher
) {
610 FetcherClient client
;
612 // The ProxyScriptFetcher interface stipulates that only a single
613 // |Fetch()| may be in flight at once, but allows reuse, so test
614 // that the state transitions correctly from done to start in all
615 // cases we're testing.
617 typedef void (*FetcherClientTestFunction
)(FetcherClient
*);
618 typedef std::vector
<FetcherClientTestFunction
> TestVector
;
619 TestVector test_functions
;
620 test_functions
.push_back(TestNormalCaseURLConfiguredOneAdapter
);
621 test_functions
.push_back(TestNormalCaseURLConfiguredMultipleAdapters
);
622 test_functions
.push_back(
623 TestNormalCaseURLConfiguredMultipleAdaptersWithTimeout
);
624 test_functions
.push_back(
625 TestFailureCaseURLConfiguredMultipleAdaptersWithTimeout
);
626 test_functions
.push_back(TestFailureCaseNoURLConfigured
);
627 test_functions
.push_back(TestFailureCaseNoDhcpAdapters
);
628 test_functions
.push_back(TestShortCircuitLessPreferredAdapters
);
629 test_functions
.push_back(TestImmediateCancel
);
631 std::random_shuffle(test_functions
.begin(),
632 test_functions
.end(),
633 base::RandGenerator
);
634 for (TestVector::const_iterator it
= test_functions
.begin();
635 it
!= test_functions
.end();
638 client
.ResetTestState();
641 // Re-do the first test to make sure the last test that was run did
642 // not leave things in a bad state.
643 (*test_functions
.begin())(&client
);