Skip to content

Commit

Permalink
Fix tests (#5715)
Browse files Browse the repository at this point in the history
  • Loading branch information
gc authored Feb 25, 2024
1 parent 780053f commit a4f5251
Show file tree
Hide file tree
Showing 25 changed files with 254 additions and 199 deletions.
9 changes: 9 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
TZ="UTC"
ROBOCHIMP_DATABASE_URL=postgresql://postgres:postgres@localhost:5436/robochimp_integration_test?connection_limit=1000
DATABASE_URL=postgresql://postgres:postgres@localhost:5435/osb_integration_test?pool_timeout=120&connection_limit=1000
PATREON_CAMPAIGN_ID=1234
PATREON_TOKEN=asdfasdfasdf
PATREON_WEBHOOK_SECRET=asdfasdfasdf
HTTP_PORT=7373
CLIENT_ID=111398433321891634
PRISMA_CLIENT_ENGINE_TYPE=binary
5 changes: 4 additions & 1 deletion .github/workflows/integration_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ jobs:
os: [ubuntu-latest]

steps:
- name: Install System Packages
run: sudo apt-get install -y build-essential libpq-dev

- name: Checkout Project
uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node_version }}
Expand All @@ -37,6 +40,6 @@ jobs:
cp config.example.ts config.ts &&
popd
- name: Copy env
run: cp .env.example .env
run: cp .env.test .env
- name: Test
run: yarn test:integration
2 changes: 1 addition & 1 deletion .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
cp config.example.ts config.ts &&
popd
- name: Copy env
run: cp .env.example .env
run: cp .env.test .env
- name: Generate Prisma Client
run: yarn gen
- name: Run ESLint on changed files
Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ version: "3.9"
services:
osb:
image: postgres:13-alpine
command: -c 'max_connections=100'
command: -c 'max_connections=1000'
restart: always
container_name: osb_database
ports:
Expand All @@ -18,7 +18,7 @@ services:

robochimp:
image: postgres:13-alpine
command: -c 'max_connections=100'
command: -c 'max_connections=1000'
restart: always
container_name: robochimp_database
ports:
Expand Down
2 changes: 1 addition & 1 deletion src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ const globalConfigSchema = z.object({
clientID: z.string().min(15).max(25),
geAdminChannelID: z.string().default('')
});
dotenv.config({ path: path.resolve(process.cwd(), process.env.TEST ? '.env.example' : '.env') });
dotenv.config({ path: path.resolve(process.cwd(), process.env.TEST ? '.env.test' : '.env') });

export const globalConfig = globalConfigSchema.parse({
patreonToken: process.env.PATREON_TOKEN,
Expand Down
28 changes: 16 additions & 12 deletions src/lib/grandExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interface CreateListingArgs {
}

function validateNumber(num: number) {
if (num < 0 || isNaN(num) || !Number.isInteger(num) || num > Number.MAX_SAFE_INTEGER) {
if (num < 0 || isNaN(num) || !Number.isInteger(num) || num >= Number.MAX_SAFE_INTEGER) {
throw new Error(`Invalid number: ${num}.`);
}
}
Expand Down Expand Up @@ -780,17 +780,21 @@ ${type} ${toKMB(quantity)} ${item.name} for ${toKMB(price)} each, for a total of
}

async tick() {
await this.queue.add(async () => {
if (this.isTicking) throw new Error('Already ticking.');
try {
await this._tick();
} catch (err: any) {
logError(err.message);
debugLog(err.message);
throw err;
} finally {
this.isTicking = false;
}
return new Promise<void>((resolve, reject) => {
this.queue.add(async () => {
if (this.isTicking) return reject(new Error('Already ticking.'));
this.isTicking = true;
try {
await this._tick();
} catch (err: any) {
logError(err.message);
debugLog(err.message);
return reject(err);
} finally {
this.isTicking = false;
resolve();
}
});
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/mahoji/commands/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ Both parties must click confirm to make the trade.`,
`${senderUser.mention} sold ${itemsSent} to ${recipientUser.mention} for ${itemsReceived}.`
);
if (itemsReceived.has('Coins')) {
addToGPTaxBalance(recipientUser.id, itemsReceived.amount('Coins'));
await addToGPTaxBalance(recipientUser.id, itemsReceived.amount('Coins'));
}
if (itemsSent.has('Coins')) {
addToGPTaxBalance(senderUser.id, itemsSent.amount('Coins'));
await addToGPTaxBalance(senderUser.id, itemsSent.amount('Coins'));
}

return `${discrimName(senderAPIUser)} sold ${itemsSent} to ${discrimName(
Expand Down
22 changes: 16 additions & 6 deletions src/scripts/integration-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,29 @@ import { sleep } from 'e';
async function main() {
try {
execSync('docker compose up -d --wait', { stdio: 'inherit' });

console.log('Waiting...');
await sleep(2000);

execSync('dotenv -e .env.example -- prisma db push --schema="./prisma/schema.prisma"', { stdio: 'inherit' });
execSync('dotenv -e .env.example -- prisma db push --schema="./prisma/robochimp.prisma"', { stdio: 'inherit' });
console.log('Starting...');
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' });
execSync('yarn prebuild:scripts', { stdio: 'inherit' });
execSync('yarn build:esbuild', { stdio: 'inherit' });

execSync('vitest run --coverage --config vitest.integration.config.ts', {
stdio: 'inherit'
});
let runs = 1;
for (let i = 0; i < runs; i++) {
execSync('vitest run --config vitest.integration.config.ts', {
stdio: 'inherit',
encoding: 'utf-8'
});
console.log(`Finished run ${i + 1}/${runs}`);
}
} catch (err) {
throw new Error(`Failed to run integration tests: ${err}`);
throw new Error(err as any);
} finally {
await sleep(5000);
console.log('Shutting down containers...');
execSync('docker-compose down', { stdio: 'inherit' });
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/tasks/minions/monsterActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,6 @@ export const monsterTask: MinionTask = {
previousCL
});

handleTripFinish(user, channelID, str, image?.file.attachment, data, itemsAdded, messages);
return handleTripFinish(user, channelID, str, image?.file.attachment, data, itemsAdded, messages);
}
};
8 changes: 3 additions & 5 deletions tests/integration/MUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ItemBank } from 'oldschooljs/dist/meta/types';
import { convertLVLtoXP } from 'oldschooljs/dist/util';
import { describe, expect, test } from 'vitest';

import { prisma } from '../../src/lib/settings/prisma';
import { SkillsEnum } from '../../src/lib/skilling/types';
import { assert } from '../../src/lib/util/logError';
import { mahojiUsersSettingsFetch } from '../../src/mahoji/mahojiSettings';
Expand Down Expand Up @@ -88,16 +87,15 @@ describe('MUser', () => {
});

test('Should add XP', async () => {
const userId = '123456789';
const user = await mUserFetch(userId);
const user = await createTestUser();
expect(user.skillsAsLevels.agility).toEqual(1);
const result = await user.addXP({ skillName: SkillsEnum.Agility, amount: 1000 });
expect(user.skillsAsLevels.agility).toEqual(9);
expect(result).toEqual(`You received 1,000 <:agility:630911040355565568> XP
**Congratulations! Your Agility level is now 9** 🎉`);
const xpAdded = await prisma.xPGain.findMany({
const xpAdded = await global.prisma!.xPGain.findMany({
where: {
user_id: BigInt(userId),
user_id: BigInt(user.id),
skill: 'agility',
xp: 1000
}
Expand Down
9 changes: 5 additions & 4 deletions tests/integration/commands/gearPresets.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { randInt } from 'e';
import { describe, expect, test, vi } from 'vitest';

import { prisma } from '../../../src/lib/settings/prisma';
import itemID from '../../../src/lib/util/itemID';
import { gearPresetsCommand } from '../../../src/mahoji/commands/gearpresets';
import { createTestUser } from '../util';
Expand Down Expand Up @@ -29,7 +28,7 @@ describe('Gear Presets Command', async () => {
}
});

const gpResult = await prisma.gearPreset.findFirst({ where: { user_id: user.id, name: 'test2h' } });
const gpResult = await global.prisma!.gearPreset.findFirst({ where: { user_id: user.id, name: 'test2h' } });
// Verify row exists:
expect(gpResult).toBeTruthy();
if (!gpResult) return false;
Expand All @@ -54,7 +53,7 @@ describe('Gear Presets Command', async () => {
}
});

const gpResult = await prisma.gearPreset.findFirst({ where: { user_id: user.id, name: 'testedit' } });
const gpResult = await global.prisma!.gearPreset.findFirst({ where: { user_id: user.id, name: 'testedit' } });
// Verify row exists:
expect(gpResult).toBeTruthy();
if (!gpResult) return false;
Expand All @@ -63,7 +62,9 @@ describe('Gear Presets Command', async () => {
edit: { gear_preset: 'TestEdit', weapon: 'Ghrazi rapier', feet: 'None' }
});

const gpEditResult = await prisma.gearPreset.findFirst({ where: { user_id: user.id, name: 'testedit' } });
const gpEditResult = await global.prisma!.gearPreset.findFirst({
where: { user_id: user.id, name: 'testedit' }
});

// Verify row found:
expect(gpEditResult).toBeTruthy();
Expand Down
56 changes: 28 additions & 28 deletions tests/integration/commands/ironman.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { miniID, randomSnowflake } from '@oldschoolgg/toolkit';
import { miniID } from '@oldschoolgg/toolkit';
import { Prisma } from '@prisma/client';
import { Time } from 'e';
import { Bank } from 'oldschooljs';
import { describe, expect, test } from 'vitest';

import { prisma } from '../../../src/lib/settings/prisma';
import { ironmanCommand } from '../../../src/mahoji/lib/abstracted_commands/ironmanCommand';
import { mockedId } from '../util';

describe('Ironman Command', () => {
async function createUserWithEverything(userId: string, userData: Partial<Prisma.UserCreateInput> = {}) {
await prisma.user.create({
await global.prisma!.user.create({
data: { id: userId, skills_agility: 100_000_000, skills_attack: 100_000_000, ...userData }
});
await prisma.newUser.create({ data: { id: userId } });
const activity = await prisma.activity.create({
await global.prisma!.newUser.create({ data: { id: userId } });
const activity = await global.prisma!.activity.create({
data: {
user_id: BigInt(userId),
start_date: new Date(),
Expand All @@ -27,11 +27,11 @@ describe('Ironman Command', () => {
}
});
await Promise.all([
prisma.botItemSell.create({ data: { user_id: userId, item_id: 1, quantity: 1, gp_received: 1 } }),
prisma.pinnedTrip.create({
global.prisma!.botItemSell.create({ data: { user_id: userId, item_id: 1, quantity: 1, gp_received: 1 } }),
global.prisma!.pinnedTrip.create({
data: { user_id: userId, id: miniID(10), activity_id: activity.id, activity_type: 'Mining' }
}),
prisma.farmedCrop.create({
global.prisma!.farmedCrop.create({
data: {
user_id: userId,
date_planted: new Date(),
Expand All @@ -41,7 +41,7 @@ describe('Ironman Command', () => {
paid_for_protection: false
}
}),
prisma.slayerTask.create({
global.prisma!.slayerTask.create({
data: {
user_id: userId,
monster_id: 1,
Expand All @@ -51,12 +51,12 @@ describe('Ironman Command', () => {
skipped: false
}
}),
prisma.playerOwnedHouse.create({ data: { user_id: userId } }),
prisma.minigame.create({ data: { user_id: userId } }),
prisma.xPGain.create({ data: { user_id: BigInt(userId), skill: 'agility', xp: 1 } }),
prisma.stashUnit.create({ data: { user_id: BigInt(userId), stash_id: 1, has_built: false } }),
prisma.userStats.create({ data: { user_id: BigInt(userId) } }),
prisma.historicalData.create({
global.prisma!.playerOwnedHouse.create({ data: { user_id: userId } }),
global.prisma!.minigame.create({ data: { user_id: userId } }),
global.prisma!.xPGain.create({ data: { user_id: BigInt(userId), skill: 'agility', xp: 1 } }),
global.prisma!.stashUnit.create({ data: { user_id: BigInt(userId), stash_id: 1, has_built: false } }),
global.prisma!.userStats.create({ data: { user_id: BigInt(userId) } }),
global.prisma!.historicalData.create({
data: {
user_id: userId,
GP: 100_000,
Expand All @@ -70,7 +70,7 @@ describe('Ironman Command', () => {
}

test('Should reset everything', async () => {
const userId = randomSnowflake();
const userId = mockedId();
await createUserWithEverything(userId);

const result = await ironmanCommand(await mUserFetch(userId), null, false);
Expand All @@ -83,23 +83,23 @@ describe('Ironman Command', () => {
expect(user.bank.equals(new Bank())).toEqual(true);
expect(user.cl.equals(new Bank())).toEqual(true);

expect(await prisma.activity.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await prisma.botItemSell.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.pinnedTrip.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.farmedCrop.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.slayerTask.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.playerOwnedHouse.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.minigame.count({ where: { user_id: userId } })).toEqual(0);
expect(await prisma.xPGain.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await prisma.stashUnit.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await prisma.historicalData.count({ where: { user_id: userId } })).toEqual(0);
const userStats = await prisma.userStats.findFirst({ where: { user_id: BigInt(userId) } });
expect(await global.prisma!.activity.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await global.prisma!.botItemSell.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.pinnedTrip.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.farmedCrop.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.slayerTask.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.playerOwnedHouse.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.minigame.count({ where: { user_id: userId } })).toEqual(0);
expect(await global.prisma!.xPGain.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await global.prisma!.stashUnit.count({ where: { user_id: BigInt(userId) } })).toEqual(0);
expect(await global.prisma!.historicalData.count({ where: { user_id: userId } })).toEqual(0);
const userStats = await global.prisma!.userStats.findFirst({ where: { user_id: BigInt(userId) } });
expect(userStats?.cl_array).toEqual(undefined);
expect(userStats?.cl_array_length).toEqual(undefined);
});

test('Should de-iron', async () => {
const userId = randomSnowflake();
const userId = mockedId();
await createUserWithEverything(userId, { minion_ironman: true });
const initialUser = await mUserFetch(userId);
expect(initialUser.isIronman).toEqual(true);
Expand Down
Loading

0 comments on commit a4f5251

Please sign in to comment.