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

// Copyright 2023 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_CLIENT_INJECTOR_H_
#define COMPONENTS_AUTOFILL_CONTENT_BROWSER_TEST_AUTOFILL_CLIENT_INJECTOR_H_

#include <concepts>

#include "components/autofill/content/browser/content_autofill_client.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"

namespace autofill {

// Asserts that at construction time, no other TestAutofillClientInjector, no
// other TestAutofillDriverInjector, and no TestAutofillManagerInjector are
// alive.
class TestAutofillClientInjectorBase {};

// RAII type that installs new AutofillClients of type `T` in all newly created
// WebContents.
//
// This happens *before* the production-code ContentAutofillClient is
// associated. It thus avoids dangling pointers to the production-code
// ContentAutofillClient.
//
// To prevent hard-to-find bugs, only one TestAutofillClientInjector may be
// alive at a time. It is compatible with TestAutofillDriverInjector and/or
// TestAutofillManagerInjector, but the client injector must be created first.
// These conditions are CHECKed.
//
// Usage:
//
//   class AutofillFooTest : public ... {
//    public:
//     TestContentAutofillClient* autofill_client(
//         content::WebContents* web_contents) {
//       return autofill_client_injector_[web_contents];
//     }
//
//    private:
//     TestAutofillClientInjector<TestContentAutofillClient>
//         autofill_client_injector_;
//   };
template <std::derived_from<ContentAutofillClient> T>
class TestAutofillClientInjector : public TestAutofillClientInjectorBase {};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CONTENT_BROWSER_TEST_AUTOFILL_CLIENT_INJECTOR_H_