The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/add unit tests to lib 150525 (#35689)
Joshen Lim2e88716266bc
diff --git a/apps/studio/lib/eszip-parser.test.ts b/apps/studio/lib/eszip-parser.test.tsnew file mode 100644index 00000000000..4577549e85c--- /dev/null+++ b/apps/studio/lib/eszip-parser.test.ts@@ -0,0 +1,119 @@+import { Parser } from '@deno/eszip'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { parseEszip } from './eszip-parser'++vi.mock('@deno/eszip', () => ({+ Parser: {+ createInstance: vi.fn(),+ },+}))++vi.stubGlobal(+ 'File',+ class MockFile {+ name: string+ content: string++ constructor(content: string[], name: string) {+ this.name = name+ this.content = content[0]+ }++ async text() {+ return this.content+ }+ }+)++vi.stubGlobal(+ 'URL',+ class MockURL {+ pathname: string++ constructor(url: string) {+ this.pathname = url+ }+ }+)++describe('eszip-parser', () => {+ const mockParser = {+ parseBytes: vi.fn(),+ load: vi.fn(),+ getModuleSource: vi.fn(),+ }++ beforeEach(() => {+ vi.clearAllMocks()+ ;(Parser.createInstance as any).mockResolvedValue(mockParser)+ })++ afterEach(() => {+ vi.resetAllMocks()+ })++ describe('parseEszip', () => {+ it('should successfully parse and extract files from eszip', async () => {+ const mockBytes = new Uint8Array([1, 2, 3])+ const mockSpecifiers = ['file1.ts', 'file2.ts']+ const mockModuleSource1 = 'export const hello = "world"'+ const mockModuleSource2 = 'export const foo = "bar"'++ mockParser.parseBytes.mockResolvedValue(mockSpecifiers)+ mockParser.load.mockResolvedValue(undefined)+ mockParser.getModuleSource+ .mockResolvedValueOnce(mockModuleSource1)+ .mockResolvedValueOnce(mockModuleSource2)++ const result = await parseEszip(mockBytes)++ expect(Parser.createInstance).toHaveBeenCalledTimes(1)+ expect(mockParser.parseBytes).toHaveBeenCalledWith(mockBytes)+ expect(mockParser.load).toHaveBeenCalled()+ expect(result).toHaveLength(2)+ expect(result[0]).toEqual({+ name: 'file1.ts',+ content: mockModuleSource1,+ })+ expect(result[1]).toEqual({+ name: 'file2.ts',+ content: mockModuleSource2,+ })+ })++ it('should handle parseBytes failure', async () => {+ mockParser.parseBytes.mockRejectedValue(new Error('Parse error'))+ await expect(parseEszip(new Uint8Array())).rejects.toThrow('Parse error')+ })++ it('should handle load failure', async () => {+ mockParser.parseBytes.mockResolvedValue(['file1.ts'])+ mockParser.load.mockRejectedValue(new Error('Load error'))++ await expect(parseEszip(new Uint8Array())).rejects.toThrow('Load error')+ })++ it('should filter out unwanted specifiers', async () => {+ const mockBytes = new Uint8Array([1, 2, 3])+ const mockSpecifiers = [+ 'file1.ts',+ 'npm:package',+ 'https://example.com/file.ts',+ 'file2.ts',+ '---internal',+ 'jsr:package',+ ]+ const mockModuleSource = 'export const test = "test"'++ mockParser.parseBytes.mockResolvedValue(mockSpecifiers)+ mockParser.load.mockResolvedValue(undefined)+ mockParser.getModuleSource.mockResolvedValue(mockModuleSource)++ const result = await parseEszip(mockBytes)+ // Only file1.ts and file2.ts should be included+ expect(result).toHaveLength(2)+ expect(result[0].name).toBe('file1.ts')+ expect(result[1].name).toBe('file2.ts')+ })+ })+})diff --git a/apps/studio/lib/formatSql.test.ts b/apps/studio/lib/formatSql.test.tsindex 841d64e82e3..0412dd2d8e7 100644--- a/apps/studio/lib/formatSql.test.ts+++ b/apps/studio/lib/formatSql.test.ts@@ -1,5 +1,5 @@+import { describe, expect, it } from 'vitest'import { formatSql } from './formatSql'-import { describe, it, expect } from 'vitest'describe('formatSql', () => {it('should format SQL', () => {@@ -13,7 +13,11 @@ fromit('should return the original argument if it is not valid, not throw', () => {const result = formatSql('123')-expect(result).toBe('123')})++ it('should return the original argument if it is not valid, not throw', () => {+ const result = formatSql('select {col1}, {col2} from {tableName};')+ expect(result).toBe('select {col1}, {col2} from {tableName};')+ })})diff --git a/apps/studio/lib/integration-utils.test.ts b/apps/studio/lib/integration-utils.test.tsnew file mode 100644index 00000000000..03f82051f33--- /dev/null+++ b/apps/studio/lib/integration-utils.test.ts@@ -0,0 +1,261 @@+import type {+ GitHubAccount,+ Integration,+ VercelAccount,+ VercelTeamAccount,+} from 'data/integrations/integrations.types'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import {+ getInitialMigrationSQLFromGitHubRepo,+ getIntegrationConfigurationUrl,+} from './integration-utils'++vi.mock('data/fetchers', () => ({+ fetchHandler: vi.fn(),+}))++describe('integration-utils', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('getInitialMigrationSQLFromGitHubRepo', () => {+ it('should return null when no externalId is provided', async () => {+ const result = await getInitialMigrationSQLFromGitHubRepo()+ expect(result).toBeNull()+ })++ it('should fetch and combine migration files correctly', async () => {+ const mockGitHubUrl = 'https://github.com/org/repo/tree/main/examples/with-supabase'+ const mockSupabaseFiles = [{ name: 'seed.sql', download_url: 'https://github.com/seed.sql' }]+ const mockMigrationFiles = [+ { name: '20230101000000_initial.sql', download_url: 'https://github.com/migration1.sql' },+ { name: '20230101000001_second.sql', download_url: 'https://github.com/migration2.sql' },+ ]++ const mockMigrationContent1 = 'CREATE TABLE users (id serial PRIMARY KEY);'+ const mockMigrationContent2 = 'CREATE TABLE posts (id serial PRIMARY KEY);'+ const mockSeedContent = 'INSERT INTO users (id) VALUES (1);'++ // Mock the fetch responses+ const { fetchHandler } = await import('data/fetchers')+ const mockFetchHandler = fetchHandler as unknown as ReturnType<typeof vi.fn>+ mockFetchHandler+ .mockResolvedValueOnce(+ new Response(JSON.stringify(mockSupabaseFiles), {+ status: 200,+ statusText: 'OK',+ headers: { 'Content-Type': 'application/json' },+ })+ )+ .mockResolvedValueOnce(+ new Response(JSON.stringify(mockMigrationFiles), {+ status: 200,+ statusText: 'OK',+ headers: { 'Content-Type': 'application/json' },+ })+ )+ .mockResolvedValueOnce(+ new Response(mockSeedContent, {+ status: 200,+ statusText: 'OK',+ headers: { 'Content-Type': 'text/plain' },+ })+ )+ .mockResolvedValueOnce(+ new Response(mockMigrationContent1, {+ status: 200,+ statusText: 'OK',+ headers: { 'Content-Type': 'text/plain' },+ })+ )+ .mockResolvedValueOnce(+ new Response(mockMigrationContent2, {+ status: 200,+ statusText: 'OK',+ headers: { 'Content-Type': 'text/plain' },+ })+ )++ const result = await getInitialMigrationSQLFromGitHubRepo(mockGitHubUrl)++ expect(result).toContain(mockMigrationContent1)+ expect(result).toContain(mockMigrationContent2)+ expect(result).toContain(mockSeedContent)+ expect(result).toContain('create schema if not exists supabase_migrations')+ expect(result).toContain('create table if not exists supabase_migrations.schema_migrations')+ })++ it('should handle GitHub API errors gracefully', async () => {+ const mockGitHubUrl = 'https://github.com/org/repo/tree/main/examples/with-supabase'++ const { fetchHandler } = await import('data/fetchers')+ const mockFetchHandler = fetchHandler as unknown as ReturnType<typeof vi.fn>++ mockFetchHandler+ .mockResolvedValueOnce(+ new Response(null, {+ status: 404,+ statusText: 'Not Found',+ headers: { 'Content-Type': 'application/json' },+ })+ )+ .mockResolvedValueOnce(+ new Response(null, {+ status: 404,+ statusText: 'Not Found',+ headers: { 'Content-Type': 'application/json' },+ })+ )++ const result = await getInitialMigrationSQLFromGitHubRepo(mockGitHubUrl)+ expect(result).toBeNull()+ })+ })++ describe('getIntegrationConfigurationUrl', () => {+ it('should return correct Vercel configuration URL for personal account', () => {+ const vercelIntegration: Integration = {+ id: '123',+ added_by: {+ username: 'testuser',+ id: '123',+ primary_email: '[email protected]',+ },+ inserted_at: '2024-01-01',+ updated_at: '2024-01-01',+ connections: [],+ organization: { slug: 'org' },+ integration: { name: 'Vercel' },+ metadata: {+ account: {+ type: 'Personal',+ name: 'Test User',+ avatar: 'test-avatar',+ source: 'marketplace',+ owner_id: '123',+ } as VercelAccount,+ configuration_id: '123',+ },+ }++ const result = getIntegrationConfigurationUrl(vercelIntegration)+ expect(result).toBe('https://vercel.com/dashboard/integrations/123')+ })++ it('should return correct Vercel configuration URL for team account', () => {+ const vercelIntegration: Integration = {+ id: '123',+ added_by: {+ username: 'testuser',+ id: '123',+ primary_email: '[email protected]',+ },+ inserted_at: '2024-01-01',+ updated_at: '2024-01-01',+ connections: [],+ organization: { slug: 'org' },+ integration: { name: 'Vercel' },+ metadata: {+ account: {+ type: 'Team',+ name: 'Test Team',+ avatar: 'test-avatar',+ source: 'marketplace',+ owner_id: '123',+ team_id: 'team123',+ team_slug: 'my-team',+ } as VercelTeamAccount,+ configuration_id: '123',+ },+ }++ const result = getIntegrationConfigurationUrl(vercelIntegration)+ expect(result).toBe('https://vercel.com/dashboard/my-team/integrations/123')+ })++ it('should return correct GitHub configuration URL for personal account', () => {+ const githubIntegration: Integration = {+ id: '456',+ added_by: {+ username: 'testuser',+ id: '123',+ primary_email: '[email protected]',+ },+ inserted_at: '2024-01-01',+ updated_at: '2024-01-01',+ connections: [],+ organization: { slug: 'org' },+ integration: { name: 'GitHub' },+ metadata: {+ account: {+ type: 'User',+ name: 'Test User',+ avatar: 'test-avatar',+ installed_by_user_id: 123,+ } as GitHubAccount,+ installation_id: 456,+ },+ }++ const result = getIntegrationConfigurationUrl(githubIntegration)+ expect(result).toBe('https://github.com/settings/installations/456')+ })++ it('should return correct GitHub configuration URL for organization', () => {+ const githubIntegration: Integration = {+ id: '456',+ added_by: {+ username: 'testuser',+ id: '123',+ primary_email: '[email protected]',+ },+ inserted_at: '2024-01-01',+ updated_at: '2024-01-01',+ connections: [],+ organization: { slug: 'org' },+ integration: { name: 'GitHub' },+ metadata: {+ account: {+ type: 'Organization',+ name: 'org-name',+ avatar: 'test-avatar',+ installed_by_user_id: 123,+ } as GitHubAccount,+ installation_id: 456,+ },+ }++ const result = getIntegrationConfigurationUrl(githubIntegration)+ expect(result).toBe('https://github.com/organizations/org-name/settings/installations/456')+ })++ it('should return empty string for unknown integration', () => {+ const unknownIntegration = {+ id: '789',+ added_by: {+ username: 'testuser',+ id: '123',+ primary_email: '[email protected]',+ },+ inserted_at: '2024-01-01',+ updated_at: '2024-01-01',+ connections: [],+ organization: { slug: 'org' },+ integration: { name: 'Unknown' as any },+ metadata: {+ account: {+ type: 'User',+ name: 'Test User',+ avatar: 'test-avatar',+ installed_by_user_id: 123,+ } as GitHubAccount,+ installation_id: 789,+ },+ } as Integration++ const result = getIntegrationConfigurationUrl(unknownIntegration)+ expect(result).toBe('')+ })+ })+})diff --git a/apps/studio/lib/logs.ts b/apps/studio/lib/logs.tsdeleted file mode 100644index 85621dea74f..00000000000--- a/apps/studio/lib/logs.ts+++ /dev/null@@ -1,18 +0,0 @@-export function filterFunctionsRequestResponse(re: any) {- return Object.fromEntries(- Object.entries(re)- .filter(([key]) => !['host', 'url'].includes(key))- .map(([key, value]) => {- if (key === 'headers') {- return [- key,- (value as any[]).map((headers) =>- Object.fromEntries(Object.entries(headers).filter(([key]) => !key.startsWith('_')))- ),- ]- }-- return [key, value]- })- )-}diff --git a/apps/studio/lib/role-impersonation.test.ts b/apps/studio/lib/role-impersonation.test.tsindex 1c2b64b8bb8..7b19032a555 100644--- a/apps/studio/lib/role-impersonation.test.ts+++ b/apps/studio/lib/role-impersonation.test.ts@@ -1,7 +1,12 @@-import { describe, it, expect } from 'vitest'-import { getPostgrestClaims } from './role-impersonation'+import { describe, expect, it } from 'vitest'+import type { RoleImpersonationState } from './role-impersonation'+import {+ getExp1HourFromNow,+ getPostgrestClaims,+ wrapWithRoleImpersonation,+} from './role-impersonation'-const baseUser = {+const createBaseUser = (overrides = {}) => ({id: 'user123',email: '[email protected]',phone: undefined,@@ -9,65 +14,217 @@ const baseUser = {is_anonymous: false,raw_app_meta_data: { provider: 'email' },raw_user_meta_data: { name: 'Tester' },-}+ ...overrides,+})++const createTestClaims = (overrides = {}) => ({+ ref: 'test-project',+ exp: getExp1HourFromNow(),+ iat: Math.floor(Date.now() / 1000),+ iss: 'https://test-project.supabase.co/auth/v1',+ role: 'authenticated' as const,+ ...overrides,+})++describe('getExp1HourFromNow', () => {+ it('returns a timestamp 1 hour in the future', () => {+ const now = Math.floor(Date.now() / 1000)+ const exp = getExp1HourFromNow()+ expect(exp).toBeGreaterThan(now)+ expect(exp).toBeLessThanOrEqual(now + 3600)+ })+})describe('getPostgrestClaims', () => {- it('returns native user claims', () => {- const claims = getPostgrestClaims('test-project', {- type: 'postgrest',- role: 'authenticated',- userType: 'native',- user: baseUser as any,+ describe('native user claims', () => {+ it('returns basic user claims', () => {+ const claims = getPostgrestClaims('test-project', {+ type: 'postgrest',+ role: 'authenticated',+ userType: 'native',+ user: createBaseUser() as any,+ })++ expect(claims.aud).toBe('authenticated')+ expect(claims.email).toBe('[email protected]')+ expect(claims.sub).toBe('user123')})- expect(claims.aud).toBe('authenticated')- expect(claims.email).toBe('[email protected]')- expect(claims.sub).toBe('user123')+ it('handles missing user data gracefully', () => {+ const claims = getPostgrestClaims('test-project', {+ type: 'postgrest',+ role: 'authenticated',+ userType: 'native',+ } as any)++ expect(claims.role).toBe('authenticated')+ expect(claims.ref).toBe('test-project')+ })})- it('returns external user claims', () => {- const claims = getPostgrestClaims('test-project', {- type: 'postgrest',- role: 'authenticated',- userType: 'external',- externalAuth: {- sub: 'ext123',- additionalClaims: { foo: 'bar' },- },+ describe('external user claims', () => {+ it('returns claims with additional data', () => {+ const claims = getPostgrestClaims('test-project', {+ type: 'postgrest',+ role: 'authenticated',+ userType: 'external',+ externalAuth: {+ sub: 'ext123',+ additionalClaims: { foo: 'bar', custom: 'value' },+ },+ })++ expect(claims.sub).toBe('ext123')+ expect((claims as any).foo).toBe('bar')+ expect((claims as any).custom).toBe('value')})- expect(claims.sub).toBe('ext123')- expect((claims as any).foo).toBe('bar')+ it('handles missing additional claims', () => {+ const claims = getPostgrestClaims('test-project', {+ type: 'postgrest',+ role: 'authenticated',+ userType: 'external',+ externalAuth: {+ sub: 'ext123',+ },+ })++ expect(claims.sub).toBe('ext123')+ expect((claims as any).foo).toBeUndefined()+ })})- it('returns basic claims for anon role', () => {- const claims = getPostgrestClaims('test-project', {- type: 'postgrest',- role: 'anon',+ describe('system roles', () => {+ 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')})- 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 basic claims for service_role', () => {- const claims = getPostgrestClaims('test-project', {- type: 'postgrest',- role: 'service_role',+describe('wrapWithRoleImpersonation', () => {+ const sql = 'select * from colors;'+ const ref = 'default'++ describe('postgres role (undefined)', () => {+ it('returns SQL as is when no role is selected', () => {+ const roleImpersonationState: RoleImpersonationState = {+ role: undefined,+ claims: undefined,+ }+ const result = wrapWithRoleImpersonation(sql, roleImpersonationState)+ expect(result).toBe(sql)})+ })++ describe('anon role', () => {+ it('wraps SQL with anon user configuration', () => {+ const claims = createTestClaims({+ iss: 'supabase',+ ref,+ role: 'anon' as const,+ })++ const roleImpersonationState: RoleImpersonationState = {+ role: { type: 'postgrest', role: 'anon' },+ claims,+ }+ const result = wrapWithRoleImpersonation(sql, roleImpersonationState)- expect(claims.role).toBe('service_role')- expect(claims.ref).toBe('test-project')+ expect(result).toContain("set_config('role', 'anon', true)")+ expect(result).toContain('request.jwt.claims')+ expect(result).toContain('ROLE_IMPERSONATION_NO_RESULTS')+ expect(result).toContain(sql)+ })})- it('returns fallback claims if native user is missing', () => {- const claims = getPostgrestClaims('test-project', {- type: 'postgrest',- role: 'authenticated',- userType: 'native',- } as any)+ describe('authenticated user', () => {+ it('wraps SQL with native user configuration', () => {+ const claims = createTestClaims({+ iss: `https://${ref}.supabase.co/auth/v1`,+ role: 'authenticated' as const,+ })++ const roleImpersonationState: RoleImpersonationState = {+ role: {+ type: 'postgrest',+ role: 'authenticated',+ aal: 'aal1',+ userType: 'native',+ user: {+ email: '[email protected]',+ id: 'abc',+ providers: [],+ },+ },+ claims,+ }+ const result = wrapWithRoleImpersonation(sql, roleImpersonationState)++ expect(result).toContain("set_config('role', 'authenticated', true)")+ expect(result).toContain('request.jwt.claims')+ expect(result).toContain('ROLE_IMPERSONATION_NO_RESULTS')+ expect(result).toContain(sql)+ })- expect(claims.role).toBe('authenticated')- expect(claims.ref).toBe('test-project')+ it('wraps SQL with external user configuration', () => {+ const claims = createTestClaims({+ aal: 'aal1' as const,+ aud: 'authenticated',+ role: 'authenticated' as const,+ session_id: 'ecab6bfd-3707-4e63-9b3b-d37af69449d9',+ sub: 'user123',+ })++ const roleImpersonationState: RoleImpersonationState = {+ role: {+ type: 'postgrest',+ role: 'authenticated',+ userType: 'external',+ externalAuth: {+ sub: 'user123',+ additionalClaims: {},+ },+ aal: 'aal1',+ },+ claims,+ }+ const result = wrapWithRoleImpersonation(sql, roleImpersonationState)++ expect(result).toContain("set_config('role', 'authenticated', true)")+ expect(result).toContain('request.jwt.claims')+ expect(result).toContain('ROLE_IMPERSONATION_NO_RESULTS')+ expect(result).toContain(sql)+ })+ })++ describe('custom role', () => {+ it('wraps SQL with custom role configuration', () => {+ const customRole = 'test'+ const roleImpersonationState: RoleImpersonationState = {+ role: { type: 'custom', role: customRole },+ claims: undefined,+ }+ const result = wrapWithRoleImpersonation(sql, roleImpersonationState)++ expect(result).toContain(`set local role '${customRole}'`)+ expect(result).toContain('ROLE_IMPERSONATION_NO_RESULTS')+ expect(result).toContain(sql)+ })})})diff --git a/apps/studio/lib/role-impersonation.ts b/apps/studio/lib/role-impersonation.tsindex 44a47eb59d3..29b45427c76 100644--- a/apps/studio/lib/role-impersonation.ts+++ b/apps/studio/lib/role-impersonation.ts@@ -1,7 +1,6 @@import type { User } from 'data/auth/users-infinite-query'import { RoleImpersonationState as ValtioRoleImpersonationState } from 'state/role-impersonation-state'import { uuidv4 } from './helpers'-import type { INTERNAL_Snapshot } from 'valtio'type PostgrestImpersonationRole =| {@@ -39,7 +38,7 @@ export type CustomImpersonationRole = {export type ImpersonationRole = PostgrestImpersonationRole | CustomImpersonationRole-function getExp1HourFromNow() {+export function getExp1HourFromNow() {return Math.floor((Date.now() + 60 * 60 * 1000) / 1000)}@@ -100,11 +99,11 @@ function getPostgrestRoleImpersonationSql(const unexpiredClaims = { ...claims, exp: getExp1HourFromNow() }return `- select set_config('role', '${role.role}', true),- set_config('request.jwt.claims', '${JSON.stringify(unexpiredClaims).replaceAll("'", "''")}', true),- set_config('request.method', 'POST', true),- set_config('request.path', '/impersonation-example-request-path', true),- set_config('request.headers', '{"accept": "*/*"}', true);+select set_config('role', '${role.role}', true),+set_config('request.jwt.claims', '${JSON.stringify(unexpiredClaims).replaceAll("'", "''")}', true),+set_config('request.method', 'POST', true),+set_config('request.path', '/impersonation-example-request-path', true),+set_config('request.headers', '{"accept": "*/*"}', true);`.trim()}@@ -115,7 +114,7 @@ export const ROLE_IMPERSONATION_NO_RESULTS = 'ROLE_IMPERSONATION_NO_RESULTS'function getCustomRoleImpersonationSql(roleName: string) {return /* SQL */ `set local role '${roleName}';- `+ `.trim()}export type RoleImpersonationState = Pick<ValtioRoleImpersonationState, 'role' | 'claims'>@@ -142,7 +141,7 @@ export function wrapWithRoleImpersonation(sql: string, state?: RoleImpersonationselect 1 as "${ROLE_IMPERSONATION_NO_RESULTS}";${sql}- `+ `.trim()}function encodeText(data: string) {