-
Notifications
You must be signed in to change notification settings - Fork 0
OUT-3586: integration tests for price.created with testcontainers #221
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3b99acd
test(OUT-3546): set up Vitest integration project with testcontainers…
SandipBajracharya 5ec80ee
test(OUT-3586): add addBreadcrumb to shared Sentry mock
SandipBajracharya 87f50ac
refactor(OUT-3586): nest priceCreated tests and extract shared helpers
SandipBajracharya 3f1c027
fix(OUT-3586): skip dotenv.config under Vitest to prevent .env leakage
SandipBajracharya 968aa29
docs(OUT-3586): correct globalSetup comment referencing Vitest config
SandipBajracharya a99e01b
chore(OUT-3586): lint fix
SandipBajracharya 5773343
fix(OUT-3586): seed tokenSetTime so tests skip real Intuit OAuth refresh
SandipBajracharya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # Test-only environment variables. | ||
| # | ||
| # Loaded by test/integration/globalSetup.ts BEFORE the testcontainer Postgres | ||
| # is started. DATABASE_URL is intentionally NOT set here — globalSetup sets it | ||
| # dynamically to the container's connection URI. | ||
| # | ||
| # Everything in this file should be a non-secret stub. No real credentials. | ||
|
|
||
| # Copilot | ||
| COPILOT_API_KEY=test-copilot-api-key | ||
| NEXT_PUBLIC_COPILOT_APP_API_KEY=test-copilot-app-key | ||
| NEXT_PUBLIC_COPILOT_DASHBOARD_URL=https://test.copilot.local | ||
| COPILOT_ENV=test | ||
|
|
||
| # Intuit / QuickBooks | ||
| INTUIT_CLIENT_ID=test-intuit-client-id | ||
| INTUIT_CLIENT_SECRET=test-intuit-client-secret | ||
| INTUIT_REDIRECT_URI_PATH=/api/quickbooks/auth/callback | ||
| INTUIT_ENVIRONMENT=sandbox | ||
| INTUIT_SANDBOX_API_URL=https://sandbox-quickbooks.api.intuit.com | ||
| INTUIT_PRODUCTION_API_URL=https://quickbooks.api.intuit.com | ||
| INTUIT_API_MINOR_VERSION=75 | ||
|
|
||
| # Supabase (stubs — tests don't hit Supabase) | ||
| NEXT_PUBLIC_SUPABASE_PROJECT_URL=https://test.supabase.local | ||
| NEXT_PUBLIC_SUPABASE_ANON_KEY=test-anon-key | ||
|
|
||
| # Cron | ||
| CRON_SECRET=test-cron-secret | ||
|
|
||
| # Vercel / Next | ||
| VERCEL_URL=localhost:3000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -41,4 +41,7 @@ yarn-error.log* | |
| *.tsbuildinfo | ||
| next-env.d.ts | ||
|
|
||
| .trigger | ||
| .trigger | ||
|
|
||
| # local decision notes (not published) | ||
| /docs | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| { | ||
| "eventType": "price.created", | ||
| "created": "2024-09-11T13:59:58.845233992Z", | ||
| "object": "price", | ||
| "data": { | ||
| "id": "C-wch-eSg", | ||
| "createdAt": "2024-09-11T13:59:58.845233992Z", | ||
| "object": "price", | ||
| "amount": 60000, | ||
| "currency": "usd", | ||
| "interval": "month", | ||
| "intervalCount": 3, | ||
| "productId": "2cf93cf0-45fa-485f-b584-03c2c38a3999", | ||
| "type": "recurring", | ||
| "updatedAt": "2024-09-11T13:59:58.845233992Z" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import { vi, type Mock } from 'vitest' | ||
| import { CopilotAPI } from '@/utils/copilotAPI' | ||
| import IntuitAPI from '@/utils/intuitAPI' | ||
| import { | ||
| TEST_INCOME_ACCOUNT_REF, | ||
| TEST_INTERNAL_USER_ID, | ||
| TEST_PORTAL_ID, | ||
| } from './seed' | ||
|
|
||
| // Restricts override keys to the actual method names of the underlying class | ||
| // so typos produce a compile-time error. The Mock value type intentionally | ||
| // stays loose — tests routinely return shapes that don't match the real | ||
| // Promise return type. | ||
| type MockMethodOverrides<T> = { | ||
| [K in keyof T as T[K] extends (...args: never[]) => unknown | ||
| ? K | ||
| : never]?: Mock | ||
| } | ||
|
|
||
| type CopilotAPIOverrides = MockMethodOverrides<CopilotAPI> | ||
| type IntuitAPIOverrides = MockMethodOverrides<IntuitAPI> | ||
|
|
||
| /** | ||
| * Factory for a mocked CopilotAPI instance. | ||
| * | ||
| * Tests mock the CopilotAPI module with `vi.mock('@/utils/copilotAPI')`, then | ||
| * wire each `new CopilotAPI(token)` call to an object produced by this factory. | ||
| * Override any method via the `overrides` arg to tailor behavior per test. | ||
| */ | ||
| export function createMockCopilotAPI(overrides: CopilotAPIOverrides = {}) { | ||
| return { | ||
| getTokenPayload: vi.fn().mockResolvedValue({ | ||
| workspaceId: TEST_PORTAL_ID, | ||
| internalUserId: TEST_INTERNAL_USER_ID, | ||
| }), | ||
| getProduct: vi.fn().mockResolvedValue({ | ||
| id: '2cf93cf0-45fa-485f-b584-03c2c38a3999', | ||
| name: 'Test Product', | ||
| description: 'Test product description', | ||
| status: 'active', | ||
| createdAt: '2024-09-11T13:59:58.845233992Z', | ||
| updatedAt: '2024-09-11T13:59:58.845233992Z', | ||
| }), | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Factory for a mocked IntuitAPI instance. | ||
| * | ||
| * Defaults represent the happy path for `price.created`: | ||
| * - getAnItem returns undefined (no existing item in QB) | ||
| * - getAnAccount returns an active income account matching the seeded ref | ||
| * - createItem returns a freshly-created QB item | ||
| */ | ||
| export function createMockIntuitAPI(overrides: IntuitAPIOverrides = {}) { | ||
| return { | ||
| getAnItem: vi.fn().mockResolvedValue(undefined), | ||
| getAnAccount: vi.fn().mockResolvedValue({ | ||
| Id: TEST_INCOME_ACCOUNT_REF, | ||
| Name: 'Sales of Product Income', | ||
| SyncToken: '0', | ||
| Active: true, | ||
| AccountType: 'Income', | ||
| }), | ||
| createItem: vi.fn().mockResolvedValue({ | ||
| Id: '999', | ||
| Name: 'Test Product', | ||
| SyncToken: '0', | ||
| UnitPrice: 600, | ||
| }), | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| export type MockCopilotAPI = ReturnType<typeof createMockCopilotAPI> | ||
| export type MockIntuitAPI = ReturnType<typeof createMockIntuitAPI> | ||
|
|
||
| /** | ||
| * Wires the module-mocked CopilotAPI + IntuitAPI to return shared instances | ||
| * for the duration of a test. Pass pre-built instances (e.g., with overrides) | ||
| * or accept the defaults. | ||
| * | ||
| * Returns the instances so tests can assert on call counts / arguments. | ||
| * | ||
| * Must use `function` (not arrow) so the mock is callable with `new`. | ||
| * | ||
| * CAVEAT — shared instance across multiple `new` sites: | ||
| * The price.created flow constructs `new CopilotAPI(...)` TWICE per request — | ||
| * once in `authenticate()` (calls `.getTokenPayload()`) and once in | ||
| * `webhookPriceCreated` (calls `.getProduct()`). Both sites receive the SAME | ||
| * `copilot` mock object returned here. This is fine when asserting on | ||
| * different methods (e.g., `getProduct` only fires from the service call), | ||
| * but be careful with shared methods: `toHaveBeenCalledTimes(1)` on a method | ||
| * both sites touch would reflect the sum of both call sites. Same applies to | ||
| * IntuitAPI if/when it gets instantiated more than once per request. | ||
| */ | ||
| export function installMockApis( | ||
| opts: { | ||
| copilot?: MockCopilotAPI | ||
| intuit?: MockIntuitAPI | ||
| } = {}, | ||
| ): { copilot: MockCopilotAPI; intuit: MockIntuitAPI } { | ||
| const copilot = opts.copilot ?? createMockCopilotAPI() | ||
| const intuit = opts.intuit ?? createMockIntuitAPI() | ||
|
|
||
| vi.mocked(CopilotAPI).mockImplementation(function ( | ||
| this: unknown, | ||
| ): CopilotAPI { | ||
| return copilot as unknown as CopilotAPI | ||
| } as unknown as typeof CopilotAPI) | ||
|
|
||
| vi.mocked(IntuitAPI).mockImplementation(function (this: unknown): IntuitAPI { | ||
| return intuit as unknown as IntuitAPI | ||
| } as unknown as typeof IntuitAPI) | ||
|
|
||
| return { copilot, intuit } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { beforeEach, afterEach, vi } from 'vitest' | ||
| import { truncateAllTestTables } from '@test/helpers/testDb' | ||
| import { | ||
| installMockApis, | ||
| type MockCopilotAPI, | ||
| type MockIntuitAPI, | ||
| } from '@test/helpers/mocks' | ||
|
|
||
| type InstallOpts = Parameters<typeof installMockApis>[0] | ||
|
|
||
| export interface PriceCreatedTestHandle { | ||
| copilot: MockCopilotAPI | ||
| intuit: MockIntuitAPI | ||
| } | ||
|
|
||
| /** | ||
| * Registers the standard `beforeEach` (truncate + installMockApis) and | ||
| * `afterEach` (clearAllMocks) hooks used by every price.created integration | ||
| * test. Returns a live handle whose `copilot` / `intuit` properties are | ||
| * replaced with fresh mock instances before each test. | ||
| * | ||
| * The `optsFactory` is invoked once per test so callers can supply overrides | ||
| * whose underlying `vi.fn()`s are freshly instantiated — a static opts object | ||
| * would be broken by the `vi.clearAllMocks()` call in afterEach. | ||
| */ | ||
| export function setupPriceCreatedTest( | ||
| optsFactory?: () => InstallOpts, | ||
| ): PriceCreatedTestHandle { | ||
| const handle = {} as PriceCreatedTestHandle | ||
|
|
||
| beforeEach(async () => { | ||
| await truncateAllTestTables() | ||
| const { copilot, intuit } = installMockApis(optsFactory?.()) | ||
| handle.copilot = copilot | ||
| handle.intuit = intuit | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| // clearAllMocks (not restoreAllMocks) — the module-level mock factories in | ||
| // test/integration/setup.ts must stay installed across tests; we only want | ||
| // to reset call counts and implementations set in beforeEach. | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| return handle | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import type { InferInsertModel } from 'drizzle-orm' | ||
| import type { z } from 'zod' | ||
| import { db } from '@/db' | ||
| import { | ||
| QBPortalConnection, | ||
| QBPortalConnectionCreateSchema, | ||
| } from '@/db/schema/qbPortalConnections' | ||
| import { QBProductSync } from '@/db/schema/qbProductSync' | ||
| import { QBSetting, QBSettingCreateSchema } from '@/db/schema/qbSettings' | ||
|
|
||
| export const TEST_PORTAL_ID = 'test-portal-00000001' | ||
| export const TEST_REALM_ID = 'test-realm-123' | ||
| export const TEST_ACCESS_TOKEN = 'test-access-token' | ||
| export const TEST_REFRESH_TOKEN = 'test-refresh-token' | ||
| export const TEST_INCOME_ACCOUNT_REF = '100' | ||
| export const TEST_ASSET_ACCOUNT_REF = '101' | ||
| export const TEST_EXPENSE_ACCOUNT_REF = '102' | ||
| export const TEST_INTERNAL_USER_ID = 'test-internal-user-id' | ||
| export const TEST_WEBHOOK_TOKEN = 'test-token-xyz' | ||
|
|
||
| // Override types are derived from the Drizzle-generated insert schemas so | ||
| // they stay in sync with the DB schema automatically. Using `Partial<typeof base>` | ||
| // would widen primitives (e.g., `true` → `boolean`) but wouldn't track column | ||
| // type changes in the underlying schema. | ||
| type PortalOverrides = Partial<z.infer<typeof QBPortalConnectionCreateSchema>> | ||
| type SettingOverrides = Partial<z.infer<typeof QBSettingCreateSchema>> | ||
| type ProductSyncOverrides = Partial<InferInsertModel<typeof QBProductSync>> | ||
|
|
||
| const basePortalConnection: z.infer<typeof QBPortalConnectionCreateSchema> = { | ||
| portalId: TEST_PORTAL_ID, | ||
| intuitRealmId: TEST_REALM_ID, | ||
| accessToken: TEST_ACCESS_TOKEN, | ||
| refreshToken: TEST_REFRESH_TOKEN, | ||
| // Keeps `isTokenFresh` true so tests don't trigger a real Intuit OAuth call. | ||
| tokenSetTime: new Date(), | ||
| expiresIn: 3600, | ||
| XRefreshTokenExpiresIn: 8_726_400, | ||
| intiatedBy: TEST_INTERNAL_USER_ID, | ||
| incomeAccountRef: TEST_INCOME_ACCOUNT_REF, | ||
| assetAccountRef: TEST_ASSET_ACCOUNT_REF, | ||
| expenseAccountRef: TEST_EXPENSE_ACCOUNT_REF, | ||
| } | ||
|
|
||
| const baseSetting: z.infer<typeof QBSettingCreateSchema> = { | ||
| portalId: TEST_PORTAL_ID, | ||
| absorbedFeeFlag: false, | ||
| useCompanyNameFlag: false, | ||
| createNewProductFlag: true, | ||
| initialInvoiceSettingMap: true, | ||
| initialProductSettingMap: true, | ||
| syncFlag: true, | ||
| isEnabled: true, | ||
| } | ||
|
|
||
| export async function seedPortalConnection(overrides: PortalOverrides = {}) { | ||
| const [row] = await db | ||
| .insert(QBPortalConnection) | ||
| .values({ ...basePortalConnection, ...overrides }) | ||
| .returning() | ||
| return row | ||
| } | ||
|
|
||
| export async function seedSetting(overrides: SettingOverrides = {}) { | ||
| const [row] = await db | ||
| .insert(QBSetting) | ||
| .values({ ...baseSetting, ...overrides }) | ||
| .returning() | ||
| return row | ||
| } | ||
|
|
||
| const baseProductSync: InferInsertModel<typeof QBProductSync> = { | ||
| portalId: TEST_PORTAL_ID, | ||
| productId: '2cf93cf0-45fa-485f-b584-03c2c38a3999', | ||
| priceId: 'C-wch-eSg', | ||
| name: 'Test Product', | ||
| copilotName: 'Test Product', | ||
| unitPrice: '60000.00', | ||
| qbItemId: '999', | ||
| qbSyncToken: '0', | ||
| } | ||
|
|
||
| export async function seedProductSync(overrides: ProductSyncOverrides = {}) { | ||
| const [row] = await db | ||
| .insert(QBProductSync) | ||
| .values({ ...baseProductSync, ...overrides }) | ||
| .returning() | ||
| return row | ||
| } | ||
|
|
||
| /** | ||
| * Convenience seeder for the common "healthy portal" fixture used by | ||
| * most tests. Returns both rows for assertions if needed. | ||
| */ | ||
| export async function seedHealthyPortal( | ||
| opts: { | ||
| portal?: PortalOverrides | ||
| setting?: SettingOverrides | ||
| } = {}, | ||
| ) { | ||
| const portal = await seedPortalConnection(opts.portal) | ||
| const setting = await seedSetting(opts.setting) | ||
| return { portal, setting } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { sql } from 'drizzle-orm' | ||
| import { db } from '@/db' | ||
|
|
||
| /** | ||
| * Wipes every table in the schema that integration tests can touch. Call in | ||
| * `beforeEach` — the testcontainer Postgres is shared across the full | ||
| * integration run, so cross-test contamination is a real risk. | ||
| * | ||
| * If a new table is added to `src/db/schema/*.ts`, add it here too. The | ||
| * consequence of forgetting is silent cross-test contamination — tests pass | ||
| * in isolation but fail in full-suite runs depending on file order. | ||
| */ | ||
| export async function truncateAllTestTables() { | ||
| await db.execute(sql` | ||
| TRUNCATE TABLE | ||
| qb_sync_logs, | ||
| qb_connection_logs, | ||
| qb_customers, | ||
| qb_invoice_sync, | ||
| qb_payment_sync, | ||
| qb_product_sync, | ||
| qb_settings, | ||
| qb_portal_connections | ||
| RESTART IDENTITY CASCADE | ||
| `) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.