network_delegate_error_observer_unittest.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.
  4. #include "net/proxy_resolution/network_delegate_error_observer.h"
  5. #include "base/bind.h"
  6. #include "base/callback_helpers.h"
  7. #include "base/location.h"
  8. #include "base/run_loop.h"
  9. #include "base/task/single_thread_task_runner.h"
  10. #include "base/test/task_environment.h"
  11. #include "base/threading/thread.h"
  12. #include "base/threading/thread_task_runner_handle.h"
  13. #include "net/base/net_errors.h"
  14. #include "net/base/network_delegate_impl.h"
  15. #include "testing/gtest/include/gtest/gtest.h"
  16. #include "third_party/abseil-cpp/absl/types/optional.h"
  17. namespace net {
  18. namespace {
  19. class TestNetworkDelegate : public NetworkDelegateImpl {
  20. public:
  21. TestNetworkDelegate() = default;
  22. ~TestNetworkDelegate() override = default;
  23. bool got_pac_error() const { return got_pac_error_; }
  24. private:
  25. // NetworkDelegate implementation.
  26. void OnPACScriptError(int line_number, const std::u16string& error) override {
  27. got_pac_error_ = true;
  28. }
  29. bool got_pac_error_ = false;
  30. };
  31. // Check that the OnPACScriptError method can be called from an arbitrary
  32. // thread.
  33. TEST(NetworkDelegateErrorObserverTest, CallOnThread) {
  34. base::test::TaskEnvironment task_environment;
  35. base::Thread thread("test_thread");
  36. thread.Start();
  37. TestNetworkDelegate network_delegate;
  38. NetworkDelegateErrorObserver observer(
  39. &network_delegate, base::ThreadTaskRunnerHandle::Get().get());
  40. thread.task_runner()->PostTask(
  41. FROM_HERE,
  42. base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError,
  43. base::Unretained(&observer), 42, std::u16string()));
  44. thread.Stop();
  45. base::RunLoop().RunUntilIdle();
  46. ASSERT_TRUE(network_delegate.got_pac_error());
  47. }
  48. // Check that passing a NULL network delegate works.
  49. TEST(NetworkDelegateErrorObserverTest, NoDelegate) {
  50. base::test::TaskEnvironment task_environment;
  51. base::Thread thread("test_thread");
  52. thread.Start();
  53. NetworkDelegateErrorObserver observer(
  54. nullptr, base::ThreadTaskRunnerHandle::Get().get());
  55. thread.task_runner()->PostTask(
  56. FROM_HERE,
  57. base::BindOnce(&NetworkDelegateErrorObserver::OnPACScriptError,
  58. base::Unretained(&observer), 42, std::u16string()));
  59. thread.Stop();
  60. base::RunLoop().RunUntilIdle();
  61. // Shouldn't have crashed until here...
  62. }
  63. } // namespace
  64. } // namespace net