Files
Artveris/apps/api/src/blockchain/tianhe.provider.spec.ts
T

177 lines
6.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { EventEmitter } from 'node:events';
// 模拟 node:https.request:接口 9 用带 body 的 GET,走 https 模块而非 fetch
const httpsRequestMock = jest.fn();
jest.mock('node:https', () => ({ request: (...args: unknown[]) => httpsRequestMock(...args) }));
function mockHttpsRequestOnce(responseJson: unknown, statusCode = 200) {
httpsRequestMock.mockImplementation((_url: unknown, _opts: unknown, cb: unknown) => {
const callback = (typeof _opts === 'function' ? _opts : cb) as (res: EventEmitter & { statusCode: number }) => void;
const req = new EventEmitter() as EventEmitter & { write: () => void; end: () => void };
req.write = () => undefined;
req.end = () => {
const res = new EventEmitter() as EventEmitter & { statusCode: number };
res.statusCode = statusCode;
callback(res);
res.emit('data', JSON.stringify(responseJson));
res.emit('end');
};
return req;
});
}
// 放在 jest.mock 之后导入,确保 provider 拿到被 mock 的 https
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { TianheProvider, buildTianheExplorerTxUrl } = require('./tianhe.provider') as typeof import('./tianhe.provider');
describe('TianheProvider', () => {
const provider = new TianheProvider({
baseUrl: 'https://test.api.tichain.tianhecloud.com',
appId: 'app-id',
appKey: 'app-key',
userId: 'user-id',
userKey: 'user-key',
});
afterEach(() => {
jest.restoreAllMocks();
});
it('按天河环境生成 DApp 浏览器交易详情地址', () => {
const txHash = '0xabc/123';
expect(buildTianheExplorerTxUrl('https://test.api.tichain.tianhecloud.com', txHash)).toBe(
'https://test.explorer.tianhecloud.com/#/tiChain/transDetail?hash=0xabc%2F123',
);
expect(
buildTianheExplorerTxUrl('https://custom-api.example.com', txHash, 'production'),
).toBe('https://explorer.tianhecloud.com/#/tiChain/transDetail?hash=0xabc%2F123');
});
it('按天河链 upload 文档映射交易哈希、存证链接和文件哈希', async () => {
const response = {
code: 0,
message: 'success',
data: {
digest: 'file-digest-001',
url: 'https://test.explorer.tianhecloud.com/proof/001',
transactionHash: '0x1234567890abcdef',
},
};
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify(response),
} as Response);
const result = await provider.attest({
dataHash: '0xlocaldatahash',
meta: { traceCode: 'TRACE-001' },
});
expect(result.txHash).toBe(response.data.transactionHash);
expect(result.explorerUrl).toBe(response.data.url);
expect(result.raw.digest).toBe(response.data.digest);
// upload 成功即存证生效:确认接口仅适用 token 交易,对纯存证不适用(联调定稿)
expect(result.raw.transactionStatus).toBe('onchain');
expect(result.confirmationRequired).toBe(false);
// 存证交易拿不到区块信息,凭据以 txHash + digest + 存证链接为准
expect(result.blockHash).toBeNull();
expect(result.blockHeight).toBeNull();
});
it('upload 手工 multipart:userDto 分段无 filename 且带 application/json', async () => {
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { digest: 'd', url: 'u', transactionHash: '0xtx' } }),
} as Response);
await provider.attest({ dataHash: '0xhash' });
const init = fetchMock.mock.calls[0][1]!;
expect(String((init.headers as Record<string, string>)['Content-Type'])).toContain('multipart/form-data; boundary=');
const body = (init.body as Buffer).toString('utf8');
// userDto 分段:无 filename、带 application/json
expect(body).toContain('Content-Disposition: form-data; name="userDto"\r\nContent-Type: application/json');
expect(body).not.toContain('name="userDto"; filename');
});
it('响应缺少 transactionHash 时抛错,不用本地 dataHash 冒充', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 0, message: 'success', data: { digest: 'only-digest' } }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('transactionHash');
});
it('响应缺少 code 字段时视为异常而非成功', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ something: 'else' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('code=缺失');
});
it('code 非 0 时抛出接口错误信息', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ code: 500, message: 'appKey invalid' }),
} as Response);
await expect(provider.attest({ dataHash: '0xlocal' })).rejects.toThrow('appKey invalid');
});
it('registerUser 按接口 1 解析托管钱包地址', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
text: async () =>
JSON.stringify({ code: 0, data: { pubKey: { address: '0xwallet', publicKey: 'ignored' } } }),
} as Response);
const result = await provider.registerUser();
expect(result.address).toBe('0xwallet');
});
it('ensureRegistered 优先查询接口 8,失败则回退注册', async () => {
const fetchMock = jest
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 1, message: 'user not found' }),
} as Response)
.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ code: 0, data: { pubKey: { address: '0xnewwallet' } } }),
} as Response);
const result = await provider.ensureRegistered();
expect(result.address).toBe('0xnewwallet');
expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v2/user/info');
expect(String(fetchMock.mock.calls[1][0])).toContain('/api/v2/user');
});
it('按交易状态接口确认链上区块信息(GET+body 走 https 模块)', async () => {
const response = {
code: 0,
message: 'success',
data: {
status: '0x0',
blockHash: '0xblockhash',
blockNum: 12345,
transactionHash: '0x1234567890abcdef',
tokenId: -999,
},
};
mockHttpsRequestOnce(response);
const result = await provider.confirmTransaction(response.data.transactionHash);
expect(result.confirmed).toBe(true);
expect(result.txHash).toBe(response.data.transactionHash);
expect(result.blockHash).toBe(response.data.blockHash);
expect(result.blockHeight).toBe(response.data.blockNum);
expect(result.raw.transactionStatus).toBe('confirmed');
});
});