expo-popcore-old/utils/cookie-encoding-test.ts

99 lines
2.4 KiB
TypeScript

type TestCase = {
name: string;
execute: () => void;
};
function logSuccess(message: string) {
// Test passed
}
function logFailure(message: string, error: unknown) {
console.error(`${message}`, error);
}
function encodeCookieValue(value: string) {
return encodeURIComponent(value);
}
function decodeCookieValue(value: string) {
return decodeURIComponent(value);
}
function runTestCase({ name, execute }: TestCase) {
try {
execute();
logSuccess(name);
} catch (error) {
logFailure(name, error);
}
}
export function runCookieEncodingTests() {
const cases: TestCase[] = [
{
name: '基本英文字母安全编码',
execute: () => {
const input = 'session=test';
const encoded = encodeCookieValue(input);
const decoded = decodeCookieValue(encoded);
if (decoded !== input) {
throw new Error('解码值与原始值不一致');
}
},
},
{
name: '支持中文字符',
execute: () => {
const input = '昵称=代码艺术家';
const encoded = encodeCookieValue(input);
const decoded = decodeCookieValue(encoded);
if (decoded !== input) {
throw new Error('中文字符编码失败');
}
},
},
{
name: '特殊字符保留',
execute: () => {
const input = 'symbols=!@#$%^&*()_+-={}[]|:;"\'<>,.?/~`';
const encoded = encodeCookieValue(input);
const decoded = decodeCookieValue(encoded);
if (decoded !== input) {
throw new Error('特殊字符编码失败');
}
},
},
];
cases.forEach(runTestCase);
}
export function testRealWorldScenarios() {
const cases: TestCase[] = [
{
name: 'JWT Token 轮换',
execute: () => {
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';
const encoded = encodeCookieValue(token);
const decoded = decodeCookieValue(encoded);
if (decoded !== token) {
throw new Error('JWT token 编解码失败');
}
},
},
{
name: '长文本粘贴',
execute: () => {
const text = 'Prompt=' + '艺术创作'.repeat(20);
const encoded = encodeCookieValue(text);
const decoded = decodeCookieValue(encoded);
if (decoded !== text) {
throw new Error('长文本编码失败');
}
},
},
];
cases.forEach(runTestCase);
}