diff --git a/.env.test b/.env.test new file mode 100644 index 0000000000..bca1e62bd3 --- /dev/null +++ b/.env.test @@ -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 \ No newline at end of file diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml index 88bfb70b9f..117c536840 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -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 }} @@ -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 diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index bdfa62cdbc..9bb15e4a59 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index eceff3a3a8..925d2b42db 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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: @@ -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: diff --git a/src/lib/constants.ts b/src/lib/constants.ts index 50b28b0fac..f8ed32230d 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -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, diff --git a/src/lib/grandExchange.ts b/src/lib/grandExchange.ts index 3b4789fadc..418df03f1e 100644 --- a/src/lib/grandExchange.ts +++ b/src/lib/grandExchange.ts @@ -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}.`); } } @@ -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((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(); + } + }); }); } diff --git a/src/mahoji/commands/trade.ts b/src/mahoji/commands/trade.ts index caf5d2c3a8..ff2f531991 100644 --- a/src/mahoji/commands/trade.ts +++ b/src/mahoji/commands/trade.ts @@ -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( diff --git a/src/scripts/integration-tests.ts b/src/scripts/integration-tests.ts index d1f0202476..6a114b8ef7 100644 --- a/src/scripts/integration-tests.ts +++ b/src/scripts/integration-tests.ts @@ -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' }); } } diff --git a/src/tasks/minions/monsterActivity.ts b/src/tasks/minions/monsterActivity.ts index 3906a9ead5..3537fc66d9 100644 --- a/src/tasks/minions/monsterActivity.ts +++ b/src/tasks/minions/monsterActivity.ts @@ -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); } }; diff --git a/tests/integration/MUser.test.ts b/tests/integration/MUser.test.ts index f310434226..c5cf9afc1c 100644 --- a/tests/integration/MUser.test.ts +++ b/tests/integration/MUser.test.ts @@ -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'; @@ -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 } diff --git a/tests/integration/commands/gearPresets.test.ts b/tests/integration/commands/gearPresets.test.ts index 4d514ae44e..a7cb6fd33e 100644 --- a/tests/integration/commands/gearPresets.test.ts +++ b/tests/integration/commands/gearPresets.test.ts @@ -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'; @@ -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; @@ -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; @@ -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(); diff --git a/tests/integration/commands/ironman.test.ts b/tests/integration/commands/ironman.test.ts index 2fc71241f1..4ebac861fa 100644 --- a/tests/integration/commands/ironman.test.ts +++ b/tests/integration/commands/ironman.test.ts @@ -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 = {}) { - 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(), @@ -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(), @@ -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, @@ -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, @@ -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); @@ -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); diff --git a/tests/integration/grandExchange.test.ts b/tests/integration/grandExchange.test.ts index 4ce4b3f56d..3a64a6d6ea 100644 --- a/tests/integration/grandExchange.test.ts +++ b/tests/integration/grandExchange.test.ts @@ -1,10 +1,12 @@ -import { calcPercentOfNum, randArrItem, randInt, Time } from 'e'; +import 'source-map-support/register'; + +import { calcPercentOfNum, randArrItem, randInt, shuffleArr, Time } from 'e'; import { Bank } from 'oldschooljs'; +import PQueue from 'p-queue'; import { describe, expect, test } from 'vitest'; import { usernameCache } from '../../src/lib/constants'; import { GrandExchange } from '../../src/lib/grandExchange'; -import { prisma } from '../../src/lib/settings/prisma'; import { assert } from '../../src/lib/util'; import resolveItems from '../../src/lib/util/resolveItems'; import { geCommand } from '../../src/mahoji/commands/ge'; @@ -37,7 +39,7 @@ const sampleBank = new Bank() async function cancelAllListings(user: TestUser) { const results: string[] = []; - const activeListings = await prisma.gEListing.findMany({ + const activeListings = await global.prisma!.gEListing.findMany({ where: { user_id: user.id } @@ -58,19 +60,19 @@ async function cancelAllListings(user: TestUser) { describe('Grand Exchange', async () => { const itemPool = resolveItems(['Egg', 'Trout', 'Coal']); GrandExchange.calculateSlotsOfUser = async () => ({ slots: 500 } as any); + await mockClient(); test( 'Fuzz', async () => { assert(randInt(1, 100_000) !== randInt(1, 100_000)); - await mockClient(); await GrandExchange.totalReset(); await GrandExchange.init(); const currentOwnedBank = await GrandExchange.fetchOwnedBank(); expect(currentOwnedBank.toString()).toEqual(new Bank().toString()); - let amountOfUsers = randInt(300, 400); + let amountOfUsers = randInt(433, 533); const totalExpectedBank = sampleBank.clone().multiply(amountOfUsers); let users: TestUser[] = []; @@ -80,22 +82,31 @@ describe('Grand Exchange', async () => { await user.addItemsToBank({ items: sampleBank }); users.push(user); } - - for (let i = 0; i < users.length; i++) { - for (const item of itemPool) { - const method = randArrItem(['buy', 'sell']); - let quantity = randArrItem(quantities); - let price = randArrItem(prices); - users[i].runCommand(geCommand, { - [method]: { - item, - quantity, - price - } - }); - } + console.log(`Finished initializing ${amountOfUsers} users`); + + const commandPromises = new PQueue({ concurrency: 10 }); + for (const user of shuffleArr(users)) { + const method = randArrItem(['buy', 'sell']); + let quantity = randArrItem(quantities); + let price = randArrItem(prices); + commandPromises.add(async () => { + for (const item of itemPool) { + await user.runCommand(geCommand, { + [method]: { + item, + quantity, + price + } + }); + } + }); } + await commandPromises.onEmpty(); + await GrandExchange.queue.onEmpty(); + + console.log('Finished running all commands'); + for (let i = 0; i < 100; i++) { await GrandExchange.tick(); await Promise.all([ @@ -103,6 +114,7 @@ describe('Grand Exchange', async () => { GrandExchange.extensiveVerification() ]); } + console.log('Finished ticking 100 times'); const testBank = new Bank(); const cancelPromises = []; @@ -111,6 +123,8 @@ describe('Grand Exchange', async () => { } await Promise.all(cancelPromises); + console.log('Finished cancelling'); + await Promise.all(users.map(u => u.sync())); for (const user of users) { @@ -125,7 +139,7 @@ describe('Grand Exchange', async () => { expect(data.taxBank).toBeGreaterThan(0); expect(data.totalTax).toBeGreaterThan(0); - const totalTaxed = await prisma.gETransaction.aggregate({ + const totalTaxed = await global.prisma!.gETransaction.aggregate({ _sum: { total_tax_paid: true } @@ -141,7 +155,7 @@ describe('Grand Exchange', async () => { assert(GrandExchange.queue.size === 0, 'Queue should be empty'); }, { - repeats: 2, + repeats: 1, timeout: Time.Minute * 5 } ); diff --git a/tests/integration/migrateUser.test.ts b/tests/integration/migrateUser.test.ts index bc4395a53d..0cb2754def 100644 --- a/tests/integration/migrateUser.test.ts +++ b/tests/integration/migrateUser.test.ts @@ -1,4 +1,3 @@ -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { Activity, activity_type_enum, @@ -32,7 +31,6 @@ import { GearSetupType, UserFullGearSetup } from '../../src/lib/gear/types'; import { GrandExchange } from '../../src/lib/grandExchange'; import { trackLoot } from '../../src/lib/lootTrack'; import { incrementMinigameScore, MinigameName } from '../../src/lib/settings/minigames'; -import { prisma } from '../../src/lib/settings/prisma'; import { SkillsEnum } from '../../src/lib/skilling/types'; import { slayerMasters } from '../../src/lib/slayer/slayerMasters'; import { assignNewSlayerTask } from '../../src/lib/slayer/slayerUtil'; @@ -59,7 +57,7 @@ import { syncNewUserUsername } from '../../src/mahoji/lib/preCommand'; import { OSBMahojiCommand } from '../../src/mahoji/lib/util'; import { updateClientGPTrackSetting, userStatsUpdate } from '../../src/mahoji/mahojiSettings'; import { calculateResultOfLMSGames, getUsersLMSStats } from '../../src/tasks/minions/minigames/lmsActivity'; -import { createTestUser, mockClient, TestUser } from './util'; +import { createTestUser, mockClient, mockedId, TestUser } from './util'; import { BotItemSell, GEListing, StashUnit } from '.prisma/client'; interface TestCommand { @@ -119,7 +117,7 @@ class UserData { } else { await this.mUser.sync(); } - const newUser = await prisma.newUser.findFirst({ where: { id: this.id }, select: { username: true } }); + const newUser = await global.prisma!.newUser.findFirst({ where: { id: this.id }, select: { username: true } }); if (newUser) this.username = newUser.username; this.bank = new Bank(this.mUser.bank); @@ -133,113 +131,122 @@ class UserData { }); if (robochimpUser) this.githubId = robochimpUser.github_id; - const stashUnits = await prisma.stashUnit.findMany({ + const stashUnits = await global.prisma!.stashUnit.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { stash_id: 'asc' } }); if (stashUnits.length > 0) this.stashUnits = stashUnits; - const gearPresets = await prisma.gearPreset.findMany({ + const gearPresets = await global.prisma!.gearPreset.findMany({ where: { user_id: this.id }, orderBy: { name: 'asc' } }); if (gearPresets.length > 0) this.gearPresets = gearPresets; - const activities = await prisma.activity.findMany({ + const activities = await global.prisma!.activity.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { start_date: 'asc' } }); if (activities.length > 0) this.activities = activities; - const slayerTasks = await prisma.slayerTask.findMany({ where: { user_id: this.id }, orderBy: { id: 'asc' } }); + const slayerTasks = await global.prisma!.slayerTask.findMany({ + where: { user_id: this.id }, + orderBy: { id: 'asc' } + }); if (slayerTasks.length > 0) this.slayerTasks = slayerTasks; - const poh = await prisma.playerOwnedHouse.findFirst({ where: { user_id: this.id } }); + const poh = await global.prisma!.playerOwnedHouse.findFirst({ where: { user_id: this.id } }); if (poh) this.poh = poh; - const giveaways = await prisma.giveaway.findMany({ where: { user_id: this.id }, orderBy: { id: 'asc' } }); + const giveaways = await global.prisma!.giveaway.findMany({ + where: { user_id: this.id }, + orderBy: { id: 'asc' } + }); if (giveaways.length > 0) this.giveaways = giveaways; - const farmedCrops = await prisma.farmedCrop.findMany({ where: { user_id: this.id }, orderBy: { id: 'asc' } }); + const farmedCrops = await global.prisma!.farmedCrop.findMany({ + where: { user_id: this.id }, + orderBy: { id: 'asc' } + }); if (farmedCrops.length > 0) this.farmedCrops = farmedCrops; - const minigames = await prisma.minigame.findFirst({ where: { user_id: this.id } }); + const minigames = await global.prisma!.minigame.findFirst({ where: { user_id: this.id } }); if (minigames) this.minigames = minigames; - const pinnedTrips = await prisma.pinnedTrip.findMany({ + const pinnedTrips = await global.prisma!.pinnedTrip.findMany({ where: { user_id: this.id }, orderBy: { activity_id: 'asc' } }); if (pinnedTrips.length > 0) this.pinnedTrips = pinnedTrips; - const lms = await prisma.lastManStandingGame.findMany({ + const lms = await global.prisma!.lastManStandingGame.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { id: 'asc' } }); if (lms.length > 0) this.lms = lms; - const lootTrack = await prisma.lootTrack.findMany({ + const lootTrack = await global.prisma!.lootTrack.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { id: 'asc' } }); if (lootTrack.length > 0) this.lootTrack = lootTrack; - const botItemSell = await prisma.botItemSell.findMany({ + const botItemSell = await global.prisma!.botItemSell.findMany({ where: { user_id: this.id }, orderBy: { item_id: 'asc' } }); if (botItemSell.length > 0) this.botItemSell = botItemSell; - const buyCommandTx = await prisma.buyCommandTransaction.findMany({ + const buyCommandTx = await global.prisma!.buyCommandTransaction.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { id: 'asc' } }); if (buyCommandTx.length > 0) this.buyCommandTx = buyCommandTx; - const reclaimableItems = await prisma.reclaimableItem.findMany({ + const reclaimableItems = await global.prisma!.reclaimableItem.findMany({ where: { user_id: this.id }, orderBy: { key: 'asc' } }); if (reclaimableItems.length > 0) this.reclaimableItems = reclaimableItems; - const xpGains = await prisma.xPGain.findMany({ + const xpGains = await global.prisma!.xPGain.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { id: 'asc' } }); if (xpGains.length > 0) this.xpGains = xpGains; - const economyTx = await prisma.economyTransaction.findMany({ + const economyTx = await global.prisma!.economyTransaction.findMany({ where: { OR: [{ sender: BigInt(this.id) }, { recipient: BigInt(this.id) }] }, orderBy: { date: 'asc' } }); if (economyTx.length > 0) this.economyTx = economyTx; - const bingoParticipant = await prisma.bingoParticipant.findMany({ + const bingoParticipant = await global.prisma!.bingoParticipant.findMany({ where: { user_id: this.id }, orderBy: { bingo_id: 'asc' } }); if (bingoParticipant.length > 0) this.bingoParticipant = bingoParticipant; - const userStats = await prisma.userStats.findFirst({ where: { user_id: BigInt(this.id) } }); + const userStats = await global.prisma!.userStats.findFirst({ where: { user_id: BigInt(this.id) } }); if (userStats) this.userStats = userStats; - const bingos = await prisma.bingo.findMany({ where: { creator_id: this.id }, orderBy: { id: 'asc' } }); + const bingos = await global.prisma!.bingo.findMany({ where: { creator_id: this.id }, orderBy: { id: 'asc' } }); if (bingos.length > 0) this.bingos = bingos; - const historicalData = await prisma.historicalData.findMany({ + const historicalData = await global.prisma!.historicalData.findMany({ where: { user_id: this.id }, orderBy: { date: 'asc' } }); if (historicalData.length > 0) this.historicalData = historicalData; - const commandUsage = await prisma.commandUsage.findMany({ + const commandUsage = await global.prisma!.commandUsage.findMany({ where: { user_id: BigInt(this.id) }, orderBy: { date: 'asc' } }); if (commandUsage.length > 0) this.commandUsage = commandUsage; - const geListings = await prisma.gEListing.findMany({ + const geListings = await global.prisma!.gEListing.findMany({ where: { user_id: this.id }, orderBy: { id: 'asc' } }); @@ -630,14 +637,14 @@ const allTableCommands: TestCommand[] = [ channel_id: 11_111_111_111n, duration }; - await prisma.activity.create({ data }); + await global.prisma!.activity.create({ data }); } } }, { name: 'Group Activity', cmd: async user => { - const users = shuffleArr([user.id, randomSnowflake(), randomSnowflake()]); + const users = shuffleArr([user.id, mockedId(), mockedId()]); const data = { leader: user.id, users, @@ -649,7 +656,7 @@ const allTableCommands: TestCommand[] = [ const duration = 30 * 60 * 1000; const start_date = new Date(); const finish_date = new Date(start_date.getTime() + duration); - await prisma.activity.create({ + await global.prisma!.activity.create({ data: { type: 'TombsOfAmascut', user_id: BigInt(user.id), @@ -695,7 +702,7 @@ const allTableCommands: TestCommand[] = [ 'Fishing bait' ]; const lootBank = new Bank().add(randArrItem(randomBuyItems), randInt(10, 999)); - await prisma.buyCommandTransaction.create({ + await global.prisma!.buyCommandTransaction.create({ data: { user_id: BigInt(user.id), cost_gp: randInt(10_000, 10_000_000), @@ -710,7 +717,7 @@ const allTableCommands: TestCommand[] = [ cmd: async user => { const randomItems = ['Cannonball', 'Blood rune', 'Twisted bow', 'Kodai wand', 'Bandos tassets']; const recvBank = new Bank().add(randArrItem(randomItems), randInt(10, 99)).add(randArrItem(randomItems)); - const partner = await createTestUser(randomSnowflake(), recvBank); + const partner = await createTestUser(recvBank); await tradePlayerItems(user, partner, undefined, recvBank); } }, @@ -719,7 +726,7 @@ const allTableCommands: TestCommand[] = [ cmd: async user => { const randomItems = ['Feather', 'Soul rune', 'Dragon claws', 'Ghrazi rapier', 'Bandos boots']; const recvBank = new Bank().add(randArrItem(randomItems), randInt(10, 99)).add(randArrItem(randomItems)); - const partner = await createTestUser(randomSnowflake(), recvBank); + const partner = await createTestUser(recvBank); await tradePlayerItems(partner, user, recvBank, undefined); } }, @@ -768,7 +775,7 @@ const allTableCommands: TestCommand[] = [ { name: 'Create giveaway', cmd: async user => { - await prisma.giveaway.create({ + await global.prisma!.giveaway.create({ data: { id: randInt(1_000_000, 9_999_999), channel_id: '1111111111111', @@ -794,7 +801,7 @@ const allTableCommands: TestCommand[] = [ name: 'Farmed crop', cmd: async user => { const plant = findPlant('Potato')!; - await prisma.farmedCrop.create({ + await global.prisma!.farmedCrop.create({ data: { user_id: user.id, date_planted: new Date(), @@ -824,7 +831,7 @@ const allTableCommands: TestCommand[] = [ { name: 'Pin Trip', cmd: async user => { - const result = await prisma.activity.findFirst({ + const result = await global.prisma!.activity.findFirst({ where: { user_id: BigInt(user.id) }, select: { id: true } }); @@ -841,7 +848,7 @@ const allTableCommands: TestCommand[] = [ const result = calculateResultOfLMSGames(quantity, lmsStats); - await prisma.lastManStandingGame.createMany({ + await global.prisma!.lastManStandingGame.createMany({ data: result.map(i => ({ ...i, user_id: BigInt(user.id), points: undefined })) }); const points = sumArr(result.map(i => i.points)); @@ -943,7 +950,7 @@ const allTableCommands: TestCommand[] = [ }), {} ), - prisma.botItemSell.createMany({ data: botItemSellData }) + global.prisma!.botItemSell.createMany({ data: botItemSellData }) ]); } }, @@ -978,21 +985,21 @@ const allTableCommands: TestCommand[] = [ creator_id: user.id, guild_id: '342983479501389826' }; - await prisma.bingo.create({ data: createOptions }); + await global.prisma!.bingo.create({ data: createOptions }); } }, { name: 'Bingo Participant', cmd: async user => { - const activeBingos = await prisma.bingo.findMany({ select: { id: true } }); + const activeBingos = await global.prisma!.bingo.findMany({ select: { id: true } }); if (activeBingos.length === 0) return; const myBingo = randArrItem(activeBingos).id; // Check if we're in this bingo already: - const existingTeam = await prisma.bingoParticipant.findFirst({ + const existingTeam = await global.prisma!.bingoParticipant.findFirst({ where: { user_id: user.id, bingo_id: myBingo } }); if (existingTeam) return; - await prisma.bingoTeam.create({ + await global.prisma!.bingoTeam.create({ data: { bingo_id: myBingo, users: { @@ -1029,7 +1036,7 @@ const allTableCommands: TestCommand[] = [ { name: 'Historical data', cmd: async user => { - await prisma.historicalData.create({ + await global.prisma!.historicalData.create({ data: { user_id: user.id, GP: 100_000, @@ -1045,7 +1052,7 @@ const allTableCommands: TestCommand[] = [ name: 'Command usage', cmd: async user => { const randCommands = ['minion', 'runecraft', 'chop', 'mine', 'buy']; - await prisma.commandUsage.create({ + await global.prisma!.commandUsage.create({ data: { user_id: BigInt(user.id), channel_id: 1_111_111_111n, @@ -1071,7 +1078,7 @@ const allTableCommands: TestCommand[] = [ } const itemId = randInt(10_000, 25_000); key += `${itemId}`; - await prisma.reclaimableItem.create({ + await global.prisma!.reclaimableItem.create({ data: { user_id: user.id, key, @@ -1154,6 +1161,7 @@ async function buildBaseUser(userId: string) { .add('Ghrazi rapier'); const userData: Partial = { + id: userId, skills_runecraft: 13_034_431, skills_woodcutting: 13_034_431, skills_mining: 13_034_431, @@ -1168,7 +1176,7 @@ async function buildBaseUser(userId: string) { kourend_favour: { Hosidius: 100, Arceuus: 0, Shayzien: 0, Lovakengj: 0 }, GP: 100_000_000 }; - const user = await createTestUser(userId, startBank, userData); + const user = await createTestUser(startBank, userData); return user; } describe('migrate user test', async () => { @@ -1208,10 +1216,10 @@ describe('migrate user test', async () => { await GrandExchange.init(); test('test migrating existing user to target with no records', async () => { - const sourceUser = await buildBaseUser(randomSnowflake()); + const sourceUser = await buildBaseUser(mockedId()); await runAllTestCommandsOnUser(sourceUser); - const destUserId = randomSnowflake(); + const destUserId = mockedId(); const sourceData = new UserData(sourceUser); await sourceData.sync(); @@ -1229,8 +1237,8 @@ describe('migrate user test', async () => { }); test('test migrating full user on top of full profile', async () => { - const sourceUser = await buildBaseUser(randomSnowflake()); - const destUser = await buildBaseUser(randomSnowflake()); + const sourceUser = await buildBaseUser(mockedId()); + const destUser = await buildBaseUser(mockedId()); await runAllTestCommandsOnUser(sourceUser); await runAllTestCommandsOnUser(destUser); @@ -1271,8 +1279,8 @@ describe('migrate user test', async () => { test( 'test migrating random user on top of empty profile', async () => { - const sourceUser = await buildBaseUser(randomSnowflake()); - const destUserId = randomSnowflake(); + const sourceUser = await buildBaseUser(mockedId()); + const destUserId = mockedId(); const sourceRolls = randInt(6, 11); const cmdHistory = await runRandomTestCommandsOnUser(sourceUser, sourceRolls); @@ -1293,14 +1301,14 @@ describe('migrate user test', async () => { expect(compareResult.result).toBe(true); }, - { repeats: 2 } + { repeats: 1 } ); test( 'test migrating random user on top of random profile', async () => { - const sourceUser = await buildBaseUser(randomSnowflake()); - const destUser = await buildBaseUser(randomSnowflake()); + const sourceUser = await buildBaseUser(mockedId()); + const destUser = await buildBaseUser(mockedId()); const sourceRolls = randInt(5, 12); const destRolls = randInt(5, 12); @@ -1322,14 +1330,14 @@ describe('migrate user test', async () => { expect(compareResult.result).toBe(true); }, - { repeats: 2 } + { repeats: 1 } ); test( 'test migrating random user on top of full profile', async () => { - const sourceUser = await buildBaseUser(randomSnowflake()); - const destUser = await buildBaseUser(randomSnowflake()); + const sourceUser = await buildBaseUser(mockedId()); + const destUser = await buildBaseUser(mockedId()); const cmdHistory = await runRandomTestCommandsOnUser(sourceUser); await runAllTestCommandsOnUser(destUser); @@ -1348,6 +1356,6 @@ describe('migrate user test', async () => { expect(compareResult.result).toBe(true); }, - { repeats: 2 } + { repeats: 1 } ); }); diff --git a/tests/integration/misc.test.ts b/tests/integration/misc.test.ts index d28e8cd3c3..0b33f7f21c 100644 --- a/tests/integration/misc.test.ts +++ b/tests/integration/misc.test.ts @@ -1,7 +1,6 @@ import { describe, expect, test } from 'vitest'; import { analyticsTick } from '../../src/lib/analytics'; -import { prisma } from '../../src/lib/settings/prisma'; import { minionStatsEmbed } from '../../src/lib/util/minionStatsEmbed'; import { mockClient } from './util'; @@ -12,6 +11,6 @@ describe('Integration Misc', () => { test('Analytics', async () => { await mockClient(); await analyticsTick(); - expect(await prisma.analytic.count()).toBeGreaterThanOrEqual(1); + expect(await global.prisma!.analytic.count()).toBeGreaterThanOrEqual(1); }); }); diff --git a/tests/integration/monsterKilling.test.ts b/tests/integration/monsterKilling.test.ts index e745e88660..41e2d8d929 100644 --- a/tests/integration/monsterKilling.test.ts +++ b/tests/integration/monsterKilling.test.ts @@ -1,7 +1,6 @@ import { Bank } from 'oldschooljs'; import { expect, test } from 'vitest'; -import { prisma } from '../../src/lib/settings/prisma'; import { MonsterActivityTaskOptions } from '../../src/lib/types/minions'; import { killCommand } from '../../src/mahoji/commands/k'; import { createTestUser, mockClient } from './util'; @@ -22,7 +21,7 @@ test('Killing Men', async () => { expect(user.bank.amount('Shark')).toBeLessThan(1_000_000); expect( - await prisma.xPGain.count({ + await global.prisma!.xPGain.count({ where: { user_id: BigInt(user.id) } diff --git a/tests/integration/paymentConflict.test.ts b/tests/integration/paymentConflict.test.ts index fb0c1c0ba3..d44d5ba93e 100644 --- a/tests/integration/paymentConflict.test.ts +++ b/tests/integration/paymentConflict.test.ts @@ -1,4 +1,3 @@ -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { randArrItem, randInt, roll, Time } from 'e'; import { Bank } from 'oldschooljs'; import { describe, expect, test } from 'vitest'; @@ -10,7 +9,7 @@ describe('Payment conflicts', async () => { const payerCount = 50; const iterations = 100; const addChance = 3; - const repeats = 5; + const repeats = 1; const bigBank = new Bank().add('Cannonball', 4).add('Bones', 10_000); @@ -20,7 +19,7 @@ describe('Payment conflicts', async () => { await mockClient(); // Payee is currently the primary target of the test. - const userPayee = await createTestUser(randomSnowflake(), new Bank(bigBank), { GP: 1_000_000_000 }); + const userPayee = await createTestUser(new Bank(bigBank), { GP: 1_000_000_000 }); const payeeTarget = await globalClient.fetchUser(userPayee.id); @@ -28,7 +27,7 @@ describe('Payment conflicts', async () => { const payers: TestUser[] = []; for (let i = 0; i < payerCount; i++) { - payers.push(await createTestUser(randomSnowflake(), new Bank(), { GP: 1_000_000_000 })); + payers.push(await createTestUser(new Bank(), { GP: 1_000_000_000 })); } const promisePay = async () => { @@ -79,13 +78,13 @@ describe('Payment conflicts', async () => { async () => { await mockClient(); // May as well test for the Payer also, even though so far we're solid here. - const userPayer = await createTestUser(randomSnowflake(), new Bank(bigBank), { GP: 1_000_000_000 }); + const userPayer = await createTestUser(new Bank(bigBank), { GP: 1_000_000_000 }); const startingBallCount = userPayer.bank.amount('Cannonball'); const payees: TestUser[] = []; for (let i = 0; i < payerCount; i++) { - payees.push(await createTestUser(randomSnowflake(), new Bank(), { GP: 1_000_000_000 })); + payees.push(await createTestUser(new Bank(), { GP: 1_000_000_000 })); } const promisePay = async () => { diff --git a/tests/integration/rolesTask.test.ts b/tests/integration/rolesTask.test.ts index 931c17dde1..5ba57e19b2 100644 --- a/tests/integration/rolesTask.test.ts +++ b/tests/integration/rolesTask.test.ts @@ -1,14 +1,12 @@ -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { Time } from 'e'; import { Bank } from 'oldschooljs'; import { describe, expect, test } from 'vitest'; import { runRolesTask } from '../../src/lib/rolesTask'; import { MinigameName, Minigames } from '../../src/lib/settings/minigames'; -import { prisma } from '../../src/lib/settings/prisma'; import { cryptoRand } from '../../src/lib/util'; import { userStatsBankUpdate } from '../../src/mahoji/mahojiSettings'; -import { createTestUser } from './util'; +import { createTestUser, mockedId } from './util'; describe('Roles Task', async () => { test('Should not throw', async () => { @@ -24,23 +22,23 @@ describe('Roles Task', async () => { for (const minigame of minigames) { minigameUpdate[minigame] = 1000; } - await prisma.minigame.upsert({ + await global.prisma!.minigame.upsert({ where: { user_id: ironUser.id }, update: minigameUpdate, create: { user_id: ironUser.id, ...minigameUpdate } }); - await prisma.giveaway.create({ + await global.prisma!.giveaway.create({ data: { user_id: user.id, loot: { 995: 10_000 }, start_date: new Date(), finish_date: new Date(Date.now() + Time.Hour), channel_id: '792691343284764693', - message_id: randomSnowflake(), - reaction_id: randomSnowflake(), + message_id: mockedId(), + reaction_id: mockedId(), users_entered: [], - id: cryptoRand(1, 100), + id: cryptoRand(1, 10_000_000), completed: false, duration: 10_000 } diff --git a/tests/integration/setup.ts b/tests/integration/setup.ts index 8617aef368..baf9a63b96 100644 --- a/tests/integration/setup.ts +++ b/tests/integration/setup.ts @@ -1,6 +1,8 @@ import '../globalSetup'; -import { vi } from 'vitest'; +import { afterEach, beforeEach, vi } from 'vitest'; + +import { prisma } from '../../src/lib/settings/prisma'; vi.mock('../../src/lib/util/handleMahojiConfirmation', () => ({ handleMahojiConfirmation: vi.fn() @@ -26,3 +28,12 @@ globalClient.fetchUser = async (id: string | bigint) => ({ id: typeof id === 'string' ? id : String(id), send: async () => {} }); + +beforeEach(async () => { + await prisma.$connect(); + console.log(await prisma.$queryRawUnsafe('select count(*) from pg_stat_activity;')); +}); + +afterEach(async () => { + await prisma.$disconnect(); +}); diff --git a/tests/integration/stats.test.ts b/tests/integration/stats.test.ts index 87df8e3319..336435ae15 100644 --- a/tests/integration/stats.test.ts +++ b/tests/integration/stats.test.ts @@ -1,6 +1,5 @@ import { describe, test } from 'vitest'; -import { prisma } from '../../src/lib/settings/prisma'; import { dataPoints } from '../../src/mahoji/lib/abstracted_commands/statCommand'; import { createTestUser, mockClient } from './util'; @@ -9,7 +8,7 @@ describe('Datapoints', async () => { test('Data points', async () => { const user = await createTestUser(); - const stats = await prisma.userStats.upsert({ + const stats = await global.prisma!.userStats.upsert({ where: { user_id: BigInt(user.id) }, create: { user_id: BigInt(user.id) }, update: {} diff --git a/tests/integration/tradeTransaction.test.ts b/tests/integration/tradeTransaction.test.ts index 1d514d7a84..8a0b34b76e 100644 --- a/tests/integration/tradeTransaction.test.ts +++ b/tests/integration/tradeTransaction.test.ts @@ -1,20 +1,19 @@ import 'source-map-support/register'; -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { Prisma } from '@prisma/client'; import { Bank } from 'oldschooljs'; import { describe, expect, test } from 'vitest'; -import { prisma } from '../../src/lib/settings/prisma'; import { tradePlayerItems } from '../../src/lib/util/tradePlayerItems'; +import { mockedId } from './util'; describe('Transactionalized Trade Test', async () => { async function createUserWithBank(bank: Bank, userData: Partial = {}) { - const userId = randomSnowflake(); + const userId = mockedId(); const GP = bank.amount('Coins'); delete bank.bank[995]; - await prisma.user.create({ + await global.prisma!.user.create({ data: { id: userId, GP, bank: bank.bank, ...userData } }); diff --git a/tests/integration/trading.test.ts b/tests/integration/trading.test.ts index 8c6cdfad83..25d3194ad1 100644 --- a/tests/integration/trading.test.ts +++ b/tests/integration/trading.test.ts @@ -2,7 +2,6 @@ import { randArrItem, shuffleArr } from 'e'; import { Bank } from 'oldschooljs'; import { expect, test } from 'vitest'; -import { prisma } from '../../src/lib/settings/prisma'; import { tradeCommand } from '../../src/mahoji/commands/trade'; import { createTestUser, mockClient, TestUser } from './util'; @@ -14,7 +13,7 @@ test('Trade consistency', async () => { const users: TestUser[] = []; for (let i = 0; i < NUMBER_OF_USERS; i++) { - users.push(await createTestUser(undefined, bank)); + users.push(await createTestUser(bank)); } function checkMatch() { @@ -70,7 +69,7 @@ test('Trade consistency', async () => { await Promise.all(promises); checkMatch(); expect( - await prisma.economyTransaction.count({ + await global.prisma!.economyTransaction.count({ where: { sender: { in: users.map(u => BigInt(u.id)) diff --git a/tests/integration/userStats.test.ts b/tests/integration/userStats.test.ts index 8579410fa1..f6815ebaba 100644 --- a/tests/integration/userStats.test.ts +++ b/tests/integration/userStats.test.ts @@ -1,4 +1,3 @@ -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { describe, expect, test } from 'vitest'; import { userStatsUpdate } from '../../src/mahoji/mahojiSettings'; @@ -6,11 +5,11 @@ import { createTestUser, mockClient } from './util'; describe('User Stats', async () => { await mockClient(); - const userID = randomSnowflake(); test('Should return nothing', async () => { - await createTestUser(userID); - const user = await mUserFetch(userID); + const user = await createTestUser(); + const userID = user.id; + expect(await user.fetchStats({})).toEqual({ user_id: BigInt(userID) }); const result = await userStatsUpdate( userID, diff --git a/tests/integration/util.ts b/tests/integration/util.ts index 9bfd9e4273..e1b18d1ef9 100644 --- a/tests/integration/util.ts +++ b/tests/integration/util.ts @@ -1,4 +1,3 @@ -import { randomSnowflake } from '@oldschoolgg/toolkit'; import { Prisma } from '@prisma/client'; import { randInt, shuffleArr, uniqueArr } from 'e'; import { CommandRunOptions } from 'mahoji'; @@ -6,10 +5,10 @@ import { Bank } from 'oldschooljs'; import { globalConfig } from '../../src/lib/constants'; import { MUserClass } from '../../src/lib/MUser'; -import { convertStoredActivityToFlatActivity, prisma } from '../../src/lib/settings/prisma'; +import { convertStoredActivityToFlatActivity } from '../../src/lib/settings/prisma'; import { processPendingActivities } from '../../src/lib/Task'; import { ItemBank } from '../../src/lib/types'; -import { assert, cryptoRand } from '../../src/lib/util'; +import { cryptoRand } from '../../src/lib/util'; import { giveMaxStats } from '../../src/mahoji/commands/testpotato'; import { ironmanCommand } from '../../src/mahoji/lib/abstracted_commands/ironmanCommand'; import { OSBMahojiCommand } from '../../src/mahoji/lib/util'; @@ -63,9 +62,9 @@ export class TestUser extends MUserClass { if (res !== 'You are now an ironman.') { throw new Error(`Failed to reset: ${res}`); } - await prisma.userStats.deleteMany({ where: { user_id: BigInt(this.id) } }); - await prisma.user.delete({ where: { id: this.id } }); - const user = await prisma.user.create({ data: { id: this.id } }); + await global.prisma!.userStats.deleteMany({ where: { user_id: BigInt(this.id) } }); + await global.prisma!.user.delete({ where: { id: this.id } }); + const user = await global.prisma!.user.create({ data: { id: this.id } }); this.user = user; } @@ -124,20 +123,21 @@ export class TestUser extends MUserClass { } } -export async function createTestUser( - id = cryptoRand(1_000_000_000, 5_000_000_000).toString(), - bank?: Bank, - userData: Partial = {} -) { - const user = await prisma.user.upsert({ +export function mockedId() { + return cryptoRand(1_000_000_000, 5_000_000_000_000).toString(); +} + +export async function createTestUser(bank?: Bank, userData: Partial = {}) { + const id = userData?.id ?? mockedId(); + const user = await global.prisma!.user.upsert({ create: { id, - bank: bank?.bank, - ...userData + ...userData, + bank: bank?.bank }, update: { - bank: bank?.bank, - ...userData + ...userData, + bank: bank?.bank }, where: { id @@ -145,14 +145,14 @@ export async function createTestUser( }); try { - await prisma.userStats.create({ + await global.prisma!.userStats.create({ data: { user_id: BigInt(user.id) } }); } catch (err) { console.error(`Failed to make userStats for ${user.id}`); - throw new Error(`Failed to make userStats for ${user.id}`); + throw new Error(err as any); } return new TestUser(user); @@ -165,12 +165,12 @@ class TestClient { } async reset() { - await prisma.clientStorage.delete({ where: { id: this.data.id } }); - this.data = (await prisma.clientStorage.create({ data: { id: this.data.id } }))!; + await global.prisma!.clientStorage.delete({ where: { id: this.data.id } }); + this.data = (await global.prisma!.clientStorage.create({ data: { id: this.data.id } }))!; } async sync() { - this.data = (await prisma.clientStorage.findFirst({ where: { id: this.data.id } }))!; + this.data = (await global.prisma!.clientStorage.findFirst({ where: { id: this.data.id } }))!; } async expectValueMatch(key: keyof ClientStorage, value: any) { @@ -182,8 +182,8 @@ class TestClient { } export async function mockClient() { - const clientId = randomSnowflake(); - const client = await prisma.clientStorage.create({ + const clientId = mockedId(); + const client = await global.prisma!.clientStorage.create({ data: { id: clientId } @@ -193,4 +193,6 @@ export async function mockClient() { return new TestClient(client); } -assert(uniqueArr([randomSnowflake(), randomSnowflake(), randomSnowflake()]).length === 3); +if (uniqueArr([mockedId(), mockedId(), mockedId()]).length !== 3) { + throw new Error('mockedId is broken'); +} diff --git a/vitest.integration.config.ts b/vitest.integration.config.ts index bfc41a49f3..871ff59afb 100644 --- a/vitest.integration.config.ts +++ b/vitest.integration.config.ts @@ -11,6 +11,10 @@ export default defineConfig({ include: ['src/lib/MUser.ts'] }, testTimeout: 30_000, - bail: 1 + bail: 1, + threads: true, + maxConcurrency: 1, + minThreads: 1, + maxThreads: 3 } });