Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

test-context.ts

243 lines6.6 KB

1import { inject, test } from 'vitest'
2import { generateSeedData } from '../src/fixtures/seed-data'
3import { makePgClient } from './global-setup'
4import type { Client } from 'pg'
5import type { SeedDataResult } from '../src/types'
6​
7/**
8 * Base fixture with database client and abort controller
9 */
10export const testWithDb = test.extend<{
11 dbClient: Client
12 aborter: AbortController
13 baseUrl: string
14 testSchema: string
15 tableName: (base: string) => string
16}>({
17 // eslint-disable-next-line no-empty-pattern
18 dbClient: async ({}, use) => {
19 const schema = inject('testSchema')
20 const client = makePgClient({
21 options: `-csearch_path=${schema}`,
22 })
23 await client.connect()
24​
25 // Ensure schema is set
26 await client.query(`SET search_path TO ${schema}`)
27​
28 await use(client)
29 await client.end()
30 },
31​
32 // eslint-disable-next-line no-empty-pattern
33 aborter: async ({}, use) => {
34 const controller = new AbortController()
35 await use(controller)
36 controller.abort('Test complete')
37 },
38​
39 // eslint-disable-next-line no-empty-pattern
40 baseUrl: async ({}, use) => {
41 await use(inject('baseUrl'))
42 },
43​
44 // eslint-disable-next-line no-empty-pattern
45 testSchema: async ({}, use) => {
46 await use(inject('testSchema'))
47 },
48​
49 tableName: async ({ task }, use) => {
50 // Generate unique table names based on task ID and random suffix
51 await use((base: string) => {
52 const taskId = task.id.replace(/[^a-zA-Z0-9]/g, '_')
53 const random = Math.random().toString(16).slice(2, 8)
54 return `"${base}_${taskId}_${random}"`
55 })
56 },
57})
58​
59/**
60 * Extended fixture with test tables (Users, Posts, Comments)
61 */
62export const testWithTables = testWithDb.extend<{
63 usersTable: string
64 postsTable: string
65 commentsTable: string
66 dropTables: () => Promise<void>
67}>({
68 usersTable: async ({ dbClient, tableName, task }, use) => {
69 const name = tableName('users')
70 const taskFile = task.file.name.replace(/'/g, '`')
71 const taskName = task.name.replace(/'/g, '`')
72​
73 await dbClient.query(`
74 DROP TABLE IF EXISTS ${name};
75 CREATE TABLE ${name} (
76 id UUID PRIMARY KEY,
77 name TEXT NOT NULL,
78 email TEXT,
79 age INTEGER NOT NULL,
80 is_active BOOLEAN NOT NULL DEFAULT true,
81 created_at TIMESTAMP NOT NULL DEFAULT NOW(),
82 metadata JSONB,
83 deleted_at TIMESTAMP
84 );
85 COMMENT ON TABLE ${name} IS 'Created for ${taskFile} - ${taskName}';
86 `)
87​
88 await use(name)
89​
90 try {
91 await dbClient.query(`DROP TABLE IF EXISTS ${name}`)
92 } catch (error) {
93 console.error(`Error dropping table ${name}:`, error)
94 }
95 },
96​
97 // eslint-disable-next-line @typescript-eslint/no-unused-vars
98 postsTable: async ({ dbClient, tableName, usersTable, task }, use) => {
99 const name = tableName('posts')
100 const taskFile = task.file.name.replace(/'/g, '`')
101 const taskName = task.name.replace(/'/g, '`')
102​
103 await dbClient.query(`
104 DROP TABLE IF EXISTS ${name};
105 CREATE TABLE ${name} (
106 id UUID PRIMARY KEY,
107 user_id UUID NOT NULL,
108 title TEXT NOT NULL,
109 content TEXT,
110 view_count INTEGER NOT NULL DEFAULT 0,
111 published_at TIMESTAMP,
112 deleted_at TIMESTAMP
113 );
114 COMMENT ON TABLE ${name} IS 'Created for ${taskFile} - ${taskName}';
115 `)
116​
117 await use(name)
118​
119 try {
120 await dbClient.query(`DROP TABLE IF EXISTS ${name}`)
121 } catch (error) {
122 console.error(`Error dropping table ${name}:`, error)
123 }
124 },
125​
126 commentsTable: async (
127 // eslint-disable-next-line @typescript-eslint/no-unused-vars
128 { dbClient, tableName, postsTable, usersTable, task },
129 use,
130 ) => {
131 const name = tableName('comments')
132 const taskFile = task.file.name.replace(/'/g, '`')
133 const taskName = task.name.replace(/'/g, '`')
134​
135 await dbClient.query(`
136 DROP TABLE IF EXISTS ${name};
137 CREATE TABLE ${name} (
138 id UUID PRIMARY KEY,
139 post_id UUID NOT NULL,
140 user_id UUID NOT NULL,
141 text TEXT NOT NULL,
142 created_at TIMESTAMP NOT NULL DEFAULT NOW(),
143 deleted_at TIMESTAMP
144 );
145 COMMENT ON TABLE ${name} IS 'Created for ${taskFile} - ${taskName}';
146 `)
147​
148 await use(name)
149​
150 try {
151 await dbClient.query(`DROP TABLE IF EXISTS ${name}`)
152 } catch (error) {
153 console.error(`Error dropping table ${name}:`, error)
154 }
155 },
156​
157 dropTables: async (
158 { dbClient, usersTable, postsTable, commentsTable },
159 use,
160 ) => {
161 await use(async () => {
162 try {
163 await dbClient.query(`DROP TABLE IF EXISTS ${commentsTable}`)
164 await dbClient.query(`DROP TABLE IF EXISTS ${postsTable}`)
165 await dbClient.query(`DROP TABLE IF EXISTS ${usersTable}`)
166 } catch (error) {
167 console.error('Error dropping tables:', error)
168 }
169 })
170 },
171})
172​
173/**
174 * Extended fixture with seeded test data
175 */
176export const testWithSeedData = testWithTables.extend<{
177 seedData: SeedDataResult
178 insertSeedData: () => Promise<void>
179}>({
180 // eslint-disable-next-line no-empty-pattern
181 seedData: async ({}, use) => {
182 const seed = generateSeedData()
183 await use(seed)
184 },
185​
186 insertSeedData: async (
187 { dbClient, usersTable, postsTable, commentsTable, seedData },
188 use,
189 ) => {
190 await use(async () => {
191 // Insert users
192 for (const user of seedData.users) {
193 await dbClient.query(
194 `INSERT INTO ${usersTable} (id, name, email, age, is_active, created_at, metadata, deleted_at)
195 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
196 [
197 user.id,
198 user.name,
199 user.email,
200 user.age,
201 user.isActive,
202 user.createdAt,
203 user.metadata ? JSON.stringify(user.metadata) : null,
204 user.deletedAt,
205 ],
206 )
207 }
208​
209 // Insert posts
210 for (const post of seedData.posts) {
211 await dbClient.query(
212 `INSERT INTO ${postsTable} (id, user_id, title, content, view_count, published_at, deleted_at)
213 VALUES ($1, $2, $3, $4, $5, $6, $7)`,
214 [
215 post.id,
216 post.userId,
217 post.title,
218 post.content,
219 post.viewCount,
220 post.publishedAt,
221 post.deletedAt,
222 ],
223 )
224 }
225​
226 // Insert comments
227 for (const comment of seedData.comments) {
228 await dbClient.query(
229 `INSERT INTO ${commentsTable} (id, post_id, user_id, text, created_at, deleted_at)
230 VALUES ($1, $2, $3, $4, $5, $6)`,
231 [
232 comment.id,
233 comment.postId,
234 comment.userId,
235 comment.text,
236 comment.createdAt,
237 comment.deletedAt,
238 ],
239 )
240 }
241 })
242 },
243})