Skip to content

Commit

Permalink
Added tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
boocmp committed Oct 21, 2024
1 parent b277191 commit e999fa1
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 16 deletions.
218 changes: 218 additions & 0 deletions browser/brave_shields/ad_block_custom_resources_browsertest.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/* Copyright (c) 2024 The Brave Authors. All rights reserved.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at https://mozilla.org/MPL/2.0/. */

#include "base/base64.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "brave/browser/brave_browser_process.h"
#include "brave/browser/brave_shields/ad_block_service_browsertest.h"
#include "brave/browser/ui/webui/brave_settings_ui.h"
#include "brave/components/brave_shields/content/browser/ad_block_service.h"
#include "brave/components/brave_shields/core/browser/ad_block_custom_resource_provider.h"
#include "brave/components/brave_shields/core/common/features.h"
#include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/test/base/android/android_browser_test.h"
#else
#include "chrome/test/base/in_process_browser_test.h"
#endif

namespace {

void AwaitElement(content::WebContents* web_contents,
const std::string& root,
const std::string& id) {
constexpr const char kScript[] = R"js(
(async () => {
while (!window.testing[$1].getElementById($2)) {
await new Promise(r => setTimeout(r, 10));
}
return true;
})();
)js";
EXPECT_TRUE(
content::EvalJs(web_contents, content::JsReplace(kScript, root, id))
.ExtractBool());
}

bool ClickAddCustomScriptlet(content::WebContents* web_contents) {
AwaitElement(web_contents, "adblockScriptletList", "add-custom-scriptlet");
return EvalJs(web_contents,
"window.testing.adblockScriptletList.getElementById('add-"
"custom-scriptlet').click()")
.value.is_none();
}

bool SetCustomScriptletValue(content::WebContents* web_contents,
const std::string& id,
const std::string& value) {
AwaitElement(web_contents, "adblockScriptletEditor", id);
constexpr const char kSetValue[] = R"js(
(function() {
const e = window.testing.adblockScriptletEditor.getElementById($1);
e.value = $2;
const event = new Event('input', {bubbles: true});
event.simulated = true;
return e.dispatchEvent(event);
})();
)js";
return EvalJs(web_contents, content::JsReplace(kSetValue, id, value))
.value.GetBool();
}

bool SetCustomScriptletName(content::WebContents* web_contents,
const std::string& name) {
return SetCustomScriptletValue(web_contents, "scriptlet-name", name);
}

bool SetCustomScriptletContent(content::WebContents* web_contents,
const std::string& content) {
return SetCustomScriptletValue(web_contents, "scriptlet-content", content);
}

std::string GetCustomScriptletValue(content::WebContents* web_contents,
const std::string& id) {
AwaitElement(web_contents, "adblockScriptletEditor", id);
return EvalJs(web_contents,
"window.testing.adblockScriptletEditor.getElementById('" + id +
"').value")
.value.GetString();
}

std::string GetCustomScriptletName(content::WebContents* web_contents) {
return GetCustomScriptletValue(web_contents, "scriptlet-name");
}

std::string GetCustomScriptletContent(content::WebContents* web_contents) {
return GetCustomScriptletValue(web_contents, "scriptlet-content");
}

bool ClickSaveCustomScriptlet(content::WebContents* web_contents) {
AwaitElement(web_contents, "adblockScriptletEditor", "save");
return EvalJs(web_contents,
"window.testing.adblockScriptletEditor.getElementById('save')."
"click()")
.value.is_none();
}

bool ClickCustomScriplet(content::WebContents* web_contents,
const std::string& name,
const std::string& button) {
AwaitElement(web_contents, "adblockScriptletList", name);
constexpr const char kClick[] = R"js(
(function() {
const e = window.testing.adblockScriptletList.getElementById($1);
const b = e.querySelector($2);
b.click();
})();
)js";
return EvalJs(web_contents, content::JsReplace(kClick, name, "#" + button))
.value.is_none();
}

} // namespace

class AdblockCustomResourcesTest : public AdBlockServiceTest {
public:
AdblockCustomResourcesTest() {
feature_list_.InitAndEnableFeature(
brave_shields::features::kCosmeticFilteringCustomScriptlets);
BraveSettingsUI::ShouldExposeElementsForTesting() = true;
}

~AdblockCustomResourcesTest() override {
BraveSettingsUI::ShouldExposeElementsForTesting() = true;
}

void SaveCustomScriptlet(const std::string& name, const std::string& value) {
ASSERT_EQ(GURL("chrome://settings/shields/filters"),
web_contents()->GetLastCommittedURL());

ASSERT_TRUE(SetCustomScriptletContent(web_contents(), value));
ASSERT_TRUE(SetCustomScriptletName(web_contents(), name));
ASSERT_TRUE(ClickSaveCustomScriptlet(web_contents()));
}

void CheckCustomScriptlet(const base::Value& custom_scriptlet,
const std::string& name,
const std::string& content) {
ASSERT_TRUE(custom_scriptlet.is_dict());
EXPECT_EQ(name, *custom_scriptlet.GetDict().FindString("name"));
EXPECT_EQ(base::Base64Encode(content),
*custom_scriptlet.GetDict().FindString("content"));
EXPECT_EQ("application/javascript",
*custom_scriptlet.GetDict().FindStringByDottedPath("kind.mime"));
}

private:
base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(AdblockCustomResourcesTest, AddEditRemoveScriptlet) {
NavigateToURL(GURL("brave://settings/shields/filters"));

constexpr const char kContent[] = "window.test = 'custom-script'";

ASSERT_TRUE(ClickAddCustomScriptlet(web_contents()));
SaveCustomScriptlet("custom-script", kContent);

auto* ad_block_service = g_brave_browser_process->ad_block_service();

{
const auto& custom_resources =
ad_block_service->custom_resource_provider()->GetCustomResources();
ASSERT_TRUE(custom_resources.is_list());
ASSERT_EQ(1u, custom_resources.GetList().size());
CheckCustomScriptlet(custom_resources.GetList().front(),
"brave-custom-script.js", kContent);
}

constexpr const char kEditedContent[] = "window.test = 'edited'";

ASSERT_TRUE(
ClickCustomScriplet(web_contents(), "brave-custom-script.js", "edit"));

EXPECT_EQ("brave-custom-script.js", GetCustomScriptletName(web_contents()));
EXPECT_EQ(kContent, GetCustomScriptletContent(web_contents()));
SaveCustomScriptlet("custom-script-edited", kEditedContent);
{
const auto& custom_resources =
ad_block_service->custom_resource_provider()->GetCustomResources();
ASSERT_TRUE(custom_resources.is_list());
ASSERT_EQ(1u, custom_resources.GetList().size());
CheckCustomScriptlet(custom_resources.GetList().front(),
"brave-custom-script-edited.js", kEditedContent);
}

ASSERT_TRUE(ClickCustomScriplet(web_contents(),
"brave-custom-script-edited.js", "delete"));
{
const auto& custom_resources =
ad_block_service->custom_resource_provider()->GetCustomResources();
ASSERT_TRUE(custom_resources.is_list());
ASSERT_TRUE(custom_resources.GetList().empty());
}
}

IN_PROC_BROWSER_TEST_F(AdblockCustomResourcesTest, ExecCustomScriptlet) {
NavigateToURL(GURL("brave://settings/shields/filters"));

constexpr const char kContent[] = "window.test = 'custom-script'";

ASSERT_TRUE(ClickAddCustomScriptlet(web_contents()));
SaveCustomScriptlet("custom-script", kContent);

UpdateAdBlockInstanceWithRules("a.com##+js(brave-custom-script)");

GURL tab_url =
embedded_test_server()->GetURL("a.com", "/cosmetic_filtering.html");
NavigateToURL(tab_url);

EXPECT_EQ("custom-script", EvalJs(web_contents(), "window.test"));
}
2 changes: 1 addition & 1 deletion browser/brave_shields/ad_block_service_browsertest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ base::FilePath AdBlockServiceTest::GetTestDataDir() {
return base::PathService::CheckedGet(brave::DIR_TEST_DATA);
}

void AdBlockServiceTest::NavigateToURL(GURL url) {
void AdBlockServiceTest::NavigateToURL(const GURL& url) {
content::NavigateToURLBlockUntilNavigationsComplete(web_contents(), url, 1,
true);
}
Expand Down
2 changes: 1 addition & 1 deletion browser/brave_shields/ad_block_service_browsertest.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AdBlockServiceTest : public PlatformBrowserTest {
void AssertTagExists(const std::string& tag, bool expected_exists) const;
void InitEmbeddedTestServer();
base::FilePath GetTestDataDir();
void NavigateToURL(GURL url);
void NavigateToURL(const GURL& url);
void SetDefaultComponentIdAndBase64PublicKeyForTest();
void SetRegionalComponentIdAndBase64PublicKeyForTest();
void InstallComponent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/icons.html.js';
import './components/brave_adblock_subscribe_dropdown.js';
import './components/brave_adblock_editor.js';
import './components/brave_adblock_scriptlet_list.js';

import {PrefsMixin} from '/shared/settings/prefs/prefs_mixin.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<style include="settings-shared md-select">
<style include="cr-shared-style settings-shared iron-flex">
div[slot=body] {
overflow: hidden;
}
Expand Down Expand Up @@ -44,7 +44,7 @@
<cr-button class="cancel-button" id="cancel"
on-click="cancelClicked_">$i18n{adblockCustomScriptletDialogCancelButton}
</cr-button>
<cr-button class="action-button" id="save" on-click="saveClicked_" disabled="[[!isScriptletValid_]]">
<cr-button class="action-button" id="save" on-click="saveClicked_">
$i18n{adblockCustomScriptletDialogSaveButton}
</cr-button>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { PolymerElement } from 'chrome://resources/polymer/v3_0/polymer/polymer_

import { getTemplate } from './brave_adblock_scriptlet_editor.html.js'

import { loadTimeData } from '../../i18n_setup.js'

import {
Scriptlet,
BraveAdblockBrowserProxyImpl,
Expand Down Expand Up @@ -50,14 +52,19 @@ class AdblockScriptletEditor extends AdblockScriptletEditorBase {
isScriptletValid_: boolean
scriptletErrorMessage_: string

scriptletName_: string
oldScriptletName_: string
browserProxy_ = BraveAdblockBrowserProxyImpl.getInstance()

override ready() {
super.ready()
this.scriptletName_ = this.scriptlet.name
if (loadTimeData.getBoolean('shouldExposeElementsForTesting')) {
window.testing = window.testing || {}
window.testing[`adblockScriptletEditor`] = this.shadowRoot
}

this.oldScriptletName_ = this.scriptlet.name

if (this.scriptletName_) {
if (this.oldScriptletName_) {
this.dialogTitle_ = this.i18n('adblockEditCustomScriptletDialogTitle')
} else {
this.dialogTitle_ = this.i18n('adblockAddCustomScriptletDialogTitle')
Expand Down Expand Up @@ -95,9 +102,14 @@ class AdblockScriptletEditor extends AdblockScriptletEditorBase {
}

saveClicked_() {
if (this.scriptletName_) {
this.updateScriptletBeforeSave_()
if (!this.isScriptletValid_) {
return
}

if (this.oldScriptletName_) {
this.browserProxy_
.updateCustomScriptlet(this.scriptletName_, this.scriptlet)
.updateCustomScriptlet(this.oldScriptletName_, this.scriptlet)
.then((e) => {
this.updateError(e)
if (this.isScriptletValid_) {
Expand All @@ -115,12 +127,24 @@ class AdblockScriptletEditor extends AdblockScriptletEditorBase {
}

validateName_() {
this.scriptlet.name = this.scriptlet.name.toLowerCase()
if (!/^[a-z-_.]*$/.test(this.scriptlet.name)) {
this.updateError(ErrorCode.kInvalidName)
} else {
this.updateError(ErrorCode.kOK)
}
}

updateScriptletBeforeSave_() {
this.scriptlet.name = this.scriptlet.name.toLowerCase()
if (!this.scriptlet.name.startsWith('brave-')) {
this.scriptlet.name = 'brave-' + this.scriptlet.name
}
if (!this.scriptlet.name.endsWith('.js')) {
this.scriptlet.name = this.scriptlet.name + '.js'
}
this.validateName_()
}
}

customElements.define(AdblockScriptletEditor.is, AdblockScriptletEditor)
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,21 @@
<div>
<div class="list">
<template is="dom-repeat" items="[[customScriptletsList_]]">
<div class="scriptlet">
<div class="scriptlet" id="[[item.name]]">
<div>
<div class="label">[[item.name]]</div>
</div>
<div>
<cr-icon-button on-click="handleEdit_" class="size-20" iron-icon="edit-pencil">
<cr-icon-button id="edit" on-click="handleEdit_" class="size-20" iron-icon="edit-pencil">
</cr-icon-button>
<cr-icon-button on-click="handleDelete_" class="size-20" iron-icon="trash">
<cr-icon-button id="delete" on-click="handleDelete_" class="size-20" iron-icon="trash">
</cr-icon-button>
</div>
</div>
</template>
</div>

<cr-button on-click="handleAdd_">
<cr-button id="add-custom-scriptlet" on-click="handleAdd_">
$i18n{adblockAddCustomScriptletButton}
</cr-button>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { BaseMixin } from '../../base_mixin.js'

import { getTemplate } from './brave_adblock_scriptlet_list.html.js'

import { loadTimeData } from '../../i18n_setup.js'

import {
Scriptlet,
BraveAdblockBrowserProxyImpl
Expand Down Expand Up @@ -52,6 +54,12 @@ class AdblockScriptletList extends AdblockScriptletListBase {

override ready() {
super.ready()

if (loadTimeData.getBoolean('shouldExposeElementsForTesting')) {
window.testing = window.testing || {}
window.testing[`adblockScriptletList`] = this.shadowRoot
}

this.isEditing_ = false
this.browserProxy_.getCustomScriptlets().then((scriptlets) => {
this.customScriptletsList_ = scriptlets
Expand All @@ -69,9 +77,11 @@ class AdblockScriptletList extends AdblockScriptletListBase {
}

handleDelete_(e: any) {
const messageText = this.i18n('adblockCustomScriptletDeleteConfirmation')
if (!confirm(messageText)) {
return
if (!loadTimeData.getBoolean('shouldExposeElementsForTesting')) {
const messageText = this.i18n('adblockCustomScriptletDeleteConfirmation')
if (!confirm(messageText)) {
return
}
}

this.browserProxy_.removeCustomScriptlet(
Expand Down
Loading

0 comments on commit e999fa1

Please sign in to comment.