chromium/components/autofill/content/browser/test_autofill_manager_injector.h

// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_AUTOFILL_CONTENT_BROWSER_TEST_AUTOFILL_MANAGER_INJECTOR_H_
#define COMPONENTS_AUTOFILL_CONTENT_BROWSER_TEST_AUTOFILL_MANAGER_INJECTOR_H_

#include "components/autofill/content/browser/content_autofill_client.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/content/browser/content_autofill_driver_factory.h"
#include "components/autofill/content/browser/content_autofill_driver_factory_test_api.h"
#include "components/autofill/content/browser/content_autofill_driver_test_api.h"
#include "components/autofill/content/browser/test_autofill_driver_injector.h"
#include "components/autofill/core/browser/autofill_manager_test_api.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/browser_test_utils.h"

namespace autofill {

// Asserts that at construction time, no other TestAutofillManagerInjector is
// alive.
class TestAutofillManagerInjectorBase {};

// RAII type that installs new AutofillManagers of type `T` in all newly
// navigated frames in all newly created WebContents.
//
// The injector only injects an AutofillManager if a driver is created.
// Especially in unit tests it may be necessary to do a navigation to create the
// driver, for example with
//   NavigateAndCommit(GURL("about:blank"))
// or force-create the driver manually with
//   client->GetAutofillDriverFactory().DriverForFrame(rfh).
//
// To prevent hard-to-find bugs, only one TestAutofillManagerInjector may be
// alive at a time. It must not be created before a TestAutofillClientInjector.
// These conditions are CHECKed.
//
// Usage:
//
//   class AutofillFooTest : public ... {
//    public:
//     class MockAutofillManager : BrowserAutofillManager {
//      public:
//       explicit MockAutofillManager(ContentAutofillDriver* driver)
//           : BrowserAutofillManager(driver, "en-US") {}
//       MOCK_METHOD(...);
//       ...
//     };
//
//     MockAutofillManager* autofill_manager(content::RenderFrameHost* rfh) {
//       return autofill_manager_injector_[rfh];
//     }
//
//    private:
//     TestAutofillManagerInjector<MockAutofillManager>
//         autofill_manager_injector_;
//   };
template <typename T>
  requires(std::derived_from<T, AutofillManager>)
class TestAutofillManagerInjector : public TestAutofillManagerInjectorBase {};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CONTENT_BROWSER_TEST_AUTOFILL_MANAGER_INJECTOR_H_