web_view_early_page_script_provider_unittest.mm 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #import "ios/web_view/internal/web_view_early_page_script_provider.h"
  5. #import <WebKit/WebKit.h>
  6. #include <memory>
  7. #include "ios/web/public/test/fakes/fake_browser_state.h"
  8. #include "ios/web/public/test/scoped_testing_web_client.h"
  9. #include "ios/web/public/test/web_task_environment.h"
  10. #include "ios/web/web_state/ui/wk_web_view_configuration_provider.h"
  11. #import "ios/web_view/internal/web_view_web_client.h"
  12. #include "ios/web_view/test/test_with_locale_and_resources.h"
  13. #include "testing/gtest/include/gtest/gtest.h"
  14. #include "testing/gtest_mac.h"
  15. #if !defined(__has_feature) || !__has_feature(objc_arc)
  16. #error "This file requires ARC support."
  17. #endif
  18. namespace ios_web_view {
  19. class WebViewEarlyPageScriptProviderTest : public TestWithLocaleAndResources {
  20. protected:
  21. WebViewEarlyPageScriptProviderTest()
  22. : web_client_(std::make_unique<WebViewWebClient>()) {}
  23. web::WebTaskEnvironment task_environment_;
  24. web::ScopedTestingWebClient web_client_;
  25. web::FakeBrowserState browser_state_;
  26. // Whether or not |string| appears in any of the configured WKUserScripts.
  27. bool UserScriptsContainString(NSString* string) {
  28. web::WKWebViewConfigurationProvider& config_provider =
  29. web::WKWebViewConfigurationProvider::FromBrowserState(&browser_state_);
  30. WKWebViewConfiguration* configuration =
  31. config_provider.GetWebViewConfiguration();
  32. for (WKUserScript* script in configuration.userContentController
  33. .userScripts) {
  34. if ([script.source containsString:string]) {
  35. return true;
  36. }
  37. }
  38. return false;
  39. }
  40. };
  41. // Test WebViewEarlyPageScriptProvder::SetScript properly updates the underlying
  42. // WKUserContentController.
  43. TEST_F(WebViewEarlyPageScriptProviderTest, SetScript) {
  44. EXPECT_FALSE(UserScriptsContainString(@"WebViewEarlyPageScriptProvider"));
  45. WebViewEarlyPageScriptProvider::FromBrowserState(&browser_state_)
  46. .SetScript(@"WebViewEarlyPageScriptProvider");
  47. EXPECT_TRUE(UserScriptsContainString(@"WebViewEarlyPageScriptProvider"));
  48. }
  49. } // namespace ios_web_view