Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

More lib tests (#35596)

Terry Sutton44bf505aa8b3
diff --git a/apps/studio/lib/posthog.test.ts b/apps/studio/lib/posthog.test.ts
new file mode 100644
index 00000000000..04ec27b7d50
--- /dev/null
+++ b/apps/studio/lib/posthog.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import * as fetchers from 'data/fetchers'
+import * as common from 'common'
+import * as constants from './constants'
+import { trackFeatureFlag } from './posthog'
+
+vi.mock('data/fetchers', () => ({
+ post: vi.fn(),
+ handleError: vi.fn(),
+}))
+vi.mock('common', () => ({
+ hasConsented: vi.fn(),
+ LOCAL_STORAGE_KEYS: {},
+}))
+vi.mock('./constants', () => ({
+ IS_PLATFORM: true,
+}))
+
+describe('trackFeatureFlag', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('returns undefined if user has not consented', async () => {
+ vi.spyOn(common, 'hasConsented').mockReturnValue(false)
+ const result = await trackFeatureFlag({ some: 'value' } as any)
+ expect(result).toBeUndefined()
+ })
+
+ it('returns undefined if not on platform', async () => {
+ vi.spyOn(common, 'hasConsented').mockReturnValue(true)
+ vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(false)
+ const result = await trackFeatureFlag({ some: 'value' } as any)
+ expect(result).toBeUndefined()
+ })
+
+ it('calls post with correct body if consented and on platform', async () => {
+ vi.spyOn(common, 'hasConsented').mockReturnValue(true)
+ vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(true)
+ vi.spyOn(fetchers, 'post').mockResolvedValue({ data: 'success' })
+
+ const result = await trackFeatureFlag({ foo: 'bar' } as any)
+
+ expect(fetchers.post).toHaveBeenCalledWith('/platform/telemetry/feature-flags/track', {
+ body: { foo: 'bar' },
+ })
+ expect(result).toBe('success')
+ })
+
+ it('calls handleError if post returns error', async () => {
+ vi.spyOn(common, 'hasConsented').mockReturnValue(true)
+ vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(true)
+ vi.spyOn(fetchers, 'post').mockResolvedValue({ error: { message: 'fail' } })
+
+ await trackFeatureFlag({ foo: 'bar' } as any)
+
+ expect(fetchers.handleError).toHaveBeenCalledWith({ message: 'fail' })
+ })
+})
diff --git a/apps/studio/lib/role-impersonation.test.ts b/apps/studio/lib/role-impersonation.test.ts
new file mode 100644
index 00000000000..1c2b64b8bb8
--- /dev/null
+++ b/apps/studio/lib/role-impersonation.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest'
+import { getPostgrestClaims } from './role-impersonation'
+
+const baseUser = {
+ id: 'user123',
+ email: '[email protected]',
+ phone: undefined,
+ role: 'authenticated',
+ is_anonymous: false,
+ raw_app_meta_data: { provider: 'email' },
+ raw_user_meta_data: { name: 'Tester' },
+}
+
+describe('getPostgrestClaims', () => {
+ it('returns native user claims', () => {
+ const claims = getPostgrestClaims('test-project', {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ user: baseUser as any,
+ })
+
+ expect(claims.aud).toBe('authenticated')
+ expect(claims.email).toBe('[email protected]')
+ expect(claims.sub).toBe('user123')
+ })
+
+ it('returns external user claims', () => {
+ const claims = getPostgrestClaims('test-project', {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ externalAuth: {
+ sub: 'ext123',
+ additionalClaims: { foo: 'bar' },
+ },
+ })
+
+ expect(claims.sub).toBe('ext123')
+ expect((claims as any).foo).toBe('bar')
+ })
+
+ it('returns basic claims for anon role', () => {
+ const claims = getPostgrestClaims('test-project', {
+ type: 'postgrest',
+ role: 'anon',
+ })
+
+ expect(claims.role).toBe('anon')
+ expect(claims.ref).toBe('test-project')
+ })
+
+ it('returns basic claims for service_role', () => {
+ const claims = getPostgrestClaims('test-project', {
+ type: 'postgrest',
+ role: 'service_role',
+ })
+
+ expect(claims.role).toBe('service_role')
+ expect(claims.ref).toBe('test-project')
+ })
+
+ it('returns fallback claims if native user is missing', () => {
+ const claims = getPostgrestClaims('test-project', {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ } as any)
+
+ expect(claims.role).toBe('authenticated')
+ expect(claims.ref).toBe('test-project')
+ })
+})
diff --git a/apps/studio/lib/schemas.test.ts b/apps/studio/lib/schemas.test.ts
new file mode 100644
index 00000000000..e381fc84981
--- /dev/null
+++ b/apps/studio/lib/schemas.test.ts
@@ -0,0 +1,9 @@
+import { describe, it, expect } from 'vitest'
+import { passwordSchema } from './schemas'
+
+describe('passwordSchema', () => {
+ it('validates a basic password', async () => {
+ const result = await passwordSchema.validate({ password: 'ValidPassword123!' })
+ expect(result.password).toBe('ValidPassword123!')
+ })
+})
diff --git a/apps/studio/lib/sql-parameters.test.ts b/apps/studio/lib/sql-parameters.test.ts
new file mode 100644
index 00000000000..5cc66469a5e
--- /dev/null
+++ b/apps/studio/lib/sql-parameters.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest'
+import { parseParameters, processParameterizedSql } from './sql-parameters'
+
+describe('parseParameters', () => {
+ it('parses simple :param without @set', () => {
+ const result = parseParameters('SELECT * FROM table WHERE id = :userId')
+ expect(result).toEqual([
+ {
+ name: 'userId',
+ value: '',
+ defaultValue: undefined,
+ type: undefined,
+ possibleValues: undefined,
+ occurrences: 1,
+ },
+ ])
+ })
+
+ it('parses @set with type and value', () => {
+ const result = parseParameters('@set userId:int = 123\nSELECT * FROM table WHERE id = :userId')
+
+ const userIdParam = result.find((p) => p.name === 'userId')
+ expect(userIdParam?.defaultValue).toBe('123')
+ expect(userIdParam?.type).toBe('int')
+ })
+
+ it('parses union type', () => {
+ const result = parseParameters(
+ '@set status:open|closed = open\nSELECT * FROM users WHERE status = :status'
+ )
+
+ const statusParam = result.find((p) => p.name === 'status')
+ expect(statusParam?.type).toBe('enum')
+ expect(statusParam?.possibleValues).toEqual(['open', 'closed'])
+ })
+
+ it('counts multiple occurrences', () => {
+ const result = parseParameters('SELECT * FROM table WHERE id = :userId OR owner_id = :userId')
+
+ const userIdParam = result.find((p) => p.name === 'userId')
+ expect(userIdParam?.occurrences).toBe(2)
+ })
+})
+
+describe('processParameterizedSql', () => {
+ it('replaces :param with value from parameters', () => {
+ const sql = 'SELECT * FROM users WHERE id = :userId'
+ const result = processParameterizedSql(sql, { userId: '42' })
+ expect(result).toBe('SELECT * FROM users WHERE id = 42')
+ })
+
+ it('uses default from @set if param not provided', () => {
+ const sql = '@set userId:int = 123\nSELECT * FROM users WHERE id = :userId'
+ const result = processParameterizedSql(sql, {})
+ expect(result).toBe('SELECT * FROM users WHERE id = 123')
+ })
+
+ it('overrides @set default if param is provided', () => {
+ const sql = '@set userId:int = 123\nSELECT * FROM users WHERE id = :userId'
+ const result = processParameterizedSql(sql, { userId: '999' })
+ expect(result).toBe('SELECT * FROM users WHERE id = 999')
+ })
+
+ it('throws if no param value is provided and no default exists', () => {
+ const sql = 'SELECT * FROM users WHERE id = :userId'
+ expect(() => processParameterizedSql(sql, {})).toThrowError(
+ 'Missing value for parameter: userId'
+ )
+ })
+
+ it('removes @set lines from final SQL', () => {
+ const sql = '@set status:open|closed = open\nSELECT * FROM items WHERE status = :status'
+ const result = processParameterizedSql(sql, {})
+ expect(result).toBe('SELECT * FROM items WHERE status = open')
+ expect(result).not.toContain('@set')
+ })
+})
diff --git a/apps/studio/lib/upload.test.ts b/apps/studio/lib/upload.test.ts
new file mode 100644
index 00000000000..0862770c55f
--- /dev/null
+++ b/apps/studio/lib/upload.test.ts
@@ -0,0 +1,71 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+import { createClient } from '@supabase/supabase-js'
+import { uploadAttachment } from './upload'
+
+vi.mock('@supabase/supabase-js', () => ({
+ createClient: vi.fn(),
+}))
+
+describe('uploadAttachment', () => {
+ const mockUpload = vi.fn()
+ const mockGetPublicUrl = vi.fn()
+
+ const mockStorage = {
+ from: vi.fn(() => ({
+ upload: mockUpload,
+ getPublicUrl: mockGetPublicUrl,
+ })),
+ }
+
+ const mockSupabaseClient = {
+ storage: mockStorage,
+ }
+
+ const mockFile = new File(['test'], 'test.png', { type: 'image/png' })
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ;(createClient as any).mockReturnValue(mockSupabaseClient)
+ })
+
+ it('uploads file and returns public URL when getUrl is true', async () => {
+ mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
+ mockGetPublicUrl.mockReturnValue({
+ data: { publicUrl: 'https://cdn.supabase.io/folder/test.png' },
+ })
+
+ const url = await uploadAttachment('bucket', 'test.png', mockFile, true)
+
+ expect(createClient).toHaveBeenCalled()
+ expect(mockUpload).toHaveBeenCalledWith('test.png', mockFile, { cacheControl: '3600' })
+ expect(mockGetPublicUrl).toHaveBeenCalledWith('folder/test.png')
+ expect(url).toBe('https://cdn.supabase.io/folder/test.png')
+ })
+
+ it('returns undefined if upload succeeds but getUrl is false', async () => {
+ mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
+
+ const result = await uploadAttachment('bucket', 'test.png', mockFile, false)
+ expect(result).toBeUndefined()
+ })
+
+ it('returns undefined and logs if upload fails', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockUpload.mockResolvedValue({ data: null, error: { message: 'Upload failed' } })
+
+ const result = await uploadAttachment('bucket', 'test.png', mockFile)
+ expect(result).toBeUndefined()
+ expect(errorSpy).toHaveBeenCalledWith('Failed to upload:', { message: 'Upload failed' })
+
+ errorSpy.mockRestore()
+ })
+
+ it('returns undefined if getPublicUrl returns no data', async () => {
+ mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
+ mockGetPublicUrl.mockReturnValue({ data: null })
+
+ const result = await uploadAttachment('bucket', 'test.png', mockFile, true)
+ expect(result).toBeUndefined()
+ })
+})
diff --git a/apps/studio/lib/uuid.test.ts b/apps/studio/lib/uuid.test.ts
new file mode 100644
index 00000000000..6ceeb8bf49a
--- /dev/null
+++ b/apps/studio/lib/uuid.test.ts
@@ -0,0 +1,15 @@
+import { describe, it, expect, vi } from 'vitest'
+import { v4 as _uuidV4 } from 'uuid'
+import uuidv4 from './uuid'
+
+vi.mock('uuid', () => ({
+ v4: vi.fn(() => 'mocked-uuid'),
+}))
+
+describe('uuidv4', () => {
+ it('calls uuid.v4 and returns the result', () => {
+ const result = uuidv4()
+ expect(_uuidV4).toHaveBeenCalled()
+ expect(result).toBe('mocked-uuid')
+ })
+})