Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration test improvements #5935

Merged
merged 9 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 3 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
"test:unit": "vitest run --coverage --config vitest.unit.config.mts",
"dev": "yarn wipedist && tsc -w -p src",
"test:watch": "vitest --config vitest.unit.config.mts --coverage",
"test:integration": "tsx ./src/scripts/integration-tests.ts",
"build:esbuild": "esbuild --bundle src/index.ts --outdir=dist --platform=node --loader:.node=file --external:canvas"
"test:integration": "tsx ./src/scripts/integration-tests.ts"
},
"dependencies": {
"@fastify/cors": "^8.2.0",
Expand Down Expand Up @@ -59,25 +58,19 @@
"devDependencies": {
"@biomejs/biome": "^1.8.3",
"@oldschoolgg/ts-config": "^0.0.1",
"@types/jest-image-snapshot": "^6.1.0",
"@types/lodash": "^4.14.195",
"@types/mitm": "^1.3.8",
"@types/node": "^14.18.12",
"@types/node": "^20.14.9",
"@types/node-cron": "^3.0.7",
"@types/node-fetch": "^2.6.1",
"@vitest/coverage-v8": "^1.6.0",
"concurrently": "^8.2.2",
"dotenv-cli": "^7.4.2",
"dpdm": "^3.14.0",
"esbuild": "^0.22.0",
"fast-glob": "^3.3.2",
"jest-image-snapshot": "^6.2.0",
"mitm": "^1.7.2",
"prettier": "^3.3.2",
"prisma": "^5.13.0",
"rimraf": "^5.0.7",
"tsx": "^4.16.0",
"typescript": "5.0.2",
"typescript": "^5.5.3",
"vitest": "^1.6.0"
},
"engines": {
Expand Down
9 changes: 1 addition & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,7 @@ export const mahojiClient = new MahojiClient({
});

declare global {
const globalClient: OldSchoolBotClient;
}
declare global {
namespace NodeJS {
interface Global {
globalClient: OldSchoolBotClient;
}
}
var globalClient: OldSchoolBotClient;
}

client.mahojiClient = mahojiClient;
Expand Down
14 changes: 2 additions & 12 deletions src/lib/MUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,8 @@ Charge your items using ${mentionCommand(globalClient, 'minion', 'charge')}.`
}
declare global {
export type MUser = MUserClass;
var mUserFetch: typeof srcMUserFetch;
var GlobalMUserClass: typeof MUserClass;
}

export async function srcMUserFetch(userID: string) {
Expand All @@ -962,17 +964,5 @@ export async function srcMUserFetch(userID: string) {
return new MUserClass(user);
}

declare global {
const mUserFetch: typeof srcMUserFetch;
const GlobalMUserClass: typeof MUserClass;
}
declare global {
namespace NodeJS {
interface Global {
mUserFetch: typeof srcMUserFetch;
GlobalMUserClass: typeof MUserClass;
}
}
}
global.mUserFetch = srcMUserFetch;
global.GlobalMUserClass = MUserClass;
10 changes: 2 additions & 8 deletions src/lib/bankImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -944,15 +944,9 @@ export async function drawChestLootImage(options: {
}

declare global {
const bankImageGenerator: BankImageTask;
}
declare global {
namespace NodeJS {
interface Global {
bankImageGenerator: BankImageTask;
}
}
var bankImageGenerator: BankImageTask;
}

export const bankImageTask = new BankImageTask();
global.bankImageGenerator = bankImageTask;
bankImageGenerator.init();
10 changes: 2 additions & 8 deletions src/lib/geImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,15 +231,9 @@ class GeImageTask {
}

declare global {
const geImageGenerator: GeImageTask;
}
declare global {
namespace NodeJS {
interface Global {
geImageGenerator: GeImageTask;
}
}
var geImageGenerator: GeImageTask;
}

global.geImageGenerator = new GeImageTask();

geImageGenerator.init();
5 changes: 0 additions & 5 deletions src/lib/grandExchange.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { GEListing, GETransaction } from '@prisma/client';
import { GEListingType } from '@prisma/client';
import { Stopwatch } from '@sapphire/stopwatch';
import { ButtonBuilder, ButtonStyle, bold, userMention } from 'discord.js';
import { Time, calcPercentOfNum, clamp, noOp, sumArr } from 'e';
import { Bank } from 'oldschooljs';
Expand Down Expand Up @@ -846,8 +845,6 @@ Difference: ${shouldHave.difference(currentBank)}`);
private async _tick() {
if (!this.ready) return;
if (this.locked) return;
const stopwatch = new Stopwatch();
stopwatch.start();
const { buyListings: _buyListings, sellListings: _sellListings } = await this.fetchActiveListings();

// Filter out listings from Blacklisted users:
Expand Down Expand Up @@ -895,8 +892,6 @@ Difference: ${shouldHave.difference(currentBank)}`);
// Process only one transaction per tick
break;
}

stopwatch.stop();
}

async totalReset() {
Expand Down
9 changes: 1 addition & 8 deletions src/lib/roboChimp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,7 @@ import { calculateMastery } from './mastery';
import { MUserStats } from './structures/MUserStats';

declare global {
const roboChimpClient: PrismaClient;
}
declare global {
namespace NodeJS {
interface Global {
roboChimpClient: PrismaClient;
}
}
var roboChimpClient: PrismaClient;
}

export type RobochimpUser = User;
Expand Down
10 changes: 3 additions & 7 deletions src/lib/settings/prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,12 @@ import type { ActivityTaskData } from '../types/minions';
import { sqlLog } from '../util/logger';

declare global {
namespace NodeJS {
interface Global {
prisma: PrismaClient | undefined;
}
}
var prisma: PrismaClient | undefined;
}

function makePrismaClient(): PrismaClient {
if (!isMainThread && !process.env.TEST) return null as any;
if (!production && !process.env.TEST) console.log('Making prisma client...');
if (!isMainThread) {
if (!isMainThread && !process.env.TEST) {
throw new Error('Prisma client should only be created on the main thread.');
}

Expand All @@ -32,6 +27,7 @@ function makePrismaClient(): PrismaClient {
});
}

// biome-ignore lint/suspicious/noRedeclare: <explanation>
export const prisma = global.prisma || makePrismaClient();
global.prisma = prisma;

Expand Down
9 changes: 1 addition & 8 deletions src/lib/util/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,7 @@ function _debugLog(str: string, context: LogContext = {}) {
sonicBoom.write(`${JSON.stringify(o)}\n`);
}
declare global {
const debugLog: typeof _debugLog;
}
declare global {
namespace NodeJS {
interface Global {
debugLog: typeof _debugLog;
}
}
var debugLog: typeof _debugLog;
}

global.debugLog = _debugLog;
10 changes: 2 additions & 8 deletions src/lib/util/transactItemsFromBank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,9 @@ export interface TransactItemsArgs {
}

declare global {
const transactItems: typeof transactItemsFromBank;
}
declare global {
namespace NodeJS {
interface Global {
transactItems: typeof transactItemsFromBank;
}
}
var transactItems: typeof transactItemsFromBank;
}

global.transactItems = transactItemsFromBank;
export async function transactItemsFromBank({
userID,
Expand Down
10 changes: 7 additions & 3 deletions src/scripts/integration-tests.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { execSync } from 'node:child_process';
import path from 'node:path';
import { config } from 'dotenv';
import { sleep } from 'e';

async function main() {
Expand All @@ -9,11 +11,13 @@ async function main() {
await sleep(2000);

console.log('Getting ready...');
execSync('dotenv -e .env.test -- prisma db push --schema="./prisma/schema.prisma"', { stdio: 'inherit' });
execSync('dotenv -e .env.test -- prisma db push --schema="./prisma/robochimp.prisma"', { stdio: 'inherit' });
const env = { ...process.env, ...config({ path: path.resolve('.env.test') }).parsed };

execSync('npx prisma db push --schema="./prisma/schema.prisma"', { stdio: 'inherit', env });
execSync('npx prisma db push --schema="./prisma/robochimp.prisma"', { stdio: 'inherit', env });

console.log('Building...');
execSync('yarn build:esbuild', { stdio: 'inherit' });
execSync('yarn build', { stdio: 'inherit' });

console.log('Starting tests...');
const runs = 1;
Expand Down
33 changes: 19 additions & 14 deletions tests/integration/allCommandsBase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ test(
await maxUser.update({ bitfield: [BitField.isModerator] });
const store = new Store({ name: 'commands', dirs: [join('dist', 'mahoji')], checker: isValidCommand });
await store.load();
const currentClientSettings = await mahojiClientSettingsFetch({ construction_cost_bank: true });
await mahojiClientSettingsFetch({ construction_cost_bank: true });
await prisma.activity.deleteMany({
where: {
user_id: BigInt(maxUser.id)
Expand Down Expand Up @@ -289,30 +289,35 @@ test(
['minion', 'bankbg']
];

const promises = [];

for (const command of cmds) {
if (ignoredCommands.includes(command.name)) continue;
const options = await generateCommandInputs(maxUser, command.options!);

const options = shuffleArr(await generateCommandInputs(maxUser, command.options!)).slice(0, 5);
outer: for (const option of options) {
for (const [parent, sub, subCommand] of ignoredSubCommands) {
if (command.name === parent && option[sub] && (subCommand ? option[sub][subCommand] : true)) {
continue outer;
}
}
try {
const res = await maxUser.runCommand(command, option);
minionActivityCache.clear();
// console.log(`Running command ${command.name}
// Options: ${JSON.stringify(option)}
// Result: ${JSON.stringify(res).slice(0, 100)}`);
} catch (err) {
console.error(
`Failed to run command ${command.name} with options ${JSON.stringify(option)}: ${err}`
);
throw err;
}

promises.push(async () => {
try {
await maxUser.runCommand(command, option);
minionActivityCache.clear();
} catch (err) {
console.error(
`Failed to run command ${command.name} with options ${JSON.stringify(option)}: ${err}`
);
throw err;
}
});
}
}

await Promise.all(promises);

await client.processActivities();
},
{
Expand Down
16 changes: 7 additions & 9 deletions tests/integration/commands/open.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import { Bank } from 'oldschooljs';
import { beforeEach, describe, expect, test } from 'vitest';
import { describe, expect, test } from 'vitest';

import { openCommand } from '../../../src/mahoji/commands/open';
import { randomMock } from '../setup';
import { createTestUser, mockClient } from '../util';

describe('Open Command', async () => {
await mockClient();
const user = await createTestUser();

beforeEach(async () => {
test.concurrent('Open with no quantity', async () => {
randomMock();
await user.reset();
const user = await createTestUser();
await user.addItemsToBank({ items: new Bank().add('Reward casket (beginner)', 100) });
});

test('Open with no quantity', async () => {
const result = await user.runCommand(openCommand, { name: 'reward casket (beginner)' });
expect(result).toMatchObject({
content: `You have now opened a total of 1x Reward casket (beginner)
Expand All @@ -31,7 +26,10 @@ describe('Open Command', async () => {
await user.clMatch(new Bank().add('Fire rune', 34));
});

test('Open with quantity', async () => {
test.concurrent('Open with quantity', async () => {
randomMock();
const user = await createTestUser();
await user.addItemsToBank({ items: new Bank().add('Reward casket (beginner)', 100) });
await user.runCommand(openCommand, { name: 'reward casket (beginner)', quantity: 10 });
await user.bankAmountMatch('Reward casket (beginner)', 90);
await user.openedBankMatch(new Bank().add('Reward casket (beginner)', 10));
Expand Down
Loading
Loading