Add database seeding script and backend testing folder structure (#18)

* setting up test structure

* added playwright config file, deleted original playwright folder and moved "some.test" file

* continued test structure setup

* Updating test folder structure

* Added database seeding script and backend testing folder structure

* removed the database test

* Replaced db seeding script

* Updated userInformation.ts to use values from choices.tsx
This commit is contained in:
Okechi Jones-Williams
2025-11-11 18:00:07 +00:00
committed by GitHub
parent 24ee2a206e
commit f954e3b2d7
9 changed files with 293 additions and 58 deletions

View File

@@ -48,6 +48,7 @@
"@capacitor/android": "7.4.4",
"@capacitor/assets": "3.0.5",
"@capacitor/cli": "7.4.4",
"@faker-js/faker": "10.1.0",
"@testing-library/dom": "^10.0.0",
"@testing-library/jest-dom": "^6.6.4",
"@testing-library/react": "^16.3.0",

124
scripts/userCreation.ts Normal file
View File

@@ -0,0 +1,124 @@
//Run with:
// export ENVIRONMENT=DEV && ./scripts/build_api.sh && npx tsx ./scripts/userCreation.ts
import {createSupabaseDirectClient} from "../backend/shared/lib/supabase/init";
import {insert} from "../backend/shared/lib/supabase/utils";
import {PrivateUser} from "../common/lib/user";
import {getDefaultNotificationPreferences} from "../common/lib/user-notification-preferences";
import {randomString} from "../common/lib/util/random";
import UserAccountInformation from "../tests/e2e/backend/utils/userInformation";
type ProfileType = 'basic' | 'medium' | 'full'
/**
* Function used to populate the database with profiles.
*
* @param pg - Supabase client used to access the database.
* @param userInfo - Class object containing information to create a user account generated by `fakerjs`.
* @param profileType - Optional param used to signify how much information is used in the account generation.
*/
async function seedDatabase (pg: any, userInfo: UserAccountInformation, profileType?: string) {
const userId = userInfo.user_id
const deviceToken = randomString()
const bio = {
"type": "doc",
"content": [
{
"type": "paragraph",
"content": [
{
"text": userInfo.bio,
"type": "text"
}
]
}
]
}
const basicProfile = {
user_id: userId,
bio_length: userInfo.bio.length,
bio: bio,
age: userInfo.age,
born_in_location: userInfo.born_in_location,
company: userInfo.company,
}
const mediumProfile = {
...basicProfile,
drinks_per_month: userInfo.drinks_per_month,
diet: [userInfo.randomElement(userInfo.diet)],
education_level: userInfo.randomElement(userInfo.education_level),
ethnicity: [userInfo.randomElement(userInfo.ethnicity)],
gender: userInfo.randomElement(userInfo.gender),
height_in_inches: userInfo.height_in_inches,
pref_gender: [userInfo.randomElement(userInfo.pref_gender)],
pref_age_min: userInfo.pref_age.min,
pref_age_max: userInfo.pref_age.max,
}
const fullProfile = {
...mediumProfile,
occupation_title: userInfo.occupation_title,
political_beliefs: [userInfo.randomElement(userInfo.political_beliefs)],
pref_relation_styles: [userInfo.randomElement(userInfo.pref_relation_styles)],
religion: [userInfo.randomElement(userInfo.religion)],
}
const profileData = profileType === 'basic' ? basicProfile
: profileType === 'medium' ? mediumProfile
: fullProfile
const user = {
// avatarUrl,
isBannedFromPosting: false,
link: {},
}
const privateUser: PrivateUser = {
id: userId,
email: userInfo.email,
initialIpAddress: userInfo.ip,
initialDeviceToken: deviceToken,
notificationPreferences: getDefaultNotificationPreferences(),
blockedUserIds: [],
blockedByUserIds: [],
}
await pg.tx(async (tx:any) => {
await insert(tx, 'users', {
id: userId,
name: userInfo.name,
username: userInfo.name,
data: user,
})
await insert(tx, 'private_users', {
id: userId,
data: privateUser,
})
await insert(tx, 'profiles', profileData )
})
}
(async () => {
const pg = createSupabaseDirectClient()
//Edit the count seedConfig to specify the amount of each profiles to create
const seedConfig = [
{ count: 1, profileType: 'basic' as ProfileType },
{ count: 1, profileType: 'medium' as ProfileType },
{ count: 1, profileType: 'full' as ProfileType },
]
for (const {count, profileType } of seedConfig) {
for (let i = 0; i < count; i++) {
const userInfo = new UserAccountInformation()
await seedDatabase(pg, userInfo, profileType)
}
}
process.exit(0)
})()

View File

@@ -1,58 +0,0 @@
// This is a script to add a user to the DB: entries in the users and private_users table
// Run with:
// export ENVIRONMENT=DEV && ./../scripts/build_api.sh && npx tsx users.ts
import {createSupabaseDirectClient} from "shared/lib/supabase/init";
import {insert} from "shared/lib/supabase/utils";
import {PrivateUser} from "common/lib/user";
import {getDefaultNotificationPreferences} from "common/lib/user-notification-preferences";
import {randomString} from "common/lib/util/random";
(async () => {
const userId = '...'
const email = '...'
const name = '...'
const username = '...'
const ip = '...'
const deviceToken = randomString()
const pg = createSupabaseDirectClient()
const user = {
// avatarUrl,
isBannedFromPosting: false,
link: {},
}
const privateUser: PrivateUser = {
id: userId,
email,
initialIpAddress: ip,
initialDeviceToken: deviceToken,
notificationPreferences: getDefaultNotificationPreferences(),
blockedUserIds: [],
blockedByUserIds: [],
}
await pg.tx(async (tx) => {
const newUserRow = await insert(tx, 'users', {
id: userId,
name,
username,
data: user,
})
console.log(newUserRow)
const newPrivateUserRow = await insert(tx, 'private_users', {
id: userId,
data: privateUser,
})
console.log(newPrivateUserRow)
})
process.exit(0)
})()

View File

@@ -0,0 +1,16 @@
import { test as base, APIRequestContext, request } from '@playwright/test';
export type TestOptions = {
apiContextPage: APIRequestContext,
}
export const test = base.extend<TestOptions>({
apiContextPage: async ({}, use) => {
const apiContext = await request.newContext({
baseURL: 'https://api.compassmeet.com'
});
await use(apiContext)
},
})
export { expect } from "@playwright/test"

View File

@@ -0,0 +1,14 @@
import { test, expect } from "../fixtures/base";
test('Check API health', async ({apiContextPage}) => {
const responseHealth = await apiContextPage.get('/health');
expect(responseHealth.status()).toBe(200)
const responseBody = await responseHealth.json()
console.log(JSON.stringify(responseBody, null, 2));
});
test.afterAll(async ({apiContextPage}) => {
await apiContextPage?.dispose();
})

View File

@@ -0,0 +1,78 @@
import {expect, test } from '@playwright/test';
import { createSupabaseDirectClient } from "../../../../backend/shared/src/supabase/init";
test('View database', async () => {
// const dbClient = createSupabaseDirectClient()
// const queryUserID = `
// SELECT p.*
// FROM public.profiles AS p
// WHERE id = $1
// `;
// const queryTableColumns = `
// SELECT
// column_name,
// data_type,
// character_maximum_length,
// is_nullable,
// column_default
// FROM information_schema.columns
// WHERE table_schema = 'public'
// AND table_name ='profiles'
// ORDER BY ordinal_position;
// `;
// const queryTableColumnsNullable = `
// SELECT
// column_name,
// data_type,
// character_maximum_length,
// column_default
// FROM information_schema.columns
// WHERE table_schema = 'public'
// AND table_name =$1
// AND is_nullable = $2
// ORDER BY ordinal_position;
// `;
// const queryInsertUserProfile = `
// INSERT INTO profiles (name, username)
// VALUES ($1, $2)
// RETURNING *;
// `;
// const queryInsertUsers = `
// INSERT INTO profiles (id, bio)
// VALUES ($1, $2)
// RETURNING *;
// `;
// const rows = await dbClient.query(
// queryInsertUsers,
// [
// 'JFTZOhrBagPk',
// {
// "type": "doc",
// "content": [
// {
// "type": "paragraph",
// "content": [
// {
// "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
// "type": "text"
// }
// ]
// }
// ]
// }
// ]
// )
// console.log("Type of: ",typeof(rows));
// console.log("Number of rows: ",rows.length);
// console.log(JSON.stringify(await rows, null, 2));
})

View File

@@ -0,0 +1,55 @@
import { faker } from "@faker-js/faker";
import {
RELATIONSHIP_CHOICES,
POLITICAL_CHOICES,
RELIGION_CHOICES,
DIET_CHOICES,
EDUCATION_CHOICES,
} from "../../../../web/components/filters/choices";
import { Races } from "../../../../web/components/race";
class UserAccountInformation {
name = faker.person.fullName();
email = faker.internet.email();
user_id = faker.string.alpha(28)
password = faker.internet.password();
ip = faker.internet.ip()
age = faker.number.int({min: 18, max:100});
bio = faker.lorem.words({min: 200, max:350});
born_in_location = faker.location.country();
gender = [
'Female',
'Male',
'Other'
];
pref_gender = [
'Female',
'Male',
'Other'
];
pref_age = {
min: faker.number.int({min: 18, max:27}),
max: faker.number.int({min: 36, max:68})
};
pref_relation_styles = Object.values(RELATIONSHIP_CHOICES);
political_beliefs = Object.values(POLITICAL_CHOICES);
religion = Object.values(RELIGION_CHOICES);
diet = Object.values(DIET_CHOICES);
drinks_per_month = faker.number.int({min: 4, max:40});
height_in_inches = faker.number.float({min: 56, max: 78, fractionDigits:2});
ethnicity = Object.values(Races);
education_level = Object.values(EDUCATION_CHOICES);
company = faker.company.name();
occupation_title = faker.person.jobTitle();
university = faker.company.name();
randomElement (array: Array<string>) {
return array[Math.floor(Math.random() * array.length)].toLowerCase()
}
}
export default UserAccountInformation;

View File

@@ -1386,6 +1386,11 @@
resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.0.tgz#a5417ae8427873f1dd08b70b3574b453e67b5f7f"
integrity sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==
"@faker-js/faker@10.1.0":
version "10.1.0"
resolved "https://registry.yarnpkg.com/@faker-js/faker/-/faker-10.1.0.tgz#eb72869d01ccbff41a77aa7ac851ce1ac9371129"
integrity sha512-C3mrr3b5dRVlKPJdfrAXS8+dq+rq8Qm5SNRazca0JKgw1HQERFmrVb0towvMmw5uu8hHKNiQasMaR/tydf3Zsg==
"@fastify/busboy@^3.0.0":
version "3.2.0"
resolved "https://registry.yarnpkg.com/@fastify/busboy/-/busboy-3.2.0.tgz#13ed8212f3b9ba697611529d15347f8528058cea"