Devlin Cronin | 1fc76f3 | 2021-09-15 01:39:34 | [diff] [blame^] | 1 | // Copyright 2021 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 | |
| 5 | #include "extensions/browser/extension_host_test_helper.h" |
| 6 | |
| 7 | #include "base/containers/contains.h" |
| 8 | #include "base/run_loop.h" |
| 9 | #include "extensions/browser/extension_host.h" |
| 10 | |
| 11 | namespace extensions { |
| 12 | |
| 13 | ExtensionHostTestHelper::ExtensionHostTestHelper( |
| 14 | content::BrowserContext* browser_context) |
| 15 | : ExtensionHostTestHelper(browser_context, ExtensionId()) {} |
| 16 | |
| 17 | ExtensionHostTestHelper::ExtensionHostTestHelper( |
| 18 | content::BrowserContext* browser_context, |
| 19 | ExtensionId extension_id) |
| 20 | : extension_id_(std::move(extension_id)) { |
| 21 | host_registry_observation_.Observe( |
| 22 | ExtensionHostRegistry::Get(browser_context)); |
| 23 | } |
| 24 | |
| 25 | ExtensionHostTestHelper::~ExtensionHostTestHelper() = default; |
| 26 | |
| 27 | void ExtensionHostTestHelper::OnExtensionHostDestroyed( |
| 28 | content::BrowserContext* browser_context, |
| 29 | ExtensionHost* host) { |
| 30 | EventSeen(host, HostEvent::kDestroyed); |
| 31 | } |
| 32 | |
| 33 | void ExtensionHostTestHelper::WaitFor(HostEvent event) { |
| 34 | DCHECK(!waiting_for_); |
| 35 | |
| 36 | if (base::Contains(observed_events_, event)) |
| 37 | return; |
| 38 | |
| 39 | base::RunLoop run_loop; |
| 40 | // Note: We use QuitWhenIdle (instead of Quit) so that any other listeners of |
| 41 | // the relevant events get a chance to run first. |
| 42 | quit_loop_ = run_loop.QuitWhenIdleClosure(); |
| 43 | waiting_for_ = event; |
| 44 | run_loop.Run(); |
| 45 | } |
| 46 | |
| 47 | void ExtensionHostTestHelper::EventSeen(ExtensionHost* host, HostEvent event) { |
| 48 | // Check if the host matches our restrictions. |
| 49 | if (!extension_id_.empty() && host->extension_id() != extension_id_) |
| 50 | return; |
| 51 | |
| 52 | observed_events_.insert(event); |
| 53 | if (waiting_for_ == event) { |
| 54 | DCHECK(quit_loop_); |
| 55 | waiting_for_.reset(); |
| 56 | std::move(quit_loop_).Run(); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | } // namespace extensions |