d3ro-voice/apps/mobile-rn/__tests__/service-guards.test.ts

220 lines
8.4 KiB
TypeScript

import { LOCALE_CODES, type TranslationKey } from '@d3ro/i18n/shared'
jest.mock('../src/lib/supabase', () => ({
supabase: {
from: jest.fn(),
rpc: jest.fn(),
storage: { from: jest.fn() },
channel: jest.fn(),
removeChannel: jest.fn(async () => 'ok'),
},
}))
import { Dirs, FileSystem } from 'react-native-file-access'
import {
assertRecordWith,
createLabeledUuidAssert,
createUuidAssert,
extractSupabaseErrorInfo,
getTypedSupabaseClient,
isSupabaseAuthFailure,
isSupabaseForbiddenFailure,
isSupabaseNetworkFailure,
parseBoundedStringWith,
parseIsoTimestampWith,
parseSafeIntegerWith,
parseUuidWith,
requireUuidWith,
} from '../src/features/shared/service-guards'
import {
isOwnedCachePath,
localPathFromCacheUri,
removeOwnedCacheFile,
} from '../src/features/shared/owned-cache-files'
import { throwIfPipelineCancelled } from '../src/features/import/abort-guard'
import { AudioPipelineError } from '../src/features/import/audio-import-types'
import { toSpeechLanguageTag } from '../src/lib/locale-speech'
import { resolveMeetingErrorMessage } from '../src/features/meetings/meeting-error-message'
import { MeetingServiceError } from '../src/features/meetings/meetings-service'
class DomainGuardError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
const VALID_UUID_UPPER = '123E4567-E89B-42D3-A456-426614174000'
const VALID_UUID_LOWER = '123e4567-e89b-42d3-a456-426614174000'
const mockFileSystem = FileSystem as typeof FileSystem & { filesystem: Map<string, string> }
describe('shared mobile service guards', () => {
beforeEach(() => {
mockFileSystem.filesystem.clear()
})
test('requireUuidWith_유효하지않은값_도메인에러발생', () => {
const assertId = createUuidAssert(() => new DomainGuardError('auth', 'User required'))
const assertLabeled = createLabeledUuidAssert(
(label) => new DomainGuardError('validation', `Invalid ${label}`),
)
expect(() => assertId('not-a-uuid')).toThrow(new DomainGuardError('auth', 'User required'))
expect(() => assertLabeled(42, 'meeting id')).toThrow(
new DomainGuardError('validation', 'Invalid meeting id'),
)
expect(() => requireUuidWith(VALID_UUID_LOWER, () => new Error('unused'))).not.toThrow()
expect(typeof getTypedSupabaseClient().from).toBe('function')
})
test('parseUuidWith_공백대소문자옵션_정규화및보존검증', () => {
const makeError = () => new DomainGuardError('validation', 'bad-uuid')
expect(parseUuidWith(` ${VALID_UUID_UPPER} `, makeError, { trim: true })).toBe(
VALID_UUID_LOWER,
)
expect(
parseUuidWith(VALID_UUID_UPPER, makeError, { normalizeCase: 'preserve' }),
).toBe(VALID_UUID_UPPER)
expect(() => parseUuidWith(VALID_UUID_UPPER, makeError)).not.toThrow()
expect(() => parseUuidWith(` ${VALID_UUID_UPPER}`, makeError)).toThrow('bad-uuid')
expect(() => parseUuidWith(123, makeError)).toThrow('bad-uuid')
})
test('레코드문자열정수타임스탬프검증기_경계위반시_정확한도메인에러발생', () => {
const makeError = (code: string) => () => new DomainGuardError(code, code)
expect(assertRecordWith({ ok: true }, makeError('not-record'))).toEqual({ ok: true })
expect(() => assertRecordWith(['array'], makeError('not-record'))).toThrow('not-record')
expect(() => assertRecordWith(null, makeError('not-record'))).toThrow('not-record')
expect(parseBoundedStringWith('abc', makeError('str'), { minLength: 2, maxLength: 3 })).toBe(
'abc',
)
expect(() =>
parseBoundedStringWith('a', makeError('str'), { minLength: 2, maxLength: 3 }),
).toThrow('str')
expect(() => parseBoundedStringWith('abcd', makeError('str'), { maxLength: 3 })).toThrow('str')
expect(parseSafeIntegerWith(10, makeError('int'), { min: 1, max: 10 })).toBe(10)
expect(() => parseSafeIntegerWith(10.5, makeError('int'), { min: 0, max: 20 })).toThrow('int')
expect(() => parseSafeIntegerWith(0, makeError('int'), { min: 1, max: 10 })).toThrow('int')
expect(
parseIsoTimestampWith('2026-11-14T00:00:00Z', makeError('ts'), {
requireTimePrefix: true,
normalizeToIso: true,
}),
).toBe('2026-11-14T00:00:00.000Z')
expect(() =>
parseIsoTimestampWith('2026-11-14', makeError('ts'), { requireTimePrefix: true }),
).toThrow('ts')
expect(() => parseIsoTimestampWith('not-a-date', makeError('ts'))).toThrow('ts')
})
test('Supabase에러분류기_네트워크인증권한실패를_정확히식별', () => {
const typeError = new TypeError('Failed to fetch')
const typeInfo = extractSupabaseErrorInfo(typeError, 'fallback')
expect(typeInfo).toEqual({
code: '',
message: 'Failed to fetch',
lower: 'failed to fetch',
})
expect(isSupabaseNetworkFailure(typeError, typeInfo)).toBe(true)
const jwtInfo = extractSupabaseErrorInfo({ code: 'PGRST301', message: 'JWT expired' }, 'fb')
expect(isSupabaseAuthFailure(jwtInfo)).toBe(true)
expect(isSupabaseForbiddenFailure(jwtInfo)).toBe(false)
const rlsInfo = extractSupabaseErrorInfo({ code: '42501', message: 'Permission denied' }, 'fb')
expect(isSupabaseAuthFailure(rlsInfo)).toBe(false)
expect(isSupabaseAuthFailure(rlsInfo, { include42501: true })).toBe(true)
expect(isSupabaseForbiddenFailure(rlsInfo)).toBe(true)
})
})
describe('owned cache files and abort guard', () => {
beforeEach(() => {
mockFileSystem.filesystem.clear()
})
test('removeOwnedCacheFile_캐시경로만삭제하고_경로이탈은거부', async () => {
const ownedPath = `${Dirs.CacheDir}/exports/sample.txt`
mockFileSystem.filesystem.set(ownedPath, 'content')
expect(localPathFromCacheUri('file:///tmp/my%20file.txt')).toBe('/tmp/my file.txt')
expect(localPathFromCacheUri('/raw/path.txt')).toBe('/raw/path.txt')
expect(isOwnedCachePath(ownedPath)).toBe(true)
expect(isOwnedCachePath(`${Dirs.CacheDir}/../secret.txt`)).toBe(false)
await removeOwnedCacheFile(ownedPath, () => new Error('outside-root'))
expect(mockFileSystem.filesystem.has(ownedPath)).toBe(false)
await expect(
removeOwnedCacheFile('/etc/passwd', () => new Error('outside-root')),
).rejects.toThrow('outside-root')
})
test('throwIfPipelineCancelled_중단된신호시_AudioPipelineError발생', () => {
const controller = new AbortController()
expect(() => throwIfPipelineCancelled(controller.signal)).not.toThrow()
controller.abort()
expect(() => throwIfPipelineCancelled(controller.signal, 'Stopped early')).toThrow(
new AudioPipelineError('cancelled', 'Stopped early'),
)
})
})
describe('speech language tags and meeting error messages', () => {
test('toSpeechLanguageTag_전체12개지원로케일을_올바른BCP47태그로매핑', () => {
const expected: Record<(typeof LOCALE_CODES)[number], string> = {
ko: 'ko-KR',
en: 'en-US',
ja: 'ja',
zh: 'zh-CN',
'zh-TW': 'zh-TW',
es: 'es',
fr: 'fr',
de: 'de',
pt: 'pt',
ru: 'ru',
vi: 'vi',
th: 'th',
}
const actual = Object.fromEntries(
LOCALE_CODES.map((code) => [code, toSpeechLanguageTag(code)]),
)
expect(actual).toEqual(expected)
})
test('resolveMeetingErrorMessage_서비스에러코드를_정확한번역키로매핑', () => {
const t = (key: TranslationKey): string => key
expect(resolveMeetingErrorMessage(new MeetingServiceError('auth', 'a'), t)).toBe(
'mobile.meetings.loginRequired',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('conflict', 'c'), t)).toBe(
'mobile.meetings.errorConflict',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('forbidden', 'f'), t)).toBe(
'mobile.meetings.errorForbidden',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('network', 'n'), t)).toBe(
'mobile.meetings.errorNetwork',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('not-found', 'nf'), t)).toBe(
'mobile.meetings.errorNotFound',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('validation', 'v'), t)).toBe(
'mobile.meetings.errorValidation',
)
expect(resolveMeetingErrorMessage(new MeetingServiceError('server', 's'), t)).toBe(
'mobile.meetings.errorServer',
)
expect(resolveMeetingErrorMessage(new Error('unexpected'), t)).toBe(
'mobile.meetings.errorServer',
)
})
})