-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathhandler.test.ts
More file actions
207 lines (170 loc) · 6.15 KB
/
handler.test.ts
File metadata and controls
207 lines (170 loc) · 6.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { StarbaseDB } from './handler'
import type { DataSource } from './types'
import { Hono } from 'hono'
import { executeQuery, executeTransaction } from './operation'
import { LiteREST } from './literest'
import { createResponse } from './utils'
import { corsPreflight } from './cors'
import { StarbasePluginRegistry } from './plugin'
vi.mock('./cors', () => ({
corsPreflight: vi.fn().mockReturnValue(new Response(null, { status: 204 })),
}))
const mockExecutionContext = {
waitUntil: vi.fn(),
} as unknown as ExecutionContext
vi.mock('hono', () => {
return {
Hono: vi.fn().mockImplementation(() => ({
use: vi.fn(),
post: vi.fn(),
get: vi.fn(),
all: vi.fn(),
fetch: vi.fn().mockResolvedValue(new Response('mock-response')),
notFound: vi.fn(),
onError: vi.fn(),
})),
}
})
vi.mock('./operation', () => ({
executeQuery: vi.fn().mockResolvedValue('mock-query-result'),
executeTransaction: vi.fn().mockResolvedValue('mock-transaction-result'),
}))
vi.mock('./literest', () => ({
LiteREST: vi.fn().mockImplementation(() => ({
handleRequest: vi
.fn()
.mockResolvedValue(new Response('mock-rest-response')),
})),
}))
vi.mock('./plugin', () => ({
StarbasePluginRegistry: vi.fn().mockImplementation(() => ({
init: vi.fn(),
})),
}))
vi.mock('./utils', async () => {
const { getFeatureFromConfig } = await import('./utils')
return {
createResponse: vi.fn((result, error, status) => ({
result,
error,
status,
})),
getFeatureFromConfig,
}
})
let instance: StarbaseDB
let mockDataSource: DataSource
let mockConfig: any
beforeEach(() => {
mockConfig = {
role: 'admin' as 'admin' | 'client',
features: { rest: true, export: true, import: true },
}
const mockExecuteQuery = vi.fn().mockResolvedValue([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
]) as unknown as DataSource['rpc']['executeQuery']
;(mockExecuteQuery as any)[Symbol.dispose] = vi.fn()
mockDataSource = {
source: 'internal',
rpc: {
executeQuery: mockExecuteQuery,
} as any,
}
instance = new StarbaseDB({
dataSource: mockDataSource,
config: mockConfig,
})
vi.clearAllMocks()
})
describe('StarbaseDB Initialization', () => {
it('should initialize with given data source and config', () => {
expect(instance).toBeDefined()
expect(instance['dataSource']).toBe(mockDataSource)
expect(instance['config']).toBe(mockConfig)
})
it('should get feature flag correctly', () => {
expect(instance['getFeature']('rest')).toBe(true)
expect(instance['getFeature']('export')).toBe(true)
})
})
describe('StarbaseDB Middleware & Request Handling', () => {
it('should correctly handle CORS preflight', async () => {
const request = new Request('https://example.com', {
method: 'OPTIONS',
})
const response = await instance.handle(request, mockExecutionContext)
expect(corsPreflight).toHaveBeenCalled()
expect(response.status).toBe(204)
})
it('should fetch using Hono app', async () => {
const request = new Request('https://example.com/api/test')
const response = await instance.handle(request, mockExecutionContext)
expect(instance['app'].fetch).toHaveBeenCalledWith(request)
expect(response).toBeDefined()
})
})
describe('StarbaseDB Query Execution', () => {
it('should execute a valid SQL query', async () => {
const request = new Request('https://example.com/query', {
method: 'POST',
body: JSON.stringify({ sql: 'SELECT * FROM users' }),
headers: { 'Content-Type': 'application/json' },
})
const response = await instance.queryRoute(request, false)
expect(executeQuery).toHaveBeenCalledWith({
sql: 'SELECT * FROM users',
params: undefined,
isRaw: false,
dataSource: mockDataSource,
config: mockConfig,
})
expect(response.status).toBe(200)
})
it('should return 400 if SQL query is invalid', async () => {
const request = new Request('https://example.com/query', {
method: 'POST',
body: JSON.stringify({ sql: '' }),
headers: { 'Content-Type': 'application/json' },
})
const response = await instance.queryRoute(request, false)
expect(response.status).toBe(400)
})
it('should execute a SQL transaction', async () => {
const request = new Request('https://example.com/query', {
method: 'POST',
body: JSON.stringify({
transaction: [{ sql: "INSERT INTO users VALUES (1, 'Alice')" }],
}),
headers: { 'Content-Type': 'application/json' },
})
const response = await instance.queryRoute(request, false)
expect(executeTransaction).toHaveBeenCalled()
expect(response.status).toBe(200)
})
})
describe('StarbaseDB Cache Expiry', () => {
it('should remove expired cache entries', async () => {
await instance['expireCache']()
expect(mockDataSource.rpc.executeQuery).toHaveBeenCalledWith({
sql: 'DELETE FROM tmp_cache WHERE timestamp + (ttl * 1000) < ?',
params: [expect.any(Number)],
})
})
})
describe('StarbaseDB Error Handling', () => {
it('should return 500 if query execution fails', async () => {
vi.mocked(executeQuery).mockRejectedValue(new Error('Database error'))
const request = new Request('https://example.com/query', {
method: 'POST',
body: JSON.stringify({ sql: 'INVALID SQL' }),
headers: { 'Content-Type': 'application/json' },
})
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {})
const response = await instance.queryRoute(request, false)
expect(response.status).toBe(500)
})
})