UNPKG

@projectlibertylabs/p2p-peer-test

Version:

CLI tool to test libp2p connections and discover peer protocols

87 lines (71 loc) 2.17 kB
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { testWithRetries } from './connection-tester.js'; // Mock the libp2p connection vi.mock('./libp2p-connection.js', () => ({ testLibp2pConnection: vi.fn() })); import { testLibp2pConnection } from './libp2p-connection.js'; beforeEach(() => { vi.clearAllMocks(); }); describe('testWithRetries', () => { it('should return success on first attempt', async () => { const mockResult = { success: true, duration: 100, peerId: 'test-peer', protocols: ['test-protocol'] }; testLibp2pConnection.mockResolvedValueOnce(mockResult); const result = await testWithRetries('/ip4/127.0.0.1/tcp/4001', { timeout: 5000, retries: 2 }); expect(result.success).toBe(true); expect(result.totalAttempts).toBe(1); expect(result.attempts).toHaveLength(1); expect(result.attempts[0]).toEqual({ attempt: 1, ...mockResult }); }); it('should retry on failure and eventually succeed', async () => { const failResult = { success: false, duration: 50, error: 'Connection failed' }; const successResult = { success: true, duration: 100, peerId: 'test-peer', protocols: ['test-protocol'] }; testLibp2pConnection.mockResolvedValueOnce(failResult).mockResolvedValueOnce(successResult); const result = await testWithRetries('/ip4/127.0.0.1/tcp/4001', { timeout: 5000, retries: 2 }); expect(result.success).toBe(true); expect(result.totalAttempts).toBe(2); expect(result.attempts).toHaveLength(2); expect(result.attempts[0].success).toBe(false); expect(result.attempts[1].success).toBe(true); }); it('should exhaust all retries and return final failure', async () => { const failResult = { success: false, duration: 50, error: 'Connection failed' }; testLibp2pConnection.mockResolvedValue(failResult); const result = await testWithRetries('/ip4/127.0.0.1/tcp/4001', { timeout: 5000, retries: 2 }); expect(result.success).toBe(false); expect(result.totalAttempts).toBe(3); // 1 + 2 retries expect(result.attempts).toHaveLength(3); expect(testLibp2pConnection).toHaveBeenCalledTimes(3); }); });