#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 {
class TestAutofillClientInjectorBase {
public:
static bool some_instance_is_alive() { return num_instances_ > 0; }
TestAutofillClientInjectorBase(const TestAutofillClientInjectorBase&) =
delete;
TestAutofillClientInjectorBase& operator=(
const TestAutofillClientInjectorBase&) = delete;
protected:
TestAutofillClientInjectorBase();
~TestAutofillClientInjectorBase();
private:
static size_t num_instances_;
};
template <std::derived_from<ContentAutofillClient> T>
class TestAutofillClientInjector : public TestAutofillClientInjectorBase {
public:
TestAutofillClientInjector() = default;
TestAutofillClientInjector(const TestAutofillClientInjector&) = delete;
TestAutofillClientInjector& operator=(const TestAutofillClientInjector&) =
delete;
~TestAutofillClientInjector() = default;
T* operator[](content::WebContents* web_contents) const {
auto it = clients_.find(web_contents);
return it != clients_.end() ? it->second : nullptr;
}
private:
void InjectClient(content::WebContents* web_contents) {
auto client = std::make_unique<T>(web_contents);
clients_[web_contents] = client.get();
web_contents->SetUserData(T::UserDataKey(), std::move(client));
}
std::map<content::WebContents*, T*> clients_;
base::CallbackListSubscription subscription_ =
content::RegisterWebContentsCreationCallback(
base::BindRepeating(&TestAutofillClientInjector::InjectClient,
base::Unretained(this)));
};
}
#endif