Skip to content

Commit

Permalink
AG-17519 improve logMessage helper and update tests
Browse files Browse the repository at this point in the history
Merge in ADGUARD-FILTERS/scriptlets from fix/AG-17519 to release/v1.8

Squashed commit of the following:

commit f54bbcc
Author: Stanislav A <[email protected]>
Date:   Wed Dec 28 15:52:35 2022 +0300

    tweak prevent-xhr test

commit 4060687
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 19:54:06 2022 +0300

    improve helper tests

commit 855ce89
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 19:14:57 2022 +0300

    fix changelog

commit 7054753
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 18:48:09 2022 +0300

    remove max-len from tests

commit f93dc21
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 18:42:29 2022 +0300

    improve naming

commit 21da001
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 18:30:38 2022 +0300

    update tests

commit 0903fb6
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 18:10:55 2022 +0300

    improve helper and add tests

commit 6e3dc40
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 17:21:56 2022 +0300

    improve naming

commit d4aa78e
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 16:04:39 2022 +0300

    update CHANGELOG

commit 8342527
Author: Stanislav A <[email protected]>
Date:   Tue Dec 27 16:00:11 2022 +0300

    improve logMessage helper and update tests
  • Loading branch information
stanislav-atr committed Dec 28, 2022
1 parent 1caed03 commit b2624bf
Show file tree
Hide file tree
Showing 23 changed files with 161 additions and 42 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
### Changed

- add decimal delay matching for `prevent-setInterval` and `prevent-setTimeout` [#247](https://github.com/AdguardTeam/Scriptlets/issues/247)
- debug logging to include rule text when available

### Fixed

Expand Down
26 changes: 23 additions & 3 deletions src/helpers/log-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,28 @@
* @param {boolean} [forced=false] to log message unconditionally
*/
export const logMessage = (source, message, forced = false) => {
if (forced || source.verbose) {
// eslint-disable-next-line no-console
console.log(`${source.name}: ${message}`);
const {
name,
ruleText,
verbose,
} = source;

if (!forced && !verbose) {
return;
}

let messageStr = `${name}: ${message}`;

// Extract scriptlet part from rule text
if (ruleText) {
const RULE_MARKER = '#%#//scriptlet';
const markerIdx = ruleText.indexOf(RULE_MARKER);
if (markerIdx > -1) {
const ruleWithoutDomains = ruleText.slice(markerIdx, ruleText.length);
messageStr += `; cannot apply rule: ${ruleWithoutDomains}`;
}
}

// eslint-disable-next-line no-console
console.log(messageStr);
};
2 changes: 1 addition & 1 deletion src/scriptlets/adjust-setInterval.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function adjustSetInterval(source, matchCallback, matchDelay, boost) {
// https://github.com/AdguardTeam/Scriptlets/issues/221
if (!isValidCallback(callback)) {
// eslint-disable-next-line max-len
const message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'.`;
const message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'`;
logMessage(source, message);
} else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
delay *= getBoostMultiplier(boost);
Expand Down
2 changes: 1 addition & 1 deletion src/scriptlets/adjust-setTimeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function adjustSetTimeout(source, matchCallback, matchDelay, boost) {
// https://github.com/AdguardTeam/Scriptlets/issues/221
if (!isValidCallback(callback)) {
// eslint-disable-next-line max-len
const message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'.`;
const message = `Scriptlet can't be applied because of invalid callback: '${String(callback)}'`;
logMessage(source, message);
} else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
delay *= getBoostMultiplier(boost);
Expand Down
2 changes: 1 addition & 1 deletion src/scriptlets/trusted-replace-fetch-response.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export function trustedReplaceFetchResponse(source, pattern = '', replacement =

// Only allow pattern as empty string for logging purposes
if (pattern === '' && replacement !== '') {
logMessage(source, 'Pattern argument should not be empty string.');
logMessage(source, 'Pattern argument should not be empty string');
return;
}
const shouldLog = pattern === '' && replacement === '';
Expand Down
4 changes: 2 additions & 2 deletions src/scriptlets/trusted-set-cookie-reload.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ import {

export function trustedSetCookieReload(source, name, value, offsetExpiresSec = '', path = '/') {
if (typeof name === 'undefined') {
logMessage(source, 'Cookie name should be specified.');
logMessage(source, 'Cookie name should be specified');
return;
}
if (typeof value === 'undefined') {
logMessage(source, 'Cookie value should be specified.');
logMessage(source, 'Cookie value should be specified');
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/scriptlets/trusted-set-cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ import {

export function trustedSetCookie(source, name, value, offsetExpiresSec = '', path = '/') {
if (typeof name === 'undefined') {
logMessage(source, 'Cookie name should be specified.');
logMessage(source, 'Cookie name should be specified');
return;
}
if (typeof value === 'undefined') {
logMessage(source, 'Cookie value should be specified.');
logMessage(source, 'Cookie value should be specified');
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/scriptlets/trusted-set-local-storage-item.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ import {

export function trustedSetLocalStorageItem(source, key, value) {
if (typeof key === 'undefined') {
logMessage(source, 'Item key should be specified.');
logMessage(source, 'Item key should be specified');
return;
}

if (typeof value === 'undefined') {
logMessage(source, 'Item value should be specified.');
logMessage(source, 'Item value should be specified');
return;
}

Expand Down
1 change: 1 addition & 0 deletions tests/helpers/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ import './noop.test';
import './number-utils.test';
import './string-utils.test';
import './object-utils.test';
import './log-message.test';
83 changes: 83 additions & 0 deletions tests/helpers/log-message.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/* eslint-disable no-console */
import {
logMessage,
} from '../../src/helpers';

const { test, module } = QUnit;
const name = 'scriptlets-redirects helpers';
const nativeConsole = console.log;

const afterEach = () => {
console.log = nativeConsole;
};

module(name, { afterEach });

const RULE_TEXT = 'example.org#%#//scriptlet(\'set-cookie\', \'name\', \'value\')';
const SCRIPTLET_NAME = 'set-cookie';
const MESSAGE = 'arbitrary text message';
const MESSAGE_EXTENSION = '; cannot apply rule: #%#//scriptlet(\'set-cookie\', \'name\', \'value\')';

test('Logs message conditionally', async (assert) => {
// eslint-disable-next-line no-console
console.log = function log(input) {
if (input.indexOf('trace') > -1) {
return;
}
assert.strictEqual(
input,
`${SCRIPTLET_NAME}: ${MESSAGE}${MESSAGE_EXTENSION}`,
'message logged correctly',
);
};

assert.expect(2);

// Log forced message
let forced = true;
let source = {
name: SCRIPTLET_NAME,
ruleText: RULE_TEXT,
verbose: false,
};
logMessage(source, MESSAGE, forced);

// Log message on verbose
forced = false;
source = {
name: SCRIPTLET_NAME,
ruleText: RULE_TEXT,
verbose: true,
};
logMessage(source, MESSAGE, forced);

// Message should not be logged this time, thus expected 2 asserts
forced = false;
source = {
name: SCRIPTLET_NAME,
ruleText: RULE_TEXT,
verbose: false,
};
logMessage(source, MESSAGE, forced);
});

test('Logs message without ruleText', async (assert) => {
// eslint-disable-next-line no-console
console.log = function log(input) {
if (input.indexOf('trace') > -1) {
return;
}
assert.strictEqual(
input,
`${SCRIPTLET_NAME}: ${MESSAGE}`,
'message logged correctly',
);
};

const FORCED = true;
const source = {
name: SCRIPTLET_NAME,
verbose: false,
};
logMessage(source, MESSAGE, FORCED);
});
2 changes: 1 addition & 1 deletion tests/scriptlets/adjust-setInterval.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ test('no match -- invalid callback - undefined', (assert) => {
assert.strictEqual(window.hit, undefined, 'hit should not fire');
assert.strictEqual(
loggedMessage,
`${name}: Scriptlet can't be applied because of invalid callback: '${String(callback)}'.`, // eslint-disable-line max-len
`${name}: Scriptlet can't be applied because of invalid callback: '${String(callback)}'`,
'console.logged warning ok',
);
clearInterval(testInterval);
Expand Down
2 changes: 1 addition & 1 deletion tests/scriptlets/adjust-setTimeout.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ test('no match -- invalid callback - undefined', (assert) => {
assert.strictEqual(window.hit, undefined, 'hit should not fire');
assert.strictEqual(
loggedMessage,
`${name}: Scriptlet can't be applied because of invalid callback: '${String(callback)}'.`, // eslint-disable-line max-len
`${name}: Scriptlet can't be applied because of invalid callback: '${String(callback)}'`,
'console.logged warning ok',
);
clearTimeout(testTimeout);
Expand Down
4 changes: 2 additions & 2 deletions tests/scriptlets/nowebrtc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ if (!isSupported) {
if (input.indexOf('trace') > -1) {
return;
}
// eslint-disable-next-line max-len
const EXPECTED_LOG_STR = `${name}: Document tried to create an RTCPeerConnection: ${TEST_URL_VALUE}`;

const EXPECTED_LOG_STR = `${name}: Document tried to create an RTCPeerConnection: ${TEST_URL_VALUE};`;
assert.ok(endsWith(input, EXPECTED_LOG_STR), 'console.hit input');
};

Expand Down
2 changes: 1 addition & 1 deletion tests/scriptlets/prevent-eval-if.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ test('AG prevent-eval-if works', (assert) => {
const firstActual = evalWrapper(`(function () {return '${agPreventEvalIf}'})()`);
assert.strictEqual(window.hit, undefined, 'hit function should not fire for not matched function');
assert.strictEqual(firstActual, agPreventEvalIf, 'result of eval evaluation should exist');
// eslint-disable-next-line max-len

const secondActual = evalWrapper(`(function () {const test = 0; return '${agPreventEvalIf}'})()`);
assert.strictEqual(window.hit, 'FIRED', 'hit function should fire');
assert.strictEqual(secondActual, undefined, 'result of eval evaluation should be undefined');
Expand Down
1 change: 0 additions & 1 deletion tests/scriptlets/prevent-fetch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ if (!isSupported) {
if (input.indexOf('trace') > -1) {
return;
}
// eslint-disable-next-line max-len
const EXPECTED_LOG_STR_START = `${name}: fetch( url:"${INPUT_JSON_PATH}" method:"${TEST_METHOD}"`;
assert.ok(startsWith(input, EXPECTED_LOG_STR_START), 'console.hit input');
};
Expand Down
6 changes: 5 additions & 1 deletion tests/scriptlets/prevent-requestAnimationFrame.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ test('prevent-requestAnimationFrame: no args -- logging', (assert) => {
// do test checking after scriptlet's execution end
setTimeout(() => {
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
assert.strictEqual(loggedMessage, `prevent-requestAnimationFrame: requestAnimationFrame(${testFunction.toString()})`, 'console.hit input');
assert.strictEqual(
loggedMessage,
`prevent-requestAnimationFrame: requestAnimationFrame(${testFunction.toString()})`,
'console.hit input',
);
assert.strictEqual(window[logProperty], 'changed', 'property changed');
clearGlobalProps(logProperty);
done();
Expand Down
2 changes: 0 additions & 2 deletions tests/scriptlets/prevent-setInterval.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ test('setInterval callback name matching', (assert) => {
// We need to run our assertion after all timeouts
setTimeout(() => {
assert.equal(window.one, 'value', 'Target property not changed');
// eslint-disable-next-line max-len
assert.equal(window.two, 'new value', 'Another property should successfully changed by another timeout');
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
done();
Expand Down Expand Up @@ -113,7 +112,6 @@ test('code matching', (assert) => {
// We need to run our assertion after all timeouts
setTimeout(() => {
assert.equal(window.one, 'value', 'Target property not changed');
// eslint-disable-next-line max-len
assert.equal(window.two, 'new value', 'Another property should be successfully changed by another timeout');
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
done();
Expand Down
2 changes: 0 additions & 2 deletions tests/scriptlets/prevent-setTimeout.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ test('setTimeout callback name matching', (assert) => {
// We need to run our assertion after all timeouts
nativeSetTimeout(() => {
assert.equal(window.one, 'value', 'Target property not changed');
// eslint-disable-next-line max-len
assert.equal(window.two, 'new value', 'Another property should successfully changed by another timeout');
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
done();
Expand Down Expand Up @@ -113,7 +112,6 @@ test('code matching', (assert) => {
// We need to run our assertion after all timeouts
nativeSetTimeout(() => {
assert.equal(window.one, 'value', 'Target property not changed');
// eslint-disable-next-line max-len
assert.equal(window.two, 'new value', 'Another property should be successfully changed by another timeout');
assert.strictEqual(window.hit, 'FIRED', 'hit fired');
done();
Expand Down
1 change: 0 additions & 1 deletion tests/scriptlets/prevent-window-open.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,6 @@ test('new syntax: log checking - url + args', (assert) => {
if (input.indexOf('trace') > -1) {
return;
}
// eslint-disable-next-line max-len
const EXPECTED_LOG_STR = `${name}: ${testUrl}, ${testWindowName}, ${testWindowFeatures}`;
assert.strictEqual(input, EXPECTED_LOG_STR, 'console.hit input');
};
Expand Down
39 changes: 25 additions & 14 deletions tests/scriptlets/prevent-xhr.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ if (isSupported) {
xhr.open(METHOD, URL);
xhr.onload = () => {
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length > 20000, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length > 20000,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand All @@ -151,8 +153,10 @@ if (isSupported) {
xhr.onload = () => {
assert.strictEqual(xhr.readyState, 4, 'Response done');
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length > 20000, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length > 20000,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand All @@ -173,8 +177,10 @@ if (isSupported) {
xhr.onload = () => {
assert.strictEqual(xhr.readyState, 4, 'Response done');
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length === 100, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length === 100,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand All @@ -195,8 +201,10 @@ if (isSupported) {
xhr.onload = () => {
assert.strictEqual(xhr.readyState, 4, 'Response done');
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length === 500000, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length === 500000,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand All @@ -216,7 +224,6 @@ if (isSupported) {
xhr.open(METHOD, URL);
xhr.onload = () => {
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length === 0, 'Response text is not randomized');
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
Expand Down Expand Up @@ -257,8 +264,10 @@ if (isSupported) {
xhr.open(METHOD, URL);
xhr.onload = () => {
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length >= 100 && xhr.responseText.length <= 300, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length >= 100 && xhr.responseText.length <= 300,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand All @@ -278,8 +287,10 @@ if (isSupported) {
xhr.open(METHOD, URL);
xhr.onload = () => {
assert.strictEqual(typeof xhr.responseText, 'string', 'Response text mocked');
// eslint-disable-next-line max-len
assert.ok(xhr.responseText.length >= 10 && xhr.responseText.length <= 20, `Response text randomized, response length: ${xhr.responseText.length}`);
assert.ok(
xhr.responseText.length >= 10 && xhr.responseText.length <= 20,
`Response text randomized, response length: ${xhr.responseText.length}`,
);
assert.strictEqual(window.hit, 'FIRED', 'hit function fired');
done();
};
Expand Down Expand Up @@ -623,7 +634,7 @@ if (isSupported) {

xhr1.send();
// use timeout to avoid hit collisions
setTimeout(() => xhr2.send(), 1);
setTimeout(() => xhr2.send(), 10);
});
} else {
test('unsupported', (assert) => {
Expand Down
Loading

0 comments on commit b2624bf

Please sign in to comment.