Spaces:
Paused
Paused
Download apps/prevision-api/test/helpers.ts from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 5.72 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/prevision-api/test/helpers.ts
- Command line
-
hf download hf://spaces/modventures/prevision/apps/prevision-api/test/helpers.ts
-
curl -L -o helpers.ts https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/prevision-api/test/helpers.ts
5.72 kB
| import type { INestApplication } from '@nestjs/common'; | |
| import { Test } from '@nestjs/testing'; | |
| import { exportSPKI, generateKeyPair, SignJWT } from 'jose'; | |
| import pg from 'pg'; | |
| import request from 'supertest'; | |
| import { AppModule } from '../src/app.module.js'; | |
| import { setupApp } from '../src/app.setup.js'; | |
| import Stripe from 'stripe'; | |
| import type { Mock } from 'vitest'; | |
| import { ClerkService } from '../src/clerk/clerk.service.js'; | |
| import { STRIPE_CLIENT } from '../src/stripe/stripe.constants.js'; | |
| import type { ClerkProfile } from '../src/clerk/interfaces/clerk.interface.js'; | |
| const ORIGIN = 'http://app.test'; | |
| const SECRET = new TextEncoder().encode('test-processing-secret-0123456789abcdef012'); | |
| const KID = 'test-key'; | |
| const clerkKeys = await generateKeyPair('RS256'); | |
| export const otherKeys = await generateKeyPair('RS256'); | |
| // Networkless Clerk verification with a test key (CLERK_JWT_KEY in production). | |
| process.env.CLERK_JWT_KEY = await exportSPKI(clerkKeys.publicKey); | |
| export const clerkUsers = new Map<string, ClerkProfile>(); | |
| /** Stripe in e2e: real webhook signing, stubbed API calls. */ | |
| const realStripe = new Stripe('sk_test_fake'); | |
| interface StripeStub { | |
| webhooks: Stripe['webhooks']; | |
| customers: { create: Mock }; | |
| checkout: { sessions: { create: Mock } }; | |
| billingPortal: { sessions: { create: Mock } }; | |
| subscriptions: { retrieve: Mock }; | |
| } | |
| export const stripeStub: StripeStub = { | |
| webhooks: realStripe.webhooks, | |
| customers: { create: vi.fn(async () => ({ id: 'cus_e2e' })) }, | |
| checkout: { sessions: { create: vi.fn(async () => ({ url: 'https://checkout.stripe.test/session' })) } }, | |
| billingPortal: { sessions: { create: vi.fn(async () => ({ url: 'https://billing.stripe.test/portal' })) } }, | |
| subscriptions: { retrieve: vi.fn() }, | |
| }; | |
| export function signedStripeEvent(type: string, object: object) { | |
| const payload = JSON.stringify({ id: `evt_${Date.now()}`, object: 'event', type, data: { object } }); | |
| return { payload, signature: realStripe.webhooks.generateTestHeaderString({ payload, secret: 'whsec_test_secret' }) }; | |
| } | |
| export async function sessionToken( | |
| sub: string, | |
| { key = clerkKeys.privateKey, azp = ORIGIN, expiresIn = 60, sid = 'sess_1' }: { key?: CryptoKey; azp?: string; expiresIn?: number; sid?: string } = {}, | |
| ) { | |
| const now = Math.floor(Date.now() / 1000); | |
| return new SignJWT({ sid, azp }) | |
| .setProtectedHeader({ alg: 'RS256', kid: KID }) | |
| .setIssuer('https://clerk.app.test') | |
| .setSubject(sub) | |
| .setIssuedAt(now - 5) | |
| .setNotBefore(now - 5) | |
| .setExpirationTime(now + expiresIn) | |
| .sign(key); | |
| } | |
| /** Headers of a signed-in Clerk user that the fake Clerk backend knows. */ | |
| export async function signIn(clerkId: string, email = `${clerkId}@example.com`, name: string | null = 'Test Person') { | |
| clerkUsers.set(clerkId, { email, name }); | |
| return { Authorization: `Bearer ${await sessionToken(clerkId)}`, Origin: ORIGIN }; | |
| } | |
| export async function internalToken(audience = 'prevision-internal', expiresIn = 60) { | |
| const now = Math.floor(Date.now() / 1000); | |
| return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(SECRET); | |
| } | |
| export async function createApp(): Promise<INestApplication> { | |
| const moduleRef = await Test.createTestingModule({ imports: [AppModule] }) | |
| .overrideProvider(ClerkService) | |
| .useFactory({ | |
| factory: (config) => { | |
| const service = new ClerkService(config); | |
| service.getVerifiedProfile = async (id: string) => { | |
| const profile = clerkUsers.get(id); | |
| if (!profile) throw new Error(`unknown Clerk user ${id}`); | |
| return profile; | |
| }; | |
| return service; | |
| }, | |
| inject: [(await import('../src/config/app-config.js')).APP_CONFIG], | |
| }) | |
| .overrideProvider(STRIPE_CLIENT) | |
| .useValue(stripeStub) | |
| .compile(); | |
| const app = setupApp(moduleRef.createNestApplication({ logger: false, rawBody: true })); | |
| await app.listen(0); | |
| return app; | |
| } | |
| export const api = (app: INestApplication) => request(app.getHttpServer()); | |
| export async function sql(query: string, values: unknown[] = []) { | |
| const db = new pg.Client({ connectionString: process.env.PREVISION_DATABASE_URL }); | |
| await db.connect(); | |
| try { | |
| return (await db.query(query, values)).rows; | |
| } finally { | |
| await db.end(); | |
| } | |
| } | |
| export async function resetDatabase() { | |
| await sql('TRUNCATE subscriptions, generations, users, tiles CASCADE'); | |
| clerkUsers.clear(); | |
| } | |
| export async function insertTiles( | |
| ...tiles: { | |
| slug: string; | |
| name: string; | |
| surfaces?: string[]; | |
| deleted?: boolean; | |
| collection?: string; | |
| visibility?: 'public' | 'admin'; | |
| brand?: string; | |
| organization?: string; | |
| }[] | |
| ) { | |
| for (const tile of tiles) { | |
| await sql( | |
| `INSERT INTO tiles (id, slug, name, surfaces, image_url, deleted_at, collection, visibility, brand, organization, render, updated_at) | |
| VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, $8, $9, '{"layout": "grid"}', now())`, | |
| [ | |
| tile.slug, | |
| tile.name, | |
| tile.surfaces ?? ['floor'], | |
| `https://cdn.test/${tile.slug}.jpg`, | |
| tile.deleted ? new Date() : null, | |
| tile.collection ?? null, | |
| tile.visibility ?? 'public', | |
| tile.brand ?? null, | |
| tile.organization ?? null, | |
| ], | |
| ); | |
| } | |
| } | |
| /** Headers of a signed-in user whose account has role=admin. */ | |
| export async function signInAdmin(clerkId: string, app: INestApplication) { | |
| const headers = await signIn(clerkId); | |
| await request(app.getHttpServer()).get('/api/me').set(headers); | |
| await sql('UPDATE users SET role = $1 WHERE clerk_user_id = $2', ['admin', clerkId]); | |
| return headers; | |
| } | |