1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/proxy_resolution/network_delegate_error_observer.h"
6
7 #include <optional>
8
9 #include "base/functional/bind.h"
10 #include "base/functional/callback_helpers.h"
11 #include "base/location.h"
12 #include "base/run_loop.h"
13 #include "base/task/single_thread_task_runner.h"
14 #include "base/test/task_environment.h"
15 #include "base/threading/thread.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/network_delegate_impl.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19
20 namespace net {
21
22 namespace {
23
24 class TestNetworkDelegate : public NetworkDelegateImpl {
25 public:
26 TestNetworkDelegate() = default;
27 ~TestNetworkDelegate() override = default;
28
got_pac_error() const29 bool got_pac_error() const { return got_pac_error_; }
30
31 private:
32 // NetworkDelegate implementation.
OnPACScriptError(int line_number,const std::u16string & error)33 void OnPACScriptError(int line_number, const std::u16string& error) override {
34 got_pac_error_ = true;
35 }
36
37 bool got_pac_error_ = false;
38 };
39
40 // Check that the OnPACScriptError method can be called from an arbitrary
41 // thread.
TEST(NetworkDelegateErrorObserverTest,CallOnThread)42 TEST(NetworkDelegateErrorObserverTest, CallOnThread) {
43 base::test::TaskEnvironment task_environment;
44 base::Thread thread("test_thread");
45 thread.Start();
46 TestNetworkDelegate network_delegate;
47 NetworkDelegateErrorObserver observer(
48 &network_delegate,
49 base::SingleThreadTaskRunner::GetCurrentDefault().get());
50 thread.task_runner()->PostTask(
51 FROM_HERE,
52 base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError,
53 base::Unretained(&observer), 42, std::u16string()));
54 thread.Stop();
55 base::RunLoop().RunUntilIdle();
56 ASSERT_TRUE(network_delegate.got_pac_error());
57 }
58
59 // Check that passing a NULL network delegate works.
TEST(NetworkDelegateErrorObserverTest,NoDelegate)60 TEST(NetworkDelegateErrorObserverTest, NoDelegate) {
61 base::test::TaskEnvironment task_environment;
62 base::Thread thread("test_thread");
63 thread.Start();
64 NetworkDelegateErrorObserver observer(
65 nullptr, base::SingleThreadTaskRunner::GetCurrentDefault().get());
66 thread.task_runner()->PostTask(
67 FROM_HERE,
68 base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError,
69 base::Unretained(&observer), 42, std::u16string()));
70 thread.Stop();
71 base::RunLoop().RunUntilIdle();
72 // Shouldn't have crashed until here...
73 }
74
75 } // namespace
76
77 } // namespace net
78