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

Fix tests #5715

Merged
merged 15 commits into from
Feb 25, 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
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 @@ -68,7 +68,7 @@
TopGlobalCL: '1072426869028294747'
};

export const enum Emoji {

Check warning on line 71 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'Emoji' is already declared in the upper scope on line 71 column 19

Check warning on line 71 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'Emoji' is already declared in the upper scope on line 71 column 19
MoneyBag = '<:MoneyBag:493286312854683654>',
OSBot = '<:OSBot:601768469905801226>',
Joy = '😂',
Expand Down Expand Up @@ -170,14 +170,14 @@
BronzeTrophy = '<:BronzeTrophy:1152881057788592188>'
}

export enum ActivityGroup {

Check warning on line 173 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'ActivityGroup' is already declared in the upper scope on line 173 column 13

Check warning on line 173 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'ActivityGroup' is already declared in the upper scope on line 173 column 13
Skilling = 'Skilling',
Clue = 'Clue',
Monster = 'Monster',
Minigame = 'Minigame'
}

export const enum Events {

Check warning on line 180 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'Events' is already declared in the upper scope on line 180 column 19

Check warning on line 180 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'Events' is already declared in the upper scope on line 180 column 19
Error = 'error',
Log = 'log',
Verbose = 'verbose',
Expand All @@ -190,7 +190,7 @@

export const COINS_ID = 995;

export const enum PerkTier {

Check warning on line 193 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'PerkTier' is already declared in the upper scope on line 193 column 19

Check warning on line 193 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'PerkTier' is already declared in the upper scope on line 193 column 19
/**
* Boosters
*/
Expand Down Expand Up @@ -221,7 +221,7 @@
Seven = 7
}

export enum BitField {

Check warning on line 224 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'BitField' is already declared in the upper scope on line 224 column 13

Check warning on line 224 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'BitField' is already declared in the upper scope on line 224 column 13
IsPatronTier1 = 2,
IsPatronTier2 = 3,
IsPatronTier3 = 4,
Expand Down Expand Up @@ -359,7 +359,7 @@
}
} as const;

export const enum PatronTierID {

Check warning on line 362 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'PatronTierID' is already declared in the upper scope on line 362 column 19

Check warning on line 362 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'PatronTierID' is already declared in the upper scope on line 362 column 19
One = '4608201',
Two = '4608226',
Three = '4720356',
Expand Down Expand Up @@ -550,7 +550,7 @@
"Osmumten's fang"
]);

export enum PeakTier {

Check warning on line 553 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

'PeakTier' is already declared in the upper scope on line 553 column 13

Check warning on line 553 in src/lib/constants.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

'PeakTier' is already declared in the upper scope on line 553 column 13
High = 'high',
Medium = 'medium',
Low = 'low'
Expand All @@ -568,7 +568,7 @@
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 @@
}

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 @@ -177,7 +177,7 @@
let maxPossible = 0;
for (const boost of this.config.slots.slotBoosts) {
maxPossible += boost.amount;
if (boost.has(user, robochimpUser)) {

Check warning on line 180 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

Unexpected value in conditional. A boolean expression is required

Check warning on line 180 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

Unexpected value in conditional. A boolean expression is required
slots += boost.amount;
} else {
doesntHaveNames.push(boost.name);
Expand Down Expand Up @@ -281,12 +281,12 @@
return { error: 'Invalid item.' };
}

if (!price || price <= 0 || isNaN(price) || !Number.isInteger(price) || price > this.config.maxPricePerItem) {

Check warning on line 284 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

Unexpected number value in conditional. An explicit zero/NaN check is required

Check warning on line 284 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

Unexpected number value in conditional. An explicit zero/NaN check is required
return {
error: `Invalid price, the price must be a number between 1 and ${toKMB(this.config.maxPricePerItem)}.`
};
}
if (!quantity || quantity <= 0 || isNaN(quantity) || !Number.isInteger(quantity) || quantity > 5_000_000) {

Check warning on line 289 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v18.12.0 - ubuntu-latest

Unexpected number value in conditional. An explicit zero/NaN check is required

Check warning on line 289 in src/lib/grandExchange.ts

View workflow job for this annotation

GitHub Actions / Node v20 - ubuntu-latest

Unexpected number value in conditional. An explicit zero/NaN check is required
return { error: 'Invalid quantity, the quantity must be a number between 1 and 5m.' };
}

Expand Down Expand Up @@ -780,17 +780,21 @@
}

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
Loading