Skip to content
This repository has been archived by the owner on Aug 15, 2023. It is now read-only.

Commit

Permalink
build(guardoni): fix cli testing scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
ascariandrea committed Oct 17, 2022
1 parent 5ffc2d1 commit d40f7b1
Show file tree
Hide file tree
Showing 24 changed files with 230 additions and 112 deletions.
50 changes: 50 additions & 0 deletions packages/shared/src/utils/csv.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { AppError, toAppError } from '../errors/AppError';
import csvParse from 'csv-parse';
import * as csvStringify from 'csv-stringify';
import * as TE from 'fp-ts/lib/TaskEither';
import { GetLogger } from '../logger';
const csvLogger = GetLogger('csv')

export const csvParseTE = (
content: Buffer,
options: csvParse.Options
): TE.TaskEither<
AppError,
{
records: any;
info: csvParse.Info;
}
> =>
TE.tryCatch(
() =>
new Promise((resolve, reject) => {
csvParse(content, options, (error, records, info) => {
if (error) {
csvLogger.error('CSV Parse error: %O', error);
return reject(error);
}
csvLogger.debug('CSV Parse results: %O', records);
return resolve({ records, info });
});
}),
toAppError
);

export const csvStringifyTE = (
records: any[],
options: csvStringify.Options
): TE.TaskEither<AppError, string> =>
TE.tryCatch(
() =>
new Promise((resolve, reject) => {
csvStringify.stringify(records, options, (error, info) => {
if (error) {
csvLogger.error('CSV Stringify error: %O', error);
return reject(error);
}
csvLogger.debug('CSV Stringify results: %O', records);
return resolve(info);
});
}),
toAppError
);
6 changes: 5 additions & 1 deletion packages/shared/src/utils/fp.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ export const foldTEOrThrow = <E, A>(te: TE.TaskEither<E, A>): Promise<A> => {
return pipe(
te,
TE.fold(
(e) => () => Promise.reject(e),
(e) => () => {
// eslint-disable-next-line
console.error(e);
return Promise.reject(e)
},
(a) => () => Promise.resolve(a)
)
)();
Expand Down
2 changes: 1 addition & 1 deletion platforms/guardoni/__tests__/cli/cli-tk.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import differenceInMilliseconds from 'date-fns/differenceInMilliseconds';
import * as fs from 'fs';
import * as path from 'path';
import { GetGuardoniCLI, GuardoniCLI } from '../../src/guardoni/cli';
import { csvStringifyTE } from '../../src/guardoni/utils';
import { csvStringifyTE } from '@shared/utils/csv.utils';
import axiosMock from '@shared/test/__mocks__/axios.mock';
import { puppeteerMock } from '@shared/test/__mocks__/puppeteer.mock';
import { formatExperimentList } from '../../src/guardoni/experiment';
Expand Down
2 changes: 1 addition & 1 deletion platforms/guardoni/__tests__/cli/cli-yt.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { pipe } from 'fp-ts/lib/function';
import * as fs from 'fs';
import * as path from 'path';
import { GetGuardoniCLI, GuardoniCLI } from '../../src/guardoni/cli';
import { csvStringifyTE } from '../../src/guardoni/utils';
import { csvStringifyTE } from '@shared/utils/csv.utils';
import axiosMock from '@shared/test/__mocks__/axios.mock';
import { puppeteerMock } from '@shared/test/__mocks__/puppeteer.mock';
import { getProfileDataDir, readProfile } from '../../src/guardoni/profile';
Expand Down
2 changes: 1 addition & 1 deletion platforms/guardoni/__tests__/guardoni.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as path from 'path';
import { readConfigFromPath } from '../src/guardoni/config';
import { GetGuardoni } from '../src/guardoni/guardoni';
import { getDefaultProfile, getProfileDataDir } from '../src/guardoni/profile';
import { csvStringifyTE } from '../src/guardoni/utils';
import { csvStringifyTE } from '@shared/utils/csv.utils';
import { guardoniLogger } from '../src/logger';
import { fc } from '@shared/test';

Expand Down
3 changes: 3 additions & 0 deletions platforms/guardoni/experiments/yt-videos.csv
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ title,url,urltag,watchFor,incrementScrollByPX,totalScroll
YouChoose: Customize your Recommendations,https://www.youtube.com/watch?v=3laqegktOuQ,youchoose-recommendations,3s,400,1000
YouChoose.ai | Gain Control on your Recommendations!,https://www.youtube.com/watch?v=ReVMTcRA-E4,youchose-gain-Control,3s,400,1000
with Tracking Exposed: knowledge is freedom — algorithm analysis is for anybody!,https://www.youtube.com/watch?v=SmYuYEhT81c,trex-algorithm,5s,400,1000
How to Investigate TikTok’s Algorithm,https://www.youtube.com/watch?v=jpb83sxcDdI,trex-algorithm,15s,400,1000
Scopriamo Tracking.Exposed,https://www.youtube.com/watch?v=VKO9UXy-vlo,trex-alorihtm,15s,400,1000
facebook tracking exposed: come Facebook condiziona il nostro modo di vedere il mondo ,https://www.youtube.com/watch?v=vDzBNID4CjI,trex-alorihtm,15s,400,1000
5 changes: 3 additions & 2 deletions platforms/guardoni/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@
"prepack": "yarn build",
"check-stealth": "ts-node ./bin/check-stealth.ts",
"tdd": "jest --watch --verbose",
"cli-yt-test-videos": "node ./scripts/cli-yt-test-videos.mjs",
"cli-yt-test-home": "node ./scripts/cli-yt-test-home.mjs"
"cli-yt-test-videos": "ts-node ./scripts/cli-yt-test-videos.mjs",
"cli-yt-test-home": "ts-node ./scripts/cli-yt-test-home-fixures.mjs",
"cli-yt-test-from-fixtures": "ts-node ./scripts/cli-yt-test-home-fixures.mjs"
},
"bin": {
"cli": "./bin/guardoni-cli.js"
Expand Down
130 changes: 130 additions & 0 deletions platforms/guardoni/scripts/cli-test-from-fixtures.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#!/usr/bin/env node

/* eslint-disable camelcase */

import { $, os, fetch, fs, path } from 'zx';
import { normalizePlatform, getGuardoniCliPkgName } from './utils.mjs';
import dotenv from 'dotenv';
import assert from 'assert';
import {
readFixtureJSONPaths,
readFixtureJSON,
} from '../../../packages/shared/build/test/utils/parser.utils.js';
import { csvStringifyTE } from '../../../packages/shared/build/utils/csv.utils.js';
import { foldTEOrThrow } from '../../../packages/shared/build/utils/fp.utils.js';

dotenv.config({ path: '.env.development' });

// eslint-disable-next-line no-void
void (async function () {
const [p, nature, count] = process.argv.slice(2);
console.log({ p, nature, count });

if (!p) {
console.error('Platform parameter not present');
process.exit(1);
}

if (!nature) {
console.error('Nature parameter not present');
process.exit(1);
}

const version = await $`node -p -e "require('./package.json').version"`;
const platform = normalizePlatform(os.type());
const profile = 'profile-test-99';

fs.removeSync(path.resolve(process.cwd(), 'profiles', profile));

const cli = `./dist/${getGuardoniCliPkgName(
version.stdout.replace('\n', ''),
platform
)}`;

const flags = [
'--basePath=./',
`--executablePath=${process.env.PUPPETEER_EXEC_PATH}`,
'-c=guardoni.config.json',
'--headless=false',
'--verbose',
];

const researchTag = `guardoni-${p}-test-${nature}`;

const experimentFlags = [
...flags,
`--publicKey=${process.env.PUBLIC_KEY}`,
`--secretKey=${process.env.SECRET_KEY}`,
`--researchTag=${researchTag}`,
];

const fixturePaths = readFixtureJSONPaths(
path.resolve(
process.cwd(),
`../${p}trex/backend/__tests__/fixtures/htmls/${nature}`
)
);

const take = parseInt(count, 10) ?? fixturePaths.length;
await $`echo "Taking ${take} fixtures"`;
const fixtures = fixturePaths
.slice(0, take)
.map((f) => readFixtureJSON(f, process.env.PUBLIC_KEY));

const sources = fixtures.reduce(
(acc, f, i) =>
acc.concat(
f.sources.map((s, ii) => ({
title: f.metadata.title,
url: s.href,
urltag: `${p}-test-${nature}-${i}-${ii}`,
watchFor: '5s',
incrementScrollByPX: 400,
totalScroll: 1000,
}))
),
[]
);

// reject cookie modal
await $`${cli} ${flags} ${p}-navigate`;

const experiment = await foldTEOrThrow(
csvStringifyTE(sources, { header: 'true' })
);

const experimentFile = path.resolve(
process.cwd(),
`./experiments/${p}-${nature}-test-from-fixtures-temp.csv`
);

fs.writeFileSync(experimentFile, experiment, 'utf-8');

const yt_home_experiment_register_out =
await $`${cli} ${flags} ${p}-register ${experimentFile}`;

const yt_home_experiment_id = yt_home_experiment_register_out.stdout
.split('\n')
.find((s) => s.startsWith('experimentId:'))
.replace('experimentId: \t', '')
.trim();

const yt_home_experiment_run_out =
await $`${cli} ${experimentFlags} ${p}-experiment ${yt_home_experiment_id} | grep 'publicKey: ' `;

const yt_home_experiment_public_key = yt_home_experiment_run_out.stdout
.replace('publicKey: \t ', '')
.replace('\n', '');

assert.strictEqual(yt_home_experiment_public_key, process.env.PUBLIC_KEY);

const backend = p === 'tk' ? process.env.TK_BACKEND : process.env.YT_BACKEND;
const personalURL = `${backend}/v2/personal/${yt_home_experiment_public_key}/${nature}/json`;
await $`echo ${personalURL}`;

// const metadata = await fetch(
// `http://localhost:9000/api/v2/metadata?publicKey=${yt_home_experiment_public_key}&experimentId=${yt_home_experiment_id}&nature=home`
// ).then((r) => r.json());

fs.removeSync(experimentFile);
})();
3 changes: 2 additions & 1 deletion platforms/guardoni/scripts/cli-tk-test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ void (async function () {

const tk_search_experiment_public_key = tk_search_experiment_run_out.stdout
.replace('publicKey: \t', '')
.replace('\n', '');
.replace('\n', '')
.trim();

await $`echo ${tk_search_experiment_public_key}`;

Expand Down
8 changes: 4 additions & 4 deletions platforms/guardoni/scripts/cli-yt-test-home.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void (async function () {
'--basePath=./',
`--executablePath=${process.env.PUPPETEER_EXEC_PATH}`,
'-c=guardoni.config.json',
'--headless',
'--headless=false',
'--verbose',
];

Expand All @@ -35,11 +35,11 @@ void (async function () {
...flags,
`--publicKey=${process.env.PUBLIC_KEY}`,
`--secretKey=${process.env.SECRET_KEY}`,
`--researchTag=${researchTag}`
`--researchTag=${researchTag}`,
];

// reject cookie modal
await $`${cli} ${flags} yt-navigate --cookie-modal=reject --exit --headless=false`;
await $`${cli} ${flags} yt-navigate --cookie-modal=reject --exit`;

const yt_home_experiment_register_out =
await $`${cli} ${flags} yt-register ./experiments/yt-home.csv | grep 'experimentId: '`;
Expand All @@ -64,7 +64,7 @@ void (async function () {

assert.strictEqual(yt_home_experiment_public_key, process.env.PUBLIC_KEY);
const metadata = await fetch(
`http://localhost:9000/api/v2/metadata?experimentId=${yt_home_experiment_id}`
`http://localhost:9000/api/v2/metadata?publicKey=${yt_home_experiment_public_key}&experimentId=${yt_home_experiment_id}`
).then((r) => r.json());

assert.strictEqual(metadata[0].experimentId, yt_home_experiment_id);
Expand Down
4 changes: 2 additions & 2 deletions platforms/guardoni/scripts/cli-yt-test-videos.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ void (async function () {
'--basePath=./',
`--executablePath=${process.env.PUPPETEER_EXEC_PATH}`,
'-c=guardoni.config.json',
'--headless',
'--headless=false',
'--verbose',
];

Expand Down Expand Up @@ -58,7 +58,7 @@ void (async function () {
.replace('publicKey: \t ', '')
.replace('\n', '');

assert.strictEqual(ytVideoExperimentPubKey, process.env.PUBLIC_KEY);
// assert.strictEqual(ytVideoExperimentPubKey, process.env.PUBLIC_KEY);

const metadata = await fetch(
`http://localhost:9000/api/v2/metadata?experimentId=${yt_video_experiment_id}`
Expand Down
5 changes: 3 additions & 2 deletions platforms/guardoni/src/guardoni/experiment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import _ from 'lodash';
// import * as NEA from 'fp-ts/lib/NonEmptyArray';
import { parseClickCommand } from '@shared/providers/puppeteer/steps/click';
import { parseKeypressCommand } from '@shared/providers/puppeteer/steps/keyPress';
import { csvParseTE } from '@shared/utils/csv.utils';
import { NonEmptyArray } from 'fp-ts/lib/NonEmptyArray';
import * as TE from 'fp-ts/lib/TaskEither';
import * as fs from 'fs';
Expand All @@ -28,9 +29,9 @@ import {
ExperimentInfo,
GuardoniContext,
GuardoniProfile,
GuardoniSuccessOutput,
GuardoniSuccessOutput
} from './types';
import { csvParseTE, liftFromIOE } from './utils';
import { liftFromIOE } from './utils';

export const validateNonEmptyString = (
s: string
Expand Down
12 changes: 5 additions & 7 deletions platforms/guardoni/src/guardoni/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,16 +196,14 @@ const getSettingsJSONPath = (ctx: GuardoniContext): string =>
export const setLocalSettings =
(ctx: GuardoniContext) =>
(s?: Partial<UserSettings>): void => {
if (!s?.publicKey && !s?.secretKey) {
ctx.logger.debug('No publicKey/secretKey pair given...');
const keys = Object.keys(s ?? {});
const settingsJsonPath = getSettingsJSONPath(ctx);
if (keys.length === 0) {
ctx.logger.debug('No values for %s given...', settingsJsonPath);
return;
}

const settingsJsonPath = getSettingsJSONPath(ctx);

ctx.logger.info('Saving settings at %s: %O', settingsJsonPath, s);
const settings = JSON.stringify(s);

ctx.logger.info('Saving settings at %s: %O', settingsJsonPath, settings);

fs.writeFileSync(settingsJsonPath, settings);
};
44 changes: 0 additions & 44 deletions platforms/guardoni/src/guardoni/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { AppError, toAppError } from '@shared/errors/AppError';
import csvParse from 'csv-parse';
import * as csvStringify from 'csv-stringify';
import * as E from 'fp-ts/lib/Either';
import { pipe } from 'fp-ts/lib/function';
import * as IOE from 'fp-ts/lib/IOEither';
Expand Down Expand Up @@ -70,49 +68,7 @@ export const toGuardoniSuccessOutput = (
};
};

export const csvParseTE = (
content: Buffer,
options: csvParse.Options
): TE.TaskEither<
AppError,
{
records: any;
info: csvParse.Info;
}
> =>
TE.tryCatch(
() =>
new Promise((resolve, reject) => {
csvParse(content, options, (error, records, info) => {
if (error) {
guardoniLogger.error('CSV Parse error: %O', error);
return reject(error);
}
guardoniLogger.debug('CSV Parse results: %O', records);
return resolve({ records, info });
});
}),
toAppError
);

export const csvStringifyTE = (
records: any[],
options: csvStringify.Options
): TE.TaskEither<AppError, string> =>
TE.tryCatch(
() =>
new Promise((resolve, reject) => {
csvStringify.stringify(records, options, (error, info) => {
if (error) {
guardoniLogger.error('CSV Stringify error: %O', error);
return reject(error);
}
guardoniLogger.debug('CSV Stringify results: %O', records);
return resolve(info);
});
}),
toAppError
);

export const liftFromIOE = <T>(lazyF: () => T): TE.TaskEither<AppError, T> => {
return pipe(IOE.tryCatch(lazyF, toAppError), TE.fromIOEither);
Expand Down
Loading

0 comments on commit d40f7b1

Please sign in to comment.