From 68d702b255960b084843b8a846cacfea07c56984 Mon Sep 17 00:00:00 2001 From: Brian Botha Date: Mon, 18 Dec 2023 13:01:28 +1100 Subject: [PATCH 1/5] tests: removed usage of conditional `testif` [ci skip] --- tests/agent/lock.test.ts | 61 +- tests/agent/lockall.test.ts | 63 +- tests/agent/start.test.ts | 339 ++++--- tests/agent/status.test.ts | 16 +- tests/agent/stop.test.ts | 14 +- tests/agent/unlock.test.ts | 4 +- tests/bootstrap.test.ts | 20 +- .../allowDisallowPermissions.test.ts | 452 +++++----- .../authenticateAuthenticated.test.ts | 176 ++-- tests/identities/claim.test.ts | 177 ++-- tests/identities/discoverGet.test.ts | 201 ++--- tests/identities/search.test.ts | 442 +++++----- tests/identities/trustUntrustList.test.ts | 57 +- tests/keys/cert.test.ts | 4 +- tests/keys/certchain.test.ts | 4 +- tests/keys/encryptDecrypt.test.ts | 16 +- tests/keys/keypair.test.ts | 66 +- tests/keys/password.test.ts | 48 +- tests/keys/private.test.ts | 46 +- tests/keys/public.test.ts | 4 +- tests/keys/renew.test.ts | 161 ++-- tests/keys/reset.test.ts | 163 ++-- tests/keys/signVerify.test.ts | 16 +- tests/nat/DMZ.test.ts | 8 +- tests/nat/endpointDependentNAT.test.ts | 10 +- tests/nat/endpointIndependentNAT.test.ts | 14 +- tests/nodes/add.test.ts | 217 +++-- tests/nodes/claim.test.ts | 34 +- tests/nodes/find.test.ts | 68 +- tests/nodes/ping.test.ts | 53 +- tests/notifications/sendReadClear.test.ts | 4 +- tests/polykey.test.ts | 10 +- tests/secrets/secrets.test.ts | 411 ++++----- tests/sessions.test.ts | 232 +++-- tests/utils.retryAuthentication.test.ts | 327 ++++--- tests/utils.test.ts | 562 ++++++------ tests/vaults/vaults.test.ts | 829 ++++++++---------- 37 files changed, 2484 insertions(+), 2845 deletions(-) diff --git a/tests/agent/lock.test.ts b/tests/agent/lock.test.ts index 1ad9852b..035d1bdd 100644 --- a/tests/agent/lock.test.ts +++ b/tests/agent/lock.test.ts @@ -20,9 +20,7 @@ describe('lock', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('lock deletes the session token', async () => { + test('lock deletes the session token', async () => { await testUtils.pkExec(['agent', 'unlock'], { env: { PK_NODE_PATH: agentDir, @@ -47,34 +45,31 @@ describe('lock', () => { expect(await session.readToken()).toBeUndefined(); await session.stop(); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'lock ensures re-authentication is required', - async () => { - const password = agentPassword; - prompts.mockClear(); - prompts.mockImplementation(async (_opts: any) => { - return { password }; - }); - await testUtils.pkStdio(['agent', 'unlock'], { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, - }, - cwd: agentDir, - }); - // Session token is deleted - await testUtils.pkStdio(['agent', 'lock'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - // Will prompt to reauthenticate - await testUtils.pkStdio(['agent', 'status'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - // Prompted for password 1 time - expect(prompts.mock.calls.length).toBe(1); - prompts.mockClear(); - }, - ); + test('lock ensures re-authentication is required', async () => { + const password = agentPassword; + prompts.mockClear(); + prompts.mockImplementation(async (_opts: any) => { + return { password }; + }); + await testUtils.pkStdio(['agent', 'unlock'], { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, + }); + // Session token is deleted + await testUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + // Will prompt to reauthenticate + await testUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + // Prompted for password 1 time + expect(prompts.mock.calls.length).toBe(1); + prompts.mockClear(); + }); }); diff --git a/tests/agent/lockall.test.ts b/tests/agent/lockall.test.ts index bd3cd151..87fe9827 100644 --- a/tests/agent/lockall.test.ts +++ b/tests/agent/lockall.test.ts @@ -26,9 +26,7 @@ describe('lockall', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('lockall deletes the session token', async () => { + test('lockall deletes the session token', async () => { await testUtils.pkExec(['agent', 'unlock'], { env: { PK_NODE_PATH: agentDir, @@ -51,38 +49,33 @@ describe('lockall', () => { expect(await session.readToken()).toBeUndefined(); await session.stop(); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'lockall ensures re-authentication is required', - async () => { - const password = agentPassword; - await testUtils.pkStdio(['agent', 'unlock'], { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, - }, - cwd: agentDir, - }); - await testUtils.pkStdio(['agent', 'lockall'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - // Token is deleted, re-authentication is required - prompts.mockClear(); - prompts.mockImplementation(async (_opts: any) => { - return { password }; - }); - await testUtils.pkStdio(['agent', 'status'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - // Prompted for password 1 time - expect(prompts.mock.calls.length).toBe(1); - prompts.mockClear(); - }, - ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('lockall causes old session tokens to fail', async () => { + test('lockall ensures re-authentication is required', async () => { + const password = agentPassword; + await testUtils.pkStdio(['agent', 'unlock'], { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, + }); + await testUtils.pkStdio(['agent', 'lockall'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + // Token is deleted, re-authentication is required + prompts.mockClear(); + prompts.mockImplementation(async (_opts: any) => { + return { password }; + }); + await testUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + // Prompted for password 1 time + expect(prompts.mock.calls.length).toBe(1); + prompts.mockClear(); + }); + test('lockall causes old session tokens to fail', async () => { await testUtils.pkExec(['agent', 'unlock'], { env: { PK_NODE_PATH: agentDir, diff --git a/tests/agent/start.test.ts b/tests/agent/start.test.ts index 4c0b8302..f6a951df 100644 --- a/tests/agent/start.test.ts +++ b/tests/agent/start.test.ts @@ -32,9 +32,7 @@ describe('start', () => { // Just ignore failures here .catch(() => {}); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start in foreground', async () => { const password = 'abc123'; @@ -104,7 +102,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'start in background', async () => { const password = 'abc123'; @@ -206,9 +204,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'concurrent starts results in 1 success', async () => { const password = 'abc123'; @@ -319,9 +315,7 @@ describe('start', () => { globalThis.defaultTimeout * 2, ); // FIXME: disabled for now, both are succeeding when 1 should fail - testUtils - // .testIf(testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker) - .testIf(false)( + test.skip( 'concurrent with bootstrap results in 1 success', async () => { const password = 'abc123'; @@ -417,9 +411,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start with existing state', async () => { const password = 'abc123'; @@ -499,9 +491,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start when interrupted, requires fresh on next start', async () => { const password = 'password'; @@ -614,9 +604,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start from recovery code', async () => { const password1 = 'abc123'; @@ -778,9 +766,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 3, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start with network configuration', async () => { const status = new Status({ @@ -840,9 +826,7 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'start with --private-key-file override', async () => { const status = new Status({ @@ -905,98 +889,83 @@ describe('start', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.describeIf(testUtils.isTestPlatformEmpty)( - 'start with global agent', - () => { - let agentDataDir; - let agent1Status: StatusLive; - let agent1Close: () => Promise; - let agent2Status: StatusLive; - let agent2Close: () => Promise; - let seedNodeId1: NodeId; - let seedNodeHost1: string; - let seedNodePort1: number; - let seedNodeId2: NodeId; - let seedNodeHost2: string; - let seedNodePort2: number; - beforeEach(async () => { - // Additional seed node - agentDataDir = await fs.promises.mkdtemp( - path.join(globalThis.tmpDir, 'polykey-test-'), - ); - ({ agentStatus: agent1Status, agentClose: agent1Close } = - await testUtils.setupTestAgent(logger)); - ({ agentStatus: agent2Status, agentClose: agent2Close } = - await testUtils.setupTestAgent(logger)); - seedNodeId1 = agent1Status.data.nodeId; - seedNodeHost1 = agent1Status.data.agentHost; - seedNodePort1 = agent1Status.data.agentPort; - seedNodeId2 = agent2Status.data.nodeId; - seedNodeHost2 = agent2Status.data.agentHost; - seedNodePort2 = agent2Status.data.agentPort; + describe('start with global agent', () => { + let agentDataDir; + let agent1Status: StatusLive; + let agent1Close: () => Promise; + let agent2Status: StatusLive; + let agent2Close: () => Promise; + let seedNodeId1: NodeId; + let seedNodeHost1: string; + let seedNodePort1: number; + let seedNodeId2: NodeId; + let seedNodeHost2: string; + let seedNodePort2: number; + beforeEach(async () => { + // Additional seed node + agentDataDir = await fs.promises.mkdtemp( + path.join(globalThis.tmpDir, 'polykey-test-'), + ); + ({ agentStatus: agent1Status, agentClose: agent1Close } = + await testUtils.setupTestAgent(logger)); + ({ agentStatus: agent2Status, agentClose: agent2Close } = + await testUtils.setupTestAgent(logger)); + seedNodeId1 = agent1Status.data.nodeId; + seedNodeHost1 = agent1Status.data.agentHost; + seedNodePort1 = agent1Status.data.agentPort; + seedNodeId2 = agent2Status.data.nodeId; + seedNodeHost2 = agent2Status.data.agentHost; + seedNodePort2 = agent2Status.data.agentPort; + }); + afterEach(async () => { + await agent1Close(); + await agent2Close(); + await fs.promises.rm(agentDataDir, { + force: true, + recursive: true, }); - afterEach(async () => { - await agent1Close(); - await agent2Close(); - await fs.promises.rm(agentDataDir, { - force: true, - recursive: true, + }); + test( + 'start with seed nodes option', + async () => { + const password = 'abc123'; + const nodePath = path.join(dataDir, 'polykey'); + const statusPath = path.join(nodePath, config.paths.statusBase); + const statusLockPath = path.join(nodePath, config.paths.statusLockBase); + const status = new Status({ + statusPath, + statusLockPath, + fs, + logger, }); - }); - test( - 'start with seed nodes option', - async () => { - const password = 'abc123'; - const nodePath = path.join(dataDir, 'polykey'); - const statusPath = path.join(nodePath, config.paths.statusBase); - const statusLockPath = path.join( - nodePath, - config.paths.statusLockBase, - ); - const status = new Status({ - statusPath, - statusLockPath, - fs, - logger, - }); - const mockedResolveSeedNodes = jest.spyOn( - nodesUtils, - 'resolveSeednodes', - ); - mockedResolveSeedNodes.mockResolvedValue({ - [nodesUtils.encodeNodeId(seedNodeId2)]: [ - seedNodeHost2 as Host, - seedNodePort2 as Port, - ], - }); - // Record - await testUtils.pkStdio( - [ - 'agent', - 'start', - '--client-host', - '127.0.0.1', - '--agent-host', - '127.0.0.1', - '--workers', - 'none', - '--seed-nodes', - `${seedNodeId1}@${seedNodeHost1}:${seedNodePort1};`, - '--network', - 'testnet', - '--verbose', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - PK_PASSWORD_OPS_LIMIT: 'min', - PK_PASSWORD_MEM_LIMIT: 'min', - }, - cwd: dataDir, - }, - ); - await testUtils.pkStdio(['agent', 'stop'], { + const mockedResolveSeedNodes = jest.spyOn( + nodesUtils, + 'resolveSeednodes', + ); + mockedResolveSeedNodes.mockResolvedValue({ + [nodesUtils.encodeNodeId(seedNodeId2)]: [ + seedNodeHost2 as Host, + seedNodePort2 as Port, + ], + }); + // Record + await testUtils.pkStdio( + [ + 'agent', + 'start', + '--client-host', + '127.0.0.1', + '--agent-host', + '127.0.0.1', + '--workers', + 'none', + '--seed-nodes', + `${seedNodeId1}@${seedNodeHost1}:${seedNodePort1};`, + '--network', + 'testnet', + '--verbose', + ], + { env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, @@ -1004,78 +973,84 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - }); - mockedResolveSeedNodes.mockRestore(); - await status.waitFor('DEAD'); - }, - globalThis.defaultTimeout * 2, - ); - test( - 'start with seed nodes environment variable', - async () => { - const password = 'abc123'; - const nodePath = path.join(dataDir, 'polykey'); - const statusPath = path.join(nodePath, config.paths.statusBase); - const statusLockPath = path.join( - nodePath, - config.paths.statusLockBase, - ); - const status = new Status({ - statusPath, - statusLockPath, - fs, - logger, - }); - const mockedResolveSeedNodes = jest.spyOn( - nodesUtils, - 'resolveSeednodes', - ); - mockedResolveSeedNodes.mockResolvedValue({ - [nodesUtils.encodeNodeId(seedNodeId2)]: [ - seedNodeHost2 as Host, - seedNodePort2 as Port, - ], - }); - await testUtils.pkStdio( - [ - 'agent', - 'start', - '--client-host', - '127.0.0.1', - '--agent-host', - '127.0.0.1', - '--workers', - 'none', - '--network', - 'testnet', - '--verbose', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - PK_PASSWORD_OPS_LIMIT: 'min', - PK_PASSWORD_MEM_LIMIT: 'min', - PK_SEED_NODES: `;${seedNodeId1}@${seedNodeHost1}:${seedNodePort1}`, - PK_NETWORK: 'testnet', - }, - cwd: dataDir, - }, - ); - await testUtils.pkStdio(['agent', 'stop'], { + }, + ); + await testUtils.pkStdio(['agent', 'stop'], { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + PK_PASSWORD_OPS_LIMIT: 'min', + PK_PASSWORD_MEM_LIMIT: 'min', + }, + cwd: dataDir, + }); + mockedResolveSeedNodes.mockRestore(); + await status.waitFor('DEAD'); + }, + globalThis.defaultTimeout * 2, + ); + test( + 'start with seed nodes environment variable', + async () => { + const password = 'abc123'; + const nodePath = path.join(dataDir, 'polykey'); + const statusPath = path.join(nodePath, config.paths.statusBase); + const statusLockPath = path.join(nodePath, config.paths.statusLockBase); + const status = new Status({ + statusPath, + statusLockPath, + fs, + logger, + }); + const mockedResolveSeedNodes = jest.spyOn( + nodesUtils, + 'resolveSeednodes', + ); + mockedResolveSeedNodes.mockResolvedValue({ + [nodesUtils.encodeNodeId(seedNodeId2)]: [ + seedNodeHost2 as Host, + seedNodePort2 as Port, + ], + }); + await testUtils.pkStdio( + [ + 'agent', + 'start', + '--client-host', + '127.0.0.1', + '--agent-host', + '127.0.0.1', + '--workers', + 'none', + '--network', + 'testnet', + '--verbose', + ], + { env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, PK_PASSWORD_OPS_LIMIT: 'min', PK_PASSWORD_MEM_LIMIT: 'min', + PK_SEED_NODES: `;${seedNodeId1}@${seedNodeHost1}:${seedNodePort1}`, + PK_NETWORK: 'testnet', }, cwd: dataDir, - }); - mockedResolveSeedNodes.mockRestore(); - await status.waitFor('DEAD'); - }, - globalThis.defaultTimeout * 2, - ); - }, - ); + }, + ); + await testUtils.pkStdio(['agent', 'stop'], { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + PK_PASSWORD_OPS_LIMIT: 'min', + PK_PASSWORD_MEM_LIMIT: 'min', + }, + cwd: dataDir, + }); + mockedResolveSeedNodes.mockRestore(); + await status.waitFor('DEAD'); + }, + globalThis.defaultTimeout * 2, + ); + }); }); diff --git a/tests/agent/status.test.ts b/tests/agent/status.test.ts index 27cb9f4a..f13d8b6c 100644 --- a/tests/agent/status.test.ts +++ b/tests/agent/status.test.ts @@ -22,9 +22,7 @@ describe('status', () => { recursive: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'status on STARTING, STOPPING, DEAD agent', async () => { // This test must create its own agent process @@ -125,9 +123,7 @@ describe('status', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('status on missing agent', async () => { + test('status on missing agent', async () => { const { exitCode, stdout } = await testUtils.pkExec( ['agent', 'status', '--format', 'json'], { @@ -151,9 +147,7 @@ describe('status', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('status on LIVE agent', async () => { + test('status on LIVE agent', async () => { const status = new Status({ statusPath: path.join(agentDir, config.paths.statusBase), statusLockPath: path.join(agentDir, config.paths.statusLockBase), @@ -186,9 +180,7 @@ describe('status', () => { nodesTotal: expect.any(Number), }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('status on remote LIVE agent', async () => { + test('status on remote LIVE agent', async () => { const passwordPath = path.join(dataDir, 'password'); await fs.promises.writeFile(passwordPath, agentPassword); const status = new Status({ diff --git a/tests/agent/stop.test.ts b/tests/agent/stop.test.ts index 60c128b9..5aab308c 100644 --- a/tests/agent/stop.test.ts +++ b/tests/agent/stop.test.ts @@ -22,9 +22,7 @@ describe('stop', () => { recursive: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'stop LIVE agent', async () => { const password = 'abc123'; @@ -78,9 +76,7 @@ describe('stop', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'stopping is idempotent during concurrent calls and STOPPING or DEAD status', async () => { const password = 'abc123'; @@ -180,7 +176,7 @@ describe('stop', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'stopping starting agent results in error', async () => { // This relies on fast execution of `agent stop` while agent is starting, @@ -246,9 +242,7 @@ describe('stop', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'stopping while unauthenticated does not stop', async () => { const password = 'abc123'; diff --git a/tests/agent/unlock.test.ts b/tests/agent/unlock.test.ts index 1cffed31..67441a0c 100644 --- a/tests/agent/unlock.test.ts +++ b/tests/agent/unlock.test.ts @@ -19,9 +19,7 @@ describe('unlock', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('unlock acquires session token', async () => { + test('unlock acquires session token', async () => { // Fresh session, to delete the token const session = await Session.createSession({ sessionTokenPath: path.join(agentDir, config.paths.tokenBase), diff --git a/tests/bootstrap.test.ts b/tests/bootstrap.test.ts index 245efb25..43353620 100644 --- a/tests/bootstrap.test.ts +++ b/tests/bootstrap.test.ts @@ -23,9 +23,7 @@ describe('bootstrap', () => { recursive: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'bootstraps node state', async () => { const password = 'password'; @@ -52,9 +50,7 @@ describe('bootstrap', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'bootstraps node state from provided private key', async () => { const password = 'password'; @@ -99,9 +95,7 @@ describe('bootstrap', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'bootstrapping occupied node state', async () => { const password = 'password'; @@ -159,9 +153,7 @@ describe('bootstrap', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'concurrent bootstrapping results in 1 success', async () => { const password = 'password'; @@ -238,9 +230,7 @@ describe('bootstrap', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'bootstrap when interrupted, requires fresh on next bootstrap', async () => { const password = 'password'; diff --git a/tests/identities/allowDisallowPermissions.test.ts b/tests/identities/allowDisallowPermissions.test.ts index 995f116a..e0e4d5f0 100644 --- a/tests/identities/allowDisallowPermissions.test.ts +++ b/tests/identities/allowDisallowPermissions.test.ts @@ -100,255 +100,247 @@ describe('allow/disallow/permissions', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'allows/disallows/gets gestalt permissions by node', - async () => { - let exitCode, stdout; - // Add the node to our node graph, otherwise we won't be able to contact it - await testUtils.pkStdio( - [ - 'nodes', - 'add', - nodesUtils.encodeNodeId(nodeId), - nodeHost, - `${nodePort}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - // Must first trust node before we can set permissions - // This is because trusting the node sets it in our gestalt graph, which - // we need in order to set permissions - await testUtils.pkStdio( - ['identities', 'trust', nodesUtils.encodeNodeId(nodeId)], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('allows/disallows/gets gestalt permissions by node', async () => { + let exitCode, stdout; + // Add the node to our node graph, otherwise we won't be able to contact it + await testUtils.pkStdio( + [ + 'nodes', + 'add', + nodesUtils.encodeNodeId(nodeId), + nodeHost, + `${nodePort}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // We should now have the 'notify' permission, so we'll set the 'scan' - // permission as well - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'allow', nodesUtils.encodeNodeId(nodeId), 'scan'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Must first trust node before we can set permissions + // This is because trusting the node sets it in our gestalt graph, which + // we need in order to set permissions + await testUtils.pkStdio( + ['identities', 'trust', nodesUtils.encodeNodeId(nodeId)], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // Check that both permissions are set - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'permissions', - nodesUtils.encodeNodeId(nodeId), - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // We should now have the 'notify' permission, so we'll set the 'scan' + // permission as well + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'allow', nodesUtils.encodeNodeId(nodeId), 'scan'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - permissions: ['notify', 'scan'], - }); - // Disallow both permissions - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'notify'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // Check that both permissions are set + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'permissions', + nodesUtils.encodeNodeId(nodeId), + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'scan'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + permissions: ['notify', 'scan'], + }); + // Disallow both permissions + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'notify'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // Check that both permissions were unset - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'permissions', - nodesUtils.encodeNodeId(nodeId), - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'scan'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - permissions: [], - }); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'allows/disallows/gets gestalt permissions by identity', - async () => { - // Can't test with target executable due to mocking - let exitCode, stdout; - // Add the node to our node graph, otherwise we won't be able to contact it - await testUtils.pkStdio( - [ - 'nodes', - 'add', - nodesUtils.encodeNodeId(nodeId), - nodeHost, - `${nodePort}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // Check that both permissions were unset + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'permissions', + nodesUtils.encodeNodeId(nodeId), + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - await testUtils.pkStdio( - [ - 'identities', - 'authenticate', - testToken.providerId, - testToken.identityId, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + permissions: [], + }); + }); + test('allows/disallows/gets gestalt permissions by identity', async () => { + // Can't test with target executable due to mocking + let exitCode, stdout; + // Add the node to our node graph, otherwise we won't be able to contact it + await testUtils.pkStdio( + [ + 'nodes', + 'add', + nodesUtils.encodeNodeId(nodeId), + nodeHost, + `${nodePort}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // Must first trust identity before we can set permissions - // This is because trusting the identity sets it in our gestalt graph, - // which we need in order to set permissions - // This command should fail first time since the identity won't be linked - // to any nodes. It will trigger this process via discovery and we must - // wait and then retry - await testUtils.pkStdio(['identities', 'trust', providerString], { + cwd: dataDir, + }, + ); + await testUtils.pkStdio( + [ + 'identities', + 'authenticate', + testToken.providerId, + testToken.identityId, + ], + { env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, }, cwd: dataDir, - }); - while ((await pkAgent.discovery.waitForDiscoveryTasks()) > 0) { - // Waiting for discovery to complete - } - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'trust', providerString], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + }, + ); + // Must first trust identity before we can set permissions + // This is because trusting the identity sets it in our gestalt graph, + // which we need in order to set permissions + // This command should fail first time since the identity won't be linked + // to any nodes. It will trigger this process via discovery and we must + // wait and then retry + await testUtils.pkStdio(['identities', 'trust', providerString], { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, + }); + while ((await pkAgent.discovery.waitForDiscoveryTasks()) > 0) { + // Waiting for discovery to complete + } + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'trust', providerString], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // We should now have the 'notify' permission, so we'll set the 'scan' - // permission as well - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'allow', providerString, 'scan'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // We should now have the 'notify' permission, so we'll set the 'scan' + // permission as well + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'allow', providerString, 'scan'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // Check that both permissions are set - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'permissions', providerString, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // Check that both permissions are set + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'permissions', providerString, '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - permissions: ['notify', 'scan'], - }); - // Disallow both permissions - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'disallow', providerString, 'notify'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + permissions: ['notify', 'scan'], + }); + // Disallow both permissions + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'disallow', providerString, 'notify'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'disallow', providerString, 'scan'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'disallow', providerString, 'scan'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // Check that both permissions were unset - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'permissions', providerString, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // Check that both permissions were unset + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'permissions', providerString, '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - permissions: [], - }); - }, - ); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('should fail on invalid inputs', async () => { + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + permissions: [], + }); + }); + test('should fail on invalid inputs', async () => { let exitCode; // Allow // Invalid gestalt id diff --git a/tests/identities/authenticateAuthenticated.test.ts b/tests/identities/authenticateAuthenticated.test.ts index 2147106e..402915d5 100644 --- a/tests/identities/authenticateAuthenticated.test.ts +++ b/tests/identities/authenticateAuthenticated.test.ts @@ -55,100 +55,94 @@ describe('authenticate/authenticated', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'authenticates identity with a provider and gets authenticated identity', - async () => { - // Can't test with target command due to mocking - let exitCode, stdout; - // Authenticate an identity - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'authenticate', - testToken.providerId, - testToken.identityId, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('authenticates identity with a provider and gets authenticated identity', async () => { + // Can't test with target command due to mocking + let exitCode, stdout; + // Authenticate an identity + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'authenticate', + testToken.providerId, + testToken.identityId, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(stdout).toContain('randomtestcode'); - // Check that the identity was authenticated - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'authenticated', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(stdout).toContain('randomtestcode'); + // Check that the identity was authenticated + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'authenticated', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - providerId: testToken.providerId, - identityId: testToken.identityId, - }); - // Check using providerId flag - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'authenticated', - '--provider-id', - testToken.providerId, - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + providerId: testToken.providerId, + identityId: testToken.identityId, + }); + // Check using providerId flag + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'authenticated', + '--provider-id', + testToken.providerId, + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - providerId: testToken.providerId, - identityId: testToken.identityId, - }); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail on invalid inputs', - async () => { - let exitCode; - // Authenticate - // Invalid provider - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'authenticate', '', testToken.identityId], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + providerId: testToken.providerId, + identityId: testToken.identityId, + }); + }); + test('should fail on invalid inputs', async () => { + let exitCode; + // Authenticate + // Invalid provider + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'authenticate', '', testToken.identityId], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Authenticated - // Invalid provider - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'authenticate', ''], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Authenticated + // Invalid provider + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'authenticate', ''], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + }); }); diff --git a/tests/identities/claim.test.ts b/tests/identities/claim.test.ts index 91ff4a22..8077903d 100644 --- a/tests/identities/claim.test.ts +++ b/tests/identities/claim.test.ts @@ -57,102 +57,93 @@ describe('claim', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'claims an identity', - async () => { - // Need an authenticated identity - await testUtils.pkStdio( - [ - 'identities', - 'authenticate', - testToken.providerId, - testToken.identityId, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('claims an identity', async () => { + // Need an authenticated identity + await testUtils.pkStdio( + [ + 'identities', + 'authenticate', + testToken.providerId, + testToken.identityId, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // Claim identity - const { exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'claim', - `${testToken.providerId}:${testToken.identityId}`, - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Claim identity + const { exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'claim', + `${testToken.providerId}:${testToken.identityId}`, + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual(['Claim Id: 0', 'Url: test.com']); - // Check for claim on the provider - const claim = await testProvider.getClaim( - testToken.identityId, - '0' as ProviderIdentityClaimId, - ); - expect(claim).toBeDefined(); - expect(claim!.id).toBe('0'); - // Expect(claim!.payload.data.type).toBe('identity'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'cannot claim unauthenticated identities', - async () => { - const { exitCode } = await testUtils.pkStdio( - [ - 'identities', - 'claim', - `${testToken.providerId}:${testToken.identityId}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual(['Claim Id: 0', 'Url: test.com']); + // Check for claim on the provider + const claim = await testProvider.getClaim( + testToken.identityId, + '0' as ProviderIdentityClaimId, + ); + expect(claim).toBeDefined(); + expect(claim!.id).toBe('0'); + // Expect(claim!.payload.data.type).toBe('identity'); + }); + test('cannot claim unauthenticated identities', async () => { + const { exitCode } = await testUtils.pkStdio( + [ + 'identities', + 'claim', + `${testToken.providerId}:${testToken.identityId}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(sysexits.NOPERM); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail on invalid inputs', - async () => { - let exitCode; - // Invalid provider - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'claim', `:${testToken.identityId}`], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(sysexits.NOPERM); + }); + test('should fail on invalid inputs', async () => { + let exitCode; + // Invalid provider + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'claim', `:${testToken.identityId}`], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Invalid identity - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'claim', `${testToken.providerId}:`], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Invalid identity + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'claim', `${testToken.providerId}:`], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + }); }); diff --git a/tests/identities/discoverGet.test.ts b/tests/identities/discoverGet.test.ts index c6239a80..1d3212b7 100644 --- a/tests/identities/discoverGet.test.ts +++ b/tests/identities/discoverGet.test.ts @@ -124,7 +124,7 @@ describe('discover/get', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'discovers and gets gestalt by node', async () => { await testUtils.pkStdio( @@ -205,113 +205,104 @@ describe('discover/get', () => { }, globalThis.defaultTimeout * 3, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'discovers and gets gestalt by identity', - async () => { - await testUtils.pkStdio( - [ - 'identities', - 'authenticate', - testToken.providerId, - testToken.identityId, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - // Add one of the nodes to our gestalt graph so that we'll be able to - // contact the gestalt during discovery - await testUtils.pkStdio( - [ - 'nodes', - 'add', - nodesUtils.encodeNodeId(nodeAId), - nodeAHost, - `${nodeAPort}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('discovers and gets gestalt by identity', async () => { + await testUtils.pkStdio( + [ + 'identities', + 'authenticate', + testToken.providerId, + testToken.identityId, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // Discover gestalt by node - const discoverResponse = await testUtils.pkStdio( - ['identities', 'discover', providerString], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Add one of the nodes to our gestalt graph so that we'll be able to + // contact the gestalt during discovery + await testUtils.pkStdio( + [ + 'nodes', + 'add', + nodesUtils.encodeNodeId(nodeAId), + nodeAHost, + `${nodeAPort}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(discoverResponse.exitCode).toBe(0); - // Since discovery is a background process we need to wait for the - while ((await pkAgent.discovery.waitForDiscoveryTasks()) > 0) { - // Gestalt to be discovered - } - // Now we can get the gestalt - const getResponse = await testUtils.pkStdio( - ['identities', 'get', providerString], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Discover gestalt by node + const discoverResponse = await testUtils.pkStdio( + ['identities', 'discover', providerString], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(getResponse.exitCode).toBe(0); - expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeAId)); - expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeBId)); - expect(getResponse.stdout).toContain(providerString); - // Revert side effects - await pkAgent.gestaltGraph.unsetNode(nodeAId); - await pkAgent.gestaltGraph.unsetNode(nodeBId); - await pkAgent.gestaltGraph.unsetIdentity([testProvider.id, identityId]); - await pkAgent.nodeGraph.unsetNodeContact(nodeAId); - await pkAgent.identitiesManager.delToken( - testToken.providerId, - testToken.identityId, - ); - // @ts-ignore - get protected property - pkAgent.discovery.visitedVertices.clear(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail on invalid inputs', - async () => { - let exitCode; - // Discover - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'discover', 'invalid'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(discoverResponse.exitCode).toBe(0); + // Since discovery is a background process we need to wait for the + while ((await pkAgent.discovery.waitForDiscoveryTasks()) > 0) { + // Gestalt to be discovered + } + // Now we can get the gestalt + const getResponse = await testUtils.pkStdio( + ['identities', 'get', providerString], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Get - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'get', 'invalid'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(getResponse.exitCode).toBe(0); + expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeAId)); + expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeBId)); + expect(getResponse.stdout).toContain(providerString); + // Revert side effects + await pkAgent.gestaltGraph.unsetNode(nodeAId); + await pkAgent.gestaltGraph.unsetNode(nodeBId); + await pkAgent.gestaltGraph.unsetIdentity([testProvider.id, identityId]); + await pkAgent.nodeGraph.unsetNodeContact(nodeAId); + await pkAgent.identitiesManager.delToken( + testToken.providerId, + testToken.identityId, + ); + // @ts-ignore - get protected property + pkAgent.discovery.visitedVertices.clear(); + }); + test('should fail on invalid inputs', async () => { + let exitCode; + // Discover + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'discover', 'invalid'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Get + ({ exitCode } = await testUtils.pkStdio(['identities', 'get', 'invalid'], { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, + })); + }); }); diff --git a/tests/identities/search.test.ts b/tests/identities/search.test.ts index 64b01f4b..0d02fa23 100644 --- a/tests/identities/search.test.ts +++ b/tests/identities/search.test.ts @@ -144,242 +144,236 @@ describe('search', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'finds connected identities', - async () => { - // Can't test with target executable due to mocking - let exitCode, stdout; - let searchResults: Array; - // Search with no authenticated identities - // Should return nothing - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('finds connected identities', async () => { + // Can't test with target executable due to mocking + let exitCode, stdout; + let searchResults: Array; + // Search with no authenticated identities + // Should return nothing + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - expect(stdout).toBe(''); - // Authenticate an identity for provider1 - await testUtils.pkStdio( - ['identities', 'authenticate', provider1.id, identityId], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + expect(stdout).toBe(''); + // Authenticate an identity for provider1 + await testUtils.pkStdio( + ['identities', 'authenticate', provider1.id, identityId], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // Now our search should include the identities from provider1 - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Now our search should include the identities from provider1 + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(3); - expect(searchResults).toContainEqual(user1); - expect(searchResults).toContainEqual(user2); - expect(searchResults).toContainEqual(user3); - // Authenticate an identity for provider2 - await testUtils.pkStdio( - ['identities', 'authenticate', provider2.id, identityId], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(3); + expect(searchResults).toContainEqual(user1); + expect(searchResults).toContainEqual(user2); + expect(searchResults).toContainEqual(user3); + // Authenticate an identity for provider2 + await testUtils.pkStdio( + ['identities', 'authenticate', provider2.id, identityId], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // Now our search should include the identities from provider1 and - // provider2 - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // Now our search should include the identities from provider1 and + // provider2 + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(6); - expect(searchResults).toContainEqual(user1); - expect(searchResults).toContainEqual(user2); - expect(searchResults).toContainEqual(user3); - expect(searchResults).toContainEqual(user4); - expect(searchResults).toContainEqual(user5); - expect(searchResults).toContainEqual(user6); - // We can narrow this search by providing search terms - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '4', '5', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(6); + expect(searchResults).toContainEqual(user1); + expect(searchResults).toContainEqual(user2); + expect(searchResults).toContainEqual(user3); + expect(searchResults).toContainEqual(user4); + expect(searchResults).toContainEqual(user5); + expect(searchResults).toContainEqual(user6); + // We can narrow this search by providing search terms + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '4', '5', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(2); - expect(searchResults).toContainEqual(user4); - expect(searchResults).toContainEqual(user5); - // Authenticate an identity for provider3 - await testUtils.pkStdio( - ['identities', 'authenticate', provider3.id, identityId], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(2); + expect(searchResults).toContainEqual(user4); + expect(searchResults).toContainEqual(user5); + // Authenticate an identity for provider3 + await testUtils.pkStdio( + ['identities', 'authenticate', provider3.id, identityId], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - // We can get results from only some providers using the --provider-id - // option - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'search', - '--provider-id', - provider2.id, - provider3.id, - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + // We can get results from only some providers using the --provider-id + // option + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'search', + '--provider-id', + provider2.id, + provider3.id, + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(5); - expect(searchResults).toContainEqual(user4); - expect(searchResults).toContainEqual(user5); - expect(searchResults).toContainEqual(user6); - expect(searchResults).toContainEqual(user7); - expect(searchResults).toContainEqual(user8); - ({ exitCode, stdout } = await testUtils.pkStdio( - [ - 'identities', - 'search', - '--provider-id', - provider2.id, - '--provider-id', - provider3.id, - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(5); + expect(searchResults).toContainEqual(user4); + expect(searchResults).toContainEqual(user5); + expect(searchResults).toContainEqual(user6); + expect(searchResults).toContainEqual(user7); + expect(searchResults).toContainEqual(user8); + ({ exitCode, stdout } = await testUtils.pkStdio( + [ + 'identities', + 'search', + '--provider-id', + provider2.id, + '--provider-id', + provider3.id, + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(5); - expect(searchResults).toContainEqual(user4); - expect(searchResults).toContainEqual(user5); - expect(searchResults).toContainEqual(user6); - expect(searchResults).toContainEqual(user7); - expect(searchResults).toContainEqual(user8); - // We can search for a specific identity id across providers - // This will find identities even if they're disconnected - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '--identity-id', 'user3', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(5); + expect(searchResults).toContainEqual(user4); + expect(searchResults).toContainEqual(user5); + expect(searchResults).toContainEqual(user6); + expect(searchResults).toContainEqual(user7); + expect(searchResults).toContainEqual(user8); + // We can search for a specific identity id across providers + // This will find identities even if they're disconnected + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '--identity-id', 'user3', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(3); - expect(searchResults).toContainEqual(user3); - expect(searchResults).toContainEqual(user6); - expect(searchResults).toContainEqual(user9); - // We can limit the number of search results to display - ({ exitCode, stdout } = await testUtils.pkStdio( - ['identities', 'search', '--limit', '2', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(3); + expect(searchResults).toContainEqual(user3); + expect(searchResults).toContainEqual(user6); + expect(searchResults).toContainEqual(user9); + // We can limit the number of search results to display + ({ exitCode, stdout } = await testUtils.pkStdio( + ['identities', 'search', '--limit', '2', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); - expect(searchResults).toHaveLength(2); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail on invalid inputs', - async () => { - let exitCode; - // Invalid identity id - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'search', '--identity-id', ''], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); + expect(searchResults).toHaveLength(2); + }); + test('should fail on invalid inputs', async () => { + let exitCode; + // Invalid identity id + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'search', '--identity-id', ''], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Invalid auth identity id - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'search', '--auth-identity-id', ''], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Invalid auth identity id + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'search', '--auth-identity-id', ''], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Invalid value for limit - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'search', '--limit', 'NaN'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Invalid value for limit + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'search', '--limit', 'NaN'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + }); }); diff --git a/tests/identities/trustUntrustList.test.ts b/tests/identities/trustUntrustList.test.ts index 03f5586a..610361c0 100644 --- a/tests/identities/trustUntrustList.test.ts +++ b/tests/identities/trustUntrustList.test.ts @@ -102,7 +102,7 @@ describe('trust/untrust/list', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'trusts and untrusts a gestalt by node, adds it to the gestalt graph, and lists the gestalt with notify permission', async () => { let exitCode, stdout; @@ -232,7 +232,7 @@ describe('trust/untrust/list', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'trusts and untrusts a gestalt by identity, adds it to the gestalt graph, and lists the gestalt with notify permission', async () => { let exitCode, stdout; @@ -376,34 +376,31 @@ describe('trust/untrust/list', () => { }, globalThis.defaultTimeout * 2, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail on invalid inputs', - async () => { - let exitCode; - // Trust - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'trust', 'invalid'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('should fail on invalid inputs', async () => { + let exitCode; + // Trust + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'trust', 'invalid'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - // Untrust - ({ exitCode } = await testUtils.pkStdio( - ['identities', 'untrust', 'invalid'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + // Untrust + ({ exitCode } = await testUtils.pkStdio( + ['identities', 'untrust', 'invalid'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(sysexits.USAGE); + }); }); diff --git a/tests/keys/cert.test.ts b/tests/keys/cert.test.ts index fade65f5..3416e0e1 100644 --- a/tests/keys/cert.test.ts +++ b/tests/keys/cert.test.ts @@ -13,9 +13,7 @@ describe('cert', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('cert gets the certificate', async () => { + test('cert gets the certificate', async () => { const { exitCode, stdout } = await testUtils.pkExec( ['keys', 'cert', '--format', 'json'], { diff --git a/tests/keys/certchain.test.ts b/tests/keys/certchain.test.ts index 16e492f2..9bbc8e2f 100644 --- a/tests/keys/certchain.test.ts +++ b/tests/keys/certchain.test.ts @@ -15,9 +15,7 @@ describe('certchain', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('certchain gets the certificate chain', async () => { + test('certchain gets the certificate chain', async () => { const { exitCode, stdout } = await testUtils.pkExec( ['keys', 'certchain', '--format', 'json'], { diff --git a/tests/keys/encryptDecrypt.test.ts b/tests/keys/encryptDecrypt.test.ts index e66d3f57..f9801204 100644 --- a/tests/keys/encryptDecrypt.test.ts +++ b/tests/keys/encryptDecrypt.test.ts @@ -22,9 +22,7 @@ describe('encrypt-decrypt', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('decrypts data', async () => { + test('decrypts data', async () => { const dataPath = path.join(agentDir, 'data'); const publicKey = keysUtils.publicKeyFromNodeId(agentStatus.data.nodeId); const encrypted = keysUtils.encryptWithPublicKey( @@ -50,9 +48,7 @@ describe('encrypt-decrypt', () => { decryptedData: 'abc', }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('encrypts data using NodeId', async () => { + test('encrypts data using NodeId', async () => { const targetkeyPair = keysUtils.generateKeyPair(); const targetNodeId = keysUtils.publicKeyToNodeId(targetkeyPair.publicKey); @@ -89,9 +85,7 @@ describe('encrypt-decrypt', () => { ); expect(decrypted?.toString()).toBe('abc'); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('encrypts data using JWK file', async () => { + test('encrypts data using JWK file', async () => { const targetkeyPair = keysUtils.generateKeyPair(); const publicJWK = keysUtils.publicKeyToJWK(targetkeyPair.publicKey); @@ -123,9 +117,7 @@ describe('encrypt-decrypt', () => { ); expect(decrypted?.toString()).toBe('abc'); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('encrypts data fails with invalid JWK file', async () => { + test('encrypts data fails with invalid JWK file', async () => { const dataPath = path.join(agentDir, 'data'); const jwkPath = path.join(agentDir, 'jwk'); await fs.promises.writeFile(dataPath, 'abc', { diff --git a/tests/keys/keypair.test.ts b/tests/keys/keypair.test.ts index 2fde9738..b010246d 100644 --- a/tests/keys/keypair.test.ts +++ b/tests/keys/keypair.test.ts @@ -15,41 +15,35 @@ describe('keypair', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( - 'keypair gets private and public key', - async () => { - const { exitCode, stdout } = await testUtils.pkExec( - ['keys', 'keypair', 'password', '--format', 'json'], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, - PK_PASSWORD_NEW: 'newPassword', - }, - cwd: agentDir, - command: globalThis.testCmd, + test('keypair gets private and public key', async () => { + const { exitCode, stdout } = await testUtils.pkExec( + ['keys', 'keypair', 'password', '--format', 'json'], + { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + PK_PASSWORD_NEW: 'newPassword', }, - ); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - publicKey: { - alg: expect.any(String), - crv: expect.any(String), - ext: expect.any(Boolean), - key_ops: expect.any(Array), - kty: expect.any(String), - x: expect.any(String), - }, - privateKey: { - ciphertext: expect.any(String), - iv: expect.any(String), - protected: expect.any(String), - tag: expect.any(String), - }, - }); - }, - 40000, - ); + cwd: agentDir, + command: globalThis.testCmd, + }, + ); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + publicKey: { + alg: expect.any(String), + crv: expect.any(String), + ext: expect.any(Boolean), + key_ops: expect.any(Array), + kty: expect.any(String), + x: expect.any(String), + }, + privateKey: { + ciphertext: expect.any(String), + iv: expect.any(String), + protected: expect.any(String), + tag: expect.any(String), + }, + }); + }, 40000); }); diff --git a/tests/keys/password.test.ts b/tests/keys/password.test.ts index 090ed2cd..794df581 100644 --- a/tests/keys/password.test.ts +++ b/tests/keys/password.test.ts @@ -17,37 +17,31 @@ describe('password', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( - 'password changes the root password', - async () => { - const passPath = path.join(agentDir, 'passwordChange'); - await fs.promises.writeFile(passPath, 'password-change'); - let { exitCode } = await testUtils.pkExec( - ['keys', 'password', '--password-new-file', passPath], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, - }, - cwd: agentDir, - command: globalThis.testCmd, - }, - ); - expect(exitCode).toBe(0); - // Old password should no longer work - ({ exitCode } = await testUtils.pkExec(['keys', 'keypair'], { + test('password changes the root password', async () => { + const passPath = path.join(agentDir, 'passwordChange'); + await fs.promises.writeFile(passPath, 'password-change'); + let { exitCode } = await testUtils.pkExec( + ['keys', 'password', '--password-new-file', passPath], + { env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, - PK_PASSWORD_NEW: 'newPassword2', }, cwd: agentDir, command: globalThis.testCmd, - })); - expect(exitCode).toBe(77); - }, - 80000, - ); + }, + ); + expect(exitCode).toBe(0); + // Old password should no longer work + ({ exitCode } = await testUtils.pkExec(['keys', 'keypair'], { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + PK_PASSWORD_NEW: 'newPassword2', + }, + cwd: agentDir, + command: globalThis.testCmd, + })); + expect(exitCode).toBe(77); + }, 80000); }); diff --git a/tests/keys/private.test.ts b/tests/keys/private.test.ts index b1ae1c52..8516ee47 100644 --- a/tests/keys/private.test.ts +++ b/tests/keys/private.test.ts @@ -15,31 +15,25 @@ describe('private', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( - 'private gets private key', - async () => { - const { exitCode, stdout } = await testUtils.pkExec( - ['keys', 'private', '--format', 'json'], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, - PK_PASSWORD_NEW: 'newPassword', - }, - cwd: agentDir, - command: globalThis.testCmd, + test('private gets private key', async () => { + const { exitCode, stdout } = await testUtils.pkExec( + ['keys', 'private', '--format', 'json'], + { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + PK_PASSWORD_NEW: 'newPassword', }, - ); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - ciphertext: expect.any(String), - iv: expect.any(String), - protected: expect.any(String), - tag: expect.any(String), - }); - }, - 40000, - ); + cwd: agentDir, + command: globalThis.testCmd, + }, + ); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + ciphertext: expect.any(String), + iv: expect.any(String), + protected: expect.any(String), + tag: expect.any(String), + }); + }, 40000); }); diff --git a/tests/keys/public.test.ts b/tests/keys/public.test.ts index 8b5c63f0..521bd509 100644 --- a/tests/keys/public.test.ts +++ b/tests/keys/public.test.ts @@ -15,9 +15,7 @@ describe('public', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('public gets public key', async () => { + test('public gets public key', async () => { const { exitCode, stdout } = await testUtils.pkExec( ['keys', 'public', 'password', '--format', 'json'], { diff --git a/tests/keys/renew.test.ts b/tests/keys/renew.test.ts index b1aa9877..a5500ee3 100644 --- a/tests/keys/renew.test.ts +++ b/tests/keys/renew.test.ts @@ -40,91 +40,88 @@ describe('renew', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'renews the keypair', - async () => { - // Can't test with target executable due to mocking - // Get previous keypair and nodeId - let { exitCode, stdout } = await testUtils.pkStdio( - ['keys', 'keypair', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - PK_PASSWORD_NEW: 'some-password', - }, - cwd: dataDir, + test('renews the keypair', async () => { + // Can't test with target executable due to mocking + // Get previous keypair and nodeId + let { exitCode, stdout } = await testUtils.pkStdio( + ['keys', 'keypair', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + PK_PASSWORD_NEW: 'some-password', }, - ); - expect(exitCode).toBe(0); - const prevPublicKey = JSON.parse(stdout).publicKey; - const prevPrivateKey = JSON.parse(stdout).privateKey; - ({ exitCode, stdout } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + const prevPublicKey = JSON.parse(stdout).publicKey; + const prevPrivateKey = JSON.parse(stdout).privateKey; + ({ exitCode, stdout } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - const prevNodeId = JSON.parse(stdout).nodeId; - // Renew keypair - const passPath = path.join(dataDir, 'renew-password'); - await fs.promises.writeFile(passPath, 'password-new'); - ({ exitCode } = await testUtils.pkStdio( - ['keys', 'renew', '--password-new-file', passPath], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const prevNodeId = JSON.parse(stdout).nodeId; + // Renew keypair + const passPath = path.join(dataDir, 'renew-password'); + await fs.promises.writeFile(passPath, 'password-new'); + ({ exitCode } = await testUtils.pkStdio( + ['keys', 'renew', '--password-new-file', passPath], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - await sleep(1000); - const nodeIdEncodedNew = nodesUtils.encodeNodeId( - pkAgent.keyRing.getNodeId(), - ); - // Get new keypair and nodeId and compare against old - ({ exitCode, stdout } = await testUtils.pkStdio( - ['keys', 'keypair', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', - PK_PASSWORD_NEW: 'some-password', - PK_NODE_ID: nodeIdEncodedNew, - PK_CLIENT_HOST: '127.0.0.1', - PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + await sleep(1000); + const nodeIdEncodedNew = nodesUtils.encodeNodeId( + pkAgent.keyRing.getNodeId(), + ); + // Get new keypair and nodeId and compare against old + ({ exitCode, stdout } = await testUtils.pkStdio( + ['keys', 'keypair', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + PK_PASSWORD_NEW: 'some-password', + PK_NODE_ID: nodeIdEncodedNew, + PK_CLIENT_HOST: '127.0.0.1', + PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, }, - )); - expect(exitCode).toBe(0); - const newPublicKey = JSON.parse(stdout).publicKey; - const newPrivateKey = JSON.parse(stdout).privateKey; - ({ exitCode, stdout } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', - PK_NODE_ID: nodeIdEncodedNew, - PK_CLIENT_HOST: '127.0.0.1', - PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const newPublicKey = JSON.parse(stdout).publicKey; + const newPrivateKey = JSON.parse(stdout).privateKey; + ({ exitCode, stdout } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + PK_NODE_ID: nodeIdEncodedNew, + PK_CLIENT_HOST: '127.0.0.1', + PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, }, - )); - expect(exitCode).toBe(0); - const newNodeId = JSON.parse(stdout).nodeId; - expect(newPublicKey).not.toBe(prevPublicKey); - expect(newPrivateKey).not.toBe(prevPrivateKey); - expect(newNodeId).not.toBe(prevNodeId); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const newNodeId = JSON.parse(stdout).nodeId; + expect(newPublicKey).not.toBe(prevPublicKey); + expect(newPrivateKey).not.toBe(prevPrivateKey); + expect(newNodeId).not.toBe(prevNodeId); + }); }); diff --git a/tests/keys/reset.test.ts b/tests/keys/reset.test.ts index 3101b621..76aa9d7b 100644 --- a/tests/keys/reset.test.ts +++ b/tests/keys/reset.test.ts @@ -40,92 +40,89 @@ describe('reset', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'resets the keypair', - async () => { - // Can't test with target executable due to mocking - // Get previous keypair and nodeId - let { exitCode, stdout } = await testUtils.pkStdio( - ['keys', 'keypair', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - PK_PASSWORD_NEW: 'some-password', - }, - cwd: dataDir, + test('resets the keypair', async () => { + // Can't test with target executable due to mocking + // Get previous keypair and nodeId + let { exitCode, stdout } = await testUtils.pkStdio( + ['keys', 'keypair', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + PK_PASSWORD_NEW: 'some-password', }, - ); - expect(exitCode).toBe(0); - const prevPublicKey = JSON.parse(stdout).publicKey; - const prevPrivateKey = JSON.parse(stdout).privateKey; - ({ exitCode, stdout } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + const prevPublicKey = JSON.parse(stdout).publicKey; + const prevPrivateKey = JSON.parse(stdout).privateKey; + ({ exitCode, stdout } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - const prevNodeId = JSON.parse(stdout).nodeId; - // Reset keypair - const passPath = path.join(dataDir, 'reset-password'); - await fs.promises.writeFile(passPath, 'password-new'); - ({ exitCode } = await testUtils.pkStdio( - ['keys', 'reset', '--password-new-file', passPath], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const prevNodeId = JSON.parse(stdout).nodeId; + // Reset keypair + const passPath = path.join(dataDir, 'reset-password'); + await fs.promises.writeFile(passPath, 'password-new'); + ({ exitCode } = await testUtils.pkStdio( + ['keys', 'reset', '--password-new-file', passPath], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - )); - expect(exitCode).toBe(0); - // Wait for keys changes to propagate to the network - await sleep(1000); - const nodeIdEncodedNew = nodesUtils.encodeNodeId( - pkAgent.keyRing.getNodeId(), - ); - // Get new keypair and nodeId and compare against old - ({ exitCode, stdout } = await testUtils.pkStdio( - ['keys', 'keypair', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', - PK_PASSWORD_NEW: 'some-password', - PK_NODE_ID: nodeIdEncodedNew, - PK_CLIENT_HOST: '127.0.0.1', - PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + // Wait for keys changes to propagate to the network + await sleep(1000); + const nodeIdEncodedNew = nodesUtils.encodeNodeId( + pkAgent.keyRing.getNodeId(), + ); + // Get new keypair and nodeId and compare against old + ({ exitCode, stdout } = await testUtils.pkStdio( + ['keys', 'keypair', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + PK_PASSWORD_NEW: 'some-password', + PK_NODE_ID: nodeIdEncodedNew, + PK_CLIENT_HOST: '127.0.0.1', + PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, }, - )); - expect(exitCode).toBe(0); - const newPublicKey = JSON.parse(stdout).publicKey; - const newPrivateKey = JSON.parse(stdout).privateKey; - ({ exitCode, stdout } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', - PK_NODE_ID: nodeIdEncodedNew, - PK_CLIENT_HOST: '127.0.0.1', - PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, - }, - cwd: dataDir, + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const newPublicKey = JSON.parse(stdout).publicKey; + const newPrivateKey = JSON.parse(stdout).privateKey; + ({ exitCode, stdout } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + PK_NODE_ID: nodeIdEncodedNew, + PK_CLIENT_HOST: '127.0.0.1', + PK_CLIENT_PORT: `${pkAgent.clientServicePort}`, }, - )); - expect(exitCode).toBe(0); - const newNodeId = JSON.parse(stdout).nodeId; - expect(newPublicKey).not.toBe(prevPublicKey); - expect(newPrivateKey).not.toBe(prevPrivateKey); - expect(newNodeId).not.toBe(prevNodeId); - }, - ); + cwd: dataDir, + }, + )); + expect(exitCode).toBe(0); + const newNodeId = JSON.parse(stdout).nodeId; + expect(newPublicKey).not.toBe(prevPublicKey); + expect(newPrivateKey).not.toBe(prevPrivateKey); + expect(newNodeId).not.toBe(prevNodeId); + }); }); diff --git a/tests/keys/signVerify.test.ts b/tests/keys/signVerify.test.ts index ce184065..97dfe298 100644 --- a/tests/keys/signVerify.test.ts +++ b/tests/keys/signVerify.test.ts @@ -23,9 +23,7 @@ describe('sign-verify', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('signs a file', async () => { + test('signs a file', async () => { const publicKey = keysUtils.publicKeyFromNodeId(agentStatus.data.nodeId); const dataPath = path.join(agentDir, 'data'); await fs.promises.writeFile(dataPath, 'sign-me', { @@ -56,9 +54,7 @@ describe('sign-verify', () => { ), ).toBeTrue(); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('verifies a signature with NodeId', async () => { + test('verifies a signature with NodeId', async () => { const sourceKeyPair = keysUtils.generateKeyPair(); const nodeId = keysUtils.publicKeyToNodeId(sourceKeyPair.publicKey); const dataPath = path.join(agentDir, 'data'); @@ -97,9 +93,7 @@ describe('sign-verify', () => { signatureVerified: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('verifies a signature with JWK', async () => { + test('verifies a signature with JWK', async () => { const sourceKeyPair = keysUtils.generateKeyPair(); const jwk = keysUtils.publicKeyToJWK(sourceKeyPair.publicKey); const dataPath = path.join(agentDir, 'data'); @@ -134,9 +128,7 @@ describe('sign-verify', () => { signatureVerified: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('verifies a signature fails with invalid JWK', async () => { + test('verifies a signature fails with invalid JWK', async () => { const dataPath = path.join(agentDir, 'data'); await fs.promises.writeFile(dataPath, 'sign-me', { encoding: 'binary', diff --git a/tests/nat/DMZ.test.ts b/tests/nat/DMZ.test.ts index dc238533..5844a49f 100644 --- a/tests/nat/DMZ.test.ts +++ b/tests/nat/DMZ.test.ts @@ -15,7 +15,7 @@ import { hasUnshare, } from '../utils/platform'; -const supportsNatTesting = +const _supportsNatTesting = isPlatformLinux && hasIp && hasIptables && hasNsenter && hasUnshare; test('dummy test to avoid fail', async () => {}); @@ -34,7 +34,7 @@ describe.skip('DMZ', () => { recursive: true, }); }); - testUtils.testIf(supportsNatTesting)( + test( 'can create an agent in a namespace', async () => { const password = 'abc123'; @@ -119,7 +119,7 @@ describe.skip('DMZ', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'agents in different namespaces can ping each other', async () => { const { @@ -238,7 +238,7 @@ describe.skip('DMZ', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'agents in different namespaces can ping each other via seed node', async () => { const { diff --git a/tests/nat/endpointDependentNAT.test.ts b/tests/nat/endpointDependentNAT.test.ts index 29fcf9a3..af6d7f1a 100644 --- a/tests/nat/endpointDependentNAT.test.ts +++ b/tests/nat/endpointDependentNAT.test.ts @@ -5,7 +5,7 @@ import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as testNatUtils from './utils'; import * as testUtils from '../utils'; -const supportsNatTesting = +const _supportsNatTesting = testUtils.isPlatformLinux && testUtils.hasIp && testUtils.hasIptables && @@ -30,7 +30,7 @@ describe.skip('endpoint dependent NAT traversal', () => { recursive: true, }); }); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EDM NAT connects to node2', async () => { const { @@ -103,7 +103,7 @@ describe.skip('endpoint dependent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 connects to node2 behind EDM NAT', async () => { const { @@ -201,7 +201,7 @@ describe.skip('endpoint dependent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EDM NAT cannot connect to node2 behind EDM NAT', async () => { const { @@ -277,7 +277,7 @@ describe.skip('endpoint dependent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EDM NAT cannot connect to node2 behind EIM NAT', async () => { const { diff --git a/tests/nat/endpointIndependentNAT.test.ts b/tests/nat/endpointIndependentNAT.test.ts index 5641c471..9c724499 100644 --- a/tests/nat/endpointIndependentNAT.test.ts +++ b/tests/nat/endpointIndependentNAT.test.ts @@ -5,15 +5,13 @@ import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as testNatUtils from './utils'; import * as testUtils from '../utils'; -const supportsNatTesting = +const _supportsNatTesting = testUtils.isPlatformLinux && testUtils.hasIp && testUtils.hasIptables && testUtils.hasNsenter && testUtils.hasUnshare; -const disabled = false; - test('dummy test to avoid fail', async () => {}); // FIXME: disabled NAT testing for now, pending changes in agent migration 2 describe.skip('endpoint independent NAT traversal', () => { @@ -32,7 +30,7 @@ describe.skip('endpoint independent NAT traversal', () => { recursive: true, }); }); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EIM NAT connects to node2', async () => { const { @@ -102,7 +100,7 @@ describe.skip('endpoint independent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 connects to node2 behind EIM NAT', async () => { const { @@ -242,7 +240,7 @@ describe.skip('endpoint independent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EIM NAT connects to node2 behind EIM NAT', async () => { const { @@ -383,7 +381,7 @@ describe.skip('endpoint independent NAT traversal', () => { globalThis.defaultTimeout * 4, ); // FIXME: known issue, disabled for now - testUtils.testIf(disabled && supportsNatTesting)( + test( 'node1 behind EIM NAT connects to node2 behind EIM NAT via seed node', async () => { const { @@ -454,7 +452,7 @@ describe.skip('endpoint independent NAT traversal', () => { }, globalThis.defaultTimeout * 4, ); - testUtils.testIf(supportsNatTesting)( + test( 'node1 behind EIM NAT cannot connect to node2 behind EDM NAT', async () => { const { diff --git a/tests/nodes/add.test.ts b/tests/nodes/add.test.ts index b394b7d2..b4eac4ae 100644 --- a/tests/nodes/add.test.ts +++ b/tests/nodes/add.test.ts @@ -54,7 +54,7 @@ describe('add', () => { }); mockedPingNode.mockRestore(); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)('adds a node', async () => { + test('adds a node', async () => { const { exitCode } = await testUtils.pkStdio( [ 'nodes', @@ -79,124 +79,109 @@ describe('add', () => { nodeContact![nodesUtils.nodeContactAddress([validHost, port])], ).toBeDefined(); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'fails to add a node (invalid node ID)', - async () => { - const { exitCode } = await testUtils.pkStdio( - ['nodes', 'add', 'INVALIDNODEID', validHost, `${port}`], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('fails to add a node (invalid node ID)', async () => { + const { exitCode } = await testUtils.pkStdio( + ['nodes', 'add', 'INVALIDNODEID', validHost, `${port}`], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'fails to add a node (invalid IP address)', - async () => { - const { exitCode } = await testUtils.pkStdio( - [ - 'nodes', - 'add', - nodesUtils.encodeNodeId(validNodeId), - invalidHost, - `${port}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(sysexits.USAGE); + }); + test('fails to add a node (invalid IP address)', async () => { + const { exitCode } = await testUtils.pkStdio( + [ + 'nodes', + 'add', + nodesUtils.encodeNodeId(validNodeId), + invalidHost, + `${port}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(sysexits.USAGE); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'adds a node with --force flag', - async () => { - const { exitCode } = await testUtils.pkStdio( - [ - 'nodes', - 'add', - '--force', - nodesUtils.encodeNodeId(validNodeId), - validHost, - `${port}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(sysexits.USAGE); + }); + test('adds a node with --force flag', async () => { + const { exitCode } = await testUtils.pkStdio( + [ + 'nodes', + 'add', + '--force', + nodesUtils.encodeNodeId(validNodeId), + validHost, + `${port}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - // Checking if node was added. - const nodeContact = await pkAgent.nodeGraph.getNodeContact(validNodeId); - expect(nodeContact).toBeDefined(); - expect( - nodeContact![nodesUtils.nodeContactAddress([validHost, port])], - ).toBeDefined(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'fails to add node when ping fails', - async () => { - mockedPingNode.mockImplementation(() => false); - const { exitCode } = await testUtils.pkStdio( - [ - 'nodes', - 'add', - nodesUtils.encodeNodeId(validNodeId), - validHost, - `${port}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + // Checking if node was added. + const nodeContact = await pkAgent.nodeGraph.getNodeContact(validNodeId); + expect(nodeContact).toBeDefined(); + expect( + nodeContact![nodesUtils.nodeContactAddress([validHost, port])], + ).toBeDefined(); + }); + test('fails to add node when ping fails', async () => { + mockedPingNode.mockImplementation(() => false); + const { exitCode } = await testUtils.pkStdio( + [ + 'nodes', + 'add', + nodesUtils.encodeNodeId(validNodeId), + validHost, + `${port}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(sysexits.NOHOST); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'adds a node with --no-ping flag', - async () => { - mockedPingNode.mockImplementation(() => false); - const { exitCode } = await testUtils.pkStdio( - [ - 'nodes', - 'add', - '--no-ping', - nodesUtils.encodeNodeId(validNodeId), - validHost, - `${port}`, - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + cwd: dataDir, + }, + ); + expect(exitCode).toBe(sysexits.NOHOST); + }); + test('adds a node with --no-ping flag', async () => { + mockedPingNode.mockImplementation(() => false); + const { exitCode } = await testUtils.pkStdio( + [ + 'nodes', + 'add', + '--no-ping', + nodesUtils.encodeNodeId(validNodeId), + validHost, + `${port}`, + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - // Checking if node was added. - const nodeContact = await pkAgent.nodeGraph.getNodeContact(validNodeId); - expect(nodeContact).toBeDefined(); - expect( - nodeContact![nodesUtils.nodeContactAddress([validHost, port])], - ).toBeDefined(); - }, - ); + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + // Checking if node was added. + const nodeContact = await pkAgent.nodeGraph.getNodeContact(validNodeId); + expect(nodeContact).toBeDefined(); + expect( + nodeContact![nodesUtils.nodeContactAddress([validHost, port])], + ).toBeDefined(); + }); }); diff --git a/tests/nodes/claim.test.ts b/tests/nodes/claim.test.ts index 1ecc62aa..531f2f7e 100644 --- a/tests/nodes/claim.test.ts +++ b/tests/nodes/claim.test.ts @@ -80,25 +80,21 @@ describe('claim', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'sends a gestalt invite', - async () => { - const { exitCode, stdout } = await testUtils.pkStdio( - ['nodes', 'claim', remoteIdEncoded], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('sends a gestalt invite', async () => { + const { exitCode, stdout } = await testUtils.pkStdio( + ['nodes', 'claim', remoteIdEncoded], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - expect(stdout).toContain('Successfully generated a cryptolink claim'); - expect(stdout).toContain(remoteIdEncoded); - }, - ); - // TestUtils.testIf(testUtils.isTestPlatformEmpty) + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + expect(stdout).toContain('Successfully generated a cryptolink claim'); + expect(stdout).toContain(remoteIdEncoded); + }); test('sends a gestalt invite (force invite)', async () => { await remoteNode.notificationsManager.sendNotification(localId, { type: 'GestaltInvite', @@ -117,7 +113,7 @@ describe('claim', () => { expect(stdout).toContain('Successfully generated a cryptolink'); expect(stdout).toContain(nodesUtils.encodeNodeId(remoteId)); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)('claims a node', async () => { + test('claims a node', async () => { await remoteNode.notificationsManager.sendNotification(localId, { type: 'GestaltInvite', }); diff --git a/tests/nodes/find.test.ts b/tests/nodes/find.test.ts index fcfdf455..b40b49cc 100644 --- a/tests/nodes/find.test.ts +++ b/tests/nodes/find.test.ts @@ -97,45 +97,39 @@ describe('find', () => { recursive: true, }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'finds an online node', - async () => { - const { exitCode, stdout } = await testUtils.pkStdio( - [ - 'nodes', - 'find', - nodesUtils.encodeNodeId(remoteOnlineNodeId), - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('finds an online node', async () => { + const { exitCode, stdout } = await testUtils.pkStdio( + [ + 'nodes', + 'find', + nodesUtils.encodeNodeId(remoteOnlineNodeId), + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - const output = JSON.parse(stdout); - expect(output).toMatchObject({ - success: true, - id: nodesUtils.encodeNodeId(remoteOnlineNodeId), - }); - expect(output.address).toMatchObject({ - host: remoteOnlineHost, - port: remoteOnlinePort, - }); - expect(output.message).toMatch( - new RegExp( - `Found node at .*?${remoteOnlineHost}:${remoteOnlinePort}.*?`, - ), - ); - }, - ); + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + const output = JSON.parse(stdout); + expect(output).toMatchObject({ + success: true, + id: nodesUtils.encodeNodeId(remoteOnlineNodeId), + }); + expect(output.address).toMatchObject({ + host: remoteOnlineHost, + port: remoteOnlinePort, + }); + expect(output.message).toMatch( + new RegExp(`Found node at .*?${remoteOnlineHost}:${remoteOnlinePort}.*?`), + ); + }); // FIXME: Bug with RPC, we can't respond after timeout since client timeout forces close. - // disabled - testUtils.testIf(false && testUtils.isTestPlatformEmpty)( + test.skip( 'fails to find an unknown node', async () => { const unknownNodeId = nodesUtils.decodeNodeId( diff --git a/tests/nodes/ping.test.ts b/tests/nodes/ping.test.ts index 9a842074..93bf010b 100644 --- a/tests/nodes/ping.test.ts +++ b/tests/nodes/ping.test.ts @@ -84,8 +84,7 @@ describe('ping', () => { }); }); // FIXME: skipped because problem with RPC processing messages after timeout - // testUtils.testIf(testUtils.isTestPlatformEmpty) - testUtils.testIf(false)( + test.skip( 'fails when pinging an offline node', async () => { const { exitCode, stdout, stderr } = await testUtils.pkStdio( @@ -114,8 +113,7 @@ describe('ping', () => { globalThis.failedConnectionTimeout, ); // FIXME: skipped because problem with RPC processing messages after timeout - // testUtils.testIf(testUtils.isTestPlatformEmpty) - testUtils.testIf(false)( + test.skip( 'fails if node cannot be found', async () => { const fakeNodeId = nodesUtils.decodeNodeId( @@ -145,30 +143,27 @@ describe('ping', () => { }, globalThis.failedConnectionTimeout, ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'succeed when pinging a live node', - async () => { - const { exitCode, stdout } = await testUtils.pkStdio( - [ - 'nodes', - 'ping', - nodesUtils.encodeNodeId(remoteOnlineNodeId), - '--format', - 'json', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, + test('succeed when pinging a live node', async () => { + const { exitCode, stdout } = await testUtils.pkStdio( + [ + 'nodes', + 'ping', + nodesUtils.encodeNodeId(remoteOnlineNodeId), + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, }, - ); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - success: true, - message: 'Node is Active.', - }); - }, - ); + cwd: dataDir, + }, + ); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + success: true, + message: 'Node is Active.', + }); + }); }); diff --git a/tests/notifications/sendReadClear.test.ts b/tests/notifications/sendReadClear.test.ts index a0f8fb39..a4b0e44c 100644 --- a/tests/notifications/sendReadClear.test.ts +++ b/tests/notifications/sendReadClear.test.ts @@ -59,9 +59,7 @@ describe('send/read/claim', () => { recursive: true, }); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )( + test( 'sends, receives, and clears notifications', async () => { let exitCode, stdout; diff --git a/tests/polykey.test.ts b/tests/polykey.test.ts index b2fba167..012db0ee 100644 --- a/tests/polykey.test.ts +++ b/tests/polykey.test.ts @@ -5,19 +5,13 @@ import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as testUtils from './utils'; describe('polykey', () => { - testUtils.testIf( - testUtils.isTestPlatformEmpty || - testUtils.isTestPlatformLinux || - testUtils.isTestPlatformDocker, - )('default help display', async () => { + test('default help display', async () => { const result = await testUtils.pkExec([]); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); expect(result.stderr.length > 0).toBe(true); }); - testUtils.testIf( - testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, - )('format option affects STDERR', async () => { + test('format option affects STDERR', async () => { const logger = new Logger('format test', LogLevel.WARN, [ new StreamHandler(), ]); diff --git a/tests/secrets/secrets.test.ts b/tests/secrets/secrets.test.ts index 78a954e7..829fc939 100644 --- a/tests/secrets/secrets.test.ts +++ b/tests/secrets/secrets.test.ts @@ -53,7 +53,7 @@ describe('CLI secrets', () => { }); describe('commandCreateSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'should create secrets', async () => { const vaultName = 'Vault1' as VaultName; @@ -88,63 +88,51 @@ describe('CLI secrets', () => { ); }); describe('commandDeleteSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should delete secrets', - async () => { - const vaultName = 'Vault2' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + test('should delete secrets', async () => { + const vaultName = 'Vault2' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual(['MySecret']); - }); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual(['MySecret']); + }); - command = [ - 'secrets', - 'delete', - '-np', - dataDir, - `${vaultName}:MySecret`, - ]; + command = ['secrets', 'delete', '-np', dataDir, `${vaultName}:MySecret`]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual([]); - }); - }, - ); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual([]); + }); + }); }); describe('commandGetSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should retrieve secrets', - async () => { - const vaultName = 'Vault3' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + test('should retrieve secrets', async () => { + const vaultName = 'Vault3' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); - }); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); + }); - command = ['secrets', 'get', '-np', dataDir, `${vaultName}:MySecret`]; + command = ['secrets', 'get', '-np', dataDir, `${vaultName}:MySecret`]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.stdout).toBe('this is the secret'); - expect(result.exitCode).toBe(0); - }, - ); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.stdout).toBe('this is the secret'); + expect(result.exitCode).toBe(0); + }); }); describe('commandListSecrets', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'should list secrets', async () => { const vaultName = 'Vault4' as VaultName; @@ -168,191 +156,176 @@ describe('CLI secrets', () => { ); }); describe('commandNewDir', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should make a directory', - async () => { - const vaultName = 'Vault5' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - - command = [ - 'secrets', - 'mkdir', - '-np', - dataDir, - `${vaultName}:dir1/dir2`, - '-r', - ]; - - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); + test('should make a directory', async () => { + const vaultName = 'Vault5' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + + command = [ + 'secrets', + 'mkdir', + '-np', + dataDir, + `${vaultName}:dir1/dir2`, + '-r', + ]; + + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret( - vault, - 'dir1/MySecret1', - 'this is the secret 1', - ); - await vaultOps.addSecret( - vault, - 'dir1/dir2/MySecret2', - 'this is the secret 2', - ); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret( + vault, + 'dir1/MySecret1', + 'this is the secret 1', + ); + await vaultOps.addSecret( + vault, + 'dir1/dir2/MySecret2', + 'this is the secret 2', + ); - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual( - ['dir1/MySecret1', 'dir1/dir2/MySecret2'].sort(), - ); - }); - }, - ); + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual( + ['dir1/MySecret1', 'dir1/dir2/MySecret2'].sort(), + ); + }); + }); }); describe('commandRenameSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should rename secrets', - async () => { - const vaultName = 'Vault6' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); - }); - - command = [ - 'secrets', - 'rename', - '-np', - dataDir, - `${vaultName}:MySecret`, - 'MyRenamedSecret', - ]; - - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); + test('should rename secrets', async () => { + const vaultName = 'Vault6' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); + }); + + command = [ + 'secrets', + 'rename', + '-np', + dataDir, + `${vaultName}:MySecret`, + 'MyRenamedSecret', + ]; + + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual(['MyRenamedSecret']); - }); - }, - ); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual(['MyRenamedSecret']); + }); + }); }); describe('commandUpdateSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should update secrets', - async () => { - const vaultName = 'Vault7' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - - const secretPath = path.join(dataDir, 'secret'); - await fs.promises.writeFile(secretPath, 'updated-content'); - - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret(vault, 'MySecret', 'original-content'); - expect( - (await vaultOps.getSecret(vault, 'MySecret')).toString(), - ).toStrictEqual('original-content'); - }); - - command = [ - 'secrets', - 'update', - '-np', - dataDir, - secretPath, - `${vaultName}:MySecret`, - ]; - - const result2 = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); - - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual(['MySecret']); - expect( - (await vaultOps.getSecret(vault, 'MySecret')).toString(), - ).toStrictEqual('updated-content'); - }); - }, - ); + test('should update secrets', async () => { + const vaultName = 'Vault7' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + + const secretPath = path.join(dataDir, 'secret'); + await fs.promises.writeFile(secretPath, 'updated-content'); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret(vault, 'MySecret', 'original-content'); + expect( + (await vaultOps.getSecret(vault, 'MySecret')).toString(), + ).toStrictEqual('original-content'); + }); + + command = [ + 'secrets', + 'update', + '-np', + dataDir, + secretPath, + `${vaultName}:MySecret`, + ]; + + const result2 = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual(['MySecret']); + expect( + (await vaultOps.getSecret(vault, 'MySecret')).toString(), + ).toStrictEqual('updated-content'); + }); + }); }); describe('commandNewDirSecret', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should add a directory of secrets', - async () => { - const vaultName = 'Vault8' as VaultName; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - - const secretDir = path.join(dataDir, 'secrets'); - await fs.promises.mkdir(secretDir); - await fs.promises.writeFile( - path.join(secretDir, 'secret-1'), - 'this is the secret 1', - ); - await fs.promises.writeFile( - path.join(secretDir, 'secret-2'), - 'this is the secret 2', - ); - await fs.promises.writeFile( - path.join(secretDir, 'secret-3'), - 'this is the secret 3', - ); - - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual([]); - }); - - command = ['secrets', 'dir', '-np', dataDir, secretDir, vaultName]; - - const result2 = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); - - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const list = await vaultOps.listSecrets(vault); - expect(list.sort()).toStrictEqual([ - 'secrets/secret-1', - 'secrets/secret-2', - 'secrets/secret-3', - ]); - }); - }, - ); + test('should add a directory of secrets', async () => { + const vaultName = 'Vault8' as VaultName; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + + const secretDir = path.join(dataDir, 'secrets'); + await fs.promises.mkdir(secretDir); + await fs.promises.writeFile( + path.join(secretDir, 'secret-1'), + 'this is the secret 1', + ); + await fs.promises.writeFile( + path.join(secretDir, 'secret-2'), + 'this is the secret 2', + ); + await fs.promises.writeFile( + path.join(secretDir, 'secret-3'), + 'this is the secret 3', + ); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual([]); + }); + + command = ['secrets', 'dir', '-np', dataDir, secretDir, vaultName]; + + const result2 = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const list = await vaultOps.listSecrets(vault); + expect(list.sort()).toStrictEqual([ + 'secrets/secret-1', + 'secrets/secret-2', + 'secrets/secret-3', + ]); + }); + }); }); describe('commandStat', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should retrieve secrets', - async () => { - const vaultName = 'Vault9'; - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + test('should retrieve secrets', async () => { + const vaultName = 'Vault9'; + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); - }); + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + await vaultOps.addSecret(vault, 'MySecret', 'this is the secret'); + }); - command = ['secrets', 'stat', '-np', dataDir, `${vaultName}:MySecret`]; + command = ['secrets', 'stat', '-np', dataDir, `${vaultName}:MySecret`]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); - expect(result.stdout).toContain('nlink: 1'); - expect(result.stdout).toContain('blocks: 1'); - expect(result.stdout).toContain('blksize: 4096'); - expect(result.stdout).toContain('size: 18'); - }, - ); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('nlink: 1'); + expect(result.stdout).toContain('blocks: 1'); + expect(result.stdout).toContain('blksize: 4096'); + expect(result.stdout).toContain('size: 18'); + }); }); }); diff --git a/tests/sessions.test.ts b/tests/sessions.test.ts index a0f645bc..25400982 100644 --- a/tests/sessions.test.ts +++ b/tests/sessions.test.ts @@ -38,136 +38,124 @@ describe('sessions', () => { }); await agentClose(); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'serial commands refresh the session token', - async () => { - const session = await Session.createSession({ - sessionTokenPath: path.join(agentDir, config.paths.tokenBase), - fs, - logger, - }); - let exitCode; - ({ exitCode } = await testUtils.pkStdio(['agent', 'status'], { + test('serial commands refresh the session token', async () => { + const session = await Session.createSession({ + sessionTokenPath: path.join(agentDir, config.paths.tokenBase), + fs, + logger, + }); + let exitCode; + ({ exitCode } = await testUtils.pkStdio(['agent', 'status'], { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, + })); + expect(exitCode).toBe(0); + const token1 = await session.readToken(); + // Tokens are not nonces + // Wait at least 1 second + // To ensure that the next token has a new expiry + await sleep(1100); + ({ exitCode } = await testUtils.pkStdio(['agent', 'status'], { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, + })); + expect(exitCode).toBe(0); + const token2 = await session.readToken(); + expect(token1).not.toBe(token2); + await session.stop(); + }); + test('unattended commands with invalid authentication should fail', async () => { + let exitCode, stderr; + // Password and Token set + ({ exitCode, stderr } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { env: { PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + PK_PASSWORD: 'invalid', + PK_TOKEN: 'token', }, cwd: agentDir, - })); - expect(exitCode).toBe(0); - const token1 = await session.readToken(); - // Tokens are not nonces - // Wait at least 1 second - // To ensure that the next token has a new expiry - await sleep(1100); - ({ exitCode } = await testUtils.pkStdio(['agent', 'status'], { + }, + )); + + testUtils.expectProcessError(exitCode, stderr, [ + new clientErrors.ErrorClientAuthDenied(), + ]); + // Password set + ({ exitCode, stderr } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { env: { PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + PK_PASSWORD: 'invalid', + PK_TOKEN: undefined, }, cwd: agentDir, - })); - expect(exitCode).toBe(0); - const token2 = await session.readToken(); - expect(token1).not.toBe(token2); - await session.stop(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'unattended commands with invalid authentication should fail', - async () => { - let exitCode, stderr; - // Password and Token set - ({ exitCode, stderr } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: 'invalid', - PK_TOKEN: 'token', - }, - cwd: agentDir, - }, - )); - - testUtils.expectProcessError(exitCode, stderr, [ - new clientErrors.ErrorClientAuthDenied(), - ]); - // Password set - ({ exitCode, stderr } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: 'invalid', - PK_TOKEN: undefined, - }, - cwd: agentDir, - }, - )); - testUtils.expectProcessError(exitCode, stderr, [ - new clientErrors.ErrorClientAuthDenied(), - ]); - // Token set - ({ exitCode, stderr } = await testUtils.pkStdio( - ['agent', 'status', '--format', 'json'], - { - env: { - PK_NODE_PATH: agentDir, - PK_PASSWORD: undefined, - PK_TOKEN: 'token', - }, - cwd: agentDir, + }, + )); + testUtils.expectProcessError(exitCode, stderr, [ + new clientErrors.ErrorClientAuthDenied(), + ]); + // Token set + ({ exitCode, stderr } = await testUtils.pkStdio( + ['agent', 'status', '--format', 'json'], + { + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: undefined, + PK_TOKEN: 'token', }, - )); - testUtils.expectProcessError(exitCode, stderr, [ - new clientErrors.ErrorClientAuthDenied(), - ]); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'prompt for password to authenticate attended commands', - async () => { - const password = agentPassword; - await testUtils.pkStdio(['agent', 'lock'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - prompts.mockClear(); - prompts.mockImplementation(async (_opts: any) => { - return { password }; - }); - const { exitCode } = await testUtils.pkStdio(['agent', 'status'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - expect(exitCode).toBe(0); - // Prompted for password 1 time - expect(prompts.mock.calls.length).toBe(1); - prompts.mockClear(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 're-prompts for password if unable to authenticate command', - async () => { - await testUtils.pkStdio(['agent', 'lock'], { - env: { PK_NODE_PATH: agentDir }, cwd: agentDir, - }); - const validPassword = agentPassword; - const invalidPassword = 'invalid'; - prompts.mockClear(); - prompts - .mockResolvedValueOnce({ password: invalidPassword }) - .mockResolvedValue({ password: validPassword }); - const { exitCode } = await testUtils.pkStdio(['agent', 'status'], { - env: { PK_NODE_PATH: agentDir }, - cwd: agentDir, - }); - expect(exitCode).toBe(0); - // Prompted for password 2 times - expect(prompts.mock.calls.length).toBe(2); - prompts.mockClear(); - }, - ); + }, + )); + testUtils.expectProcessError(exitCode, stderr, [ + new clientErrors.ErrorClientAuthDenied(), + ]); + }); + test('prompt for password to authenticate attended commands', async () => { + const password = agentPassword; + await testUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + prompts.mockClear(); + prompts.mockImplementation(async (_opts: any) => { + return { password }; + }); + const { exitCode } = await testUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + expect(exitCode).toBe(0); + // Prompted for password 1 time + expect(prompts.mock.calls.length).toBe(1); + prompts.mockClear(); + }); + test('re-prompts for password if unable to authenticate command', async () => { + await testUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + const validPassword = agentPassword; + const invalidPassword = 'invalid'; + prompts.mockClear(); + prompts + .mockResolvedValueOnce({ password: invalidPassword }) + .mockResolvedValue({ password: validPassword }); + const { exitCode } = await testUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); + expect(exitCode).toBe(0); + // Prompted for password 2 times + expect(prompts.mock.calls.length).toBe(2); + prompts.mockClear(); + }); }); diff --git a/tests/utils.retryAuthentication.test.ts b/tests/utils.retryAuthentication.test.ts index b30591c5..3b6a9423 100644 --- a/tests/utils.retryAuthentication.test.ts +++ b/tests/utils.retryAuthentication.test.ts @@ -3,184 +3,159 @@ import mockedEnv from 'mocked-env'; import * as clientUtils from 'polykey/dist/client/utils'; import * as clientErrors from 'polykey/dist/client/errors'; import * as binUtils from '@/utils'; -import * as testUtils from './utils'; jest.mock('prompts'); describe('bin/utils retryAuthentication', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'no retry on success', - async () => { - const mockCallSuccess = jest.fn().mockResolvedValue('hello world'); - const result = await binUtils.retryAuthentication(mockCallSuccess); - expect(mockCallSuccess.mock.calls.length).toBe(1); - expect(result).toBe('hello world'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'no retry on generic error', - async () => { - const error = new Error('oh no'); - const mockCallFail = jest.fn().mockRejectedValue(error); - await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( - /oh no/, - ); - expect(mockCallFail.mock.calls.length).toBe(1); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'no retry on unattended call with PK_TOKEN and PK_PASSWORD', - async () => { - const mockCallFail = jest - .fn() - .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); - const envRestore = mockedEnv({ - PK_TOKEN: 'hello', - PK_PASSWORD: 'world', - }); - await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( - clientErrors.ErrorClientAuthMissing, - ); - envRestore(); - expect(mockCallFail.mock.calls.length).toBe(1); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'no retry on unattended call with PK_TOKEN', - async () => { - const mockCallFail = jest - .fn() - .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); - const envRestore = mockedEnv({ - PK_TOKEN: 'hello', - PK_PASSWORD: undefined, - }); - await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( - clientErrors.ErrorClientAuthMissing, - ); - envRestore(); - expect(mockCallFail.mock.calls.length).toBe(1); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'no retry on unattended call with PK_PASSWORD', - async () => { - const mockCallFail = jest - .fn() - .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); - const envRestore = mockedEnv({ - PK_TOKEN: undefined, - PK_PASSWORD: 'world', - }); - await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( - clientErrors.ErrorClientAuthMissing, - ); - envRestore(); - expect(mockCallFail.mock.calls.length).toBe(1); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'retry once on clientErrors.ErrorClientAuthMissing', - async () => { - const password = 'the password'; - // Password prompt will return hello world - prompts.mockImplementation(async (_opts: any) => { - return { password }; - }); - // Call will reject with ErrorClientAuthMissing then succeed - const mockCall = jest - .fn() - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) - .mockResolvedValue('hello world'); - // Make this an attended call - const envRestore = mockedEnv({ - PK_TOKEN: undefined, - PK_PASSWORD: undefined, - }); - const result = await binUtils.retryAuthentication(mockCall); - envRestore(); - // Result is successful - expect(result).toBe('hello world'); - // Call was tried 2 times - expect(mockCall.mock.calls.length).toBe(2); - // Prompted for password 1 time - expect(prompts.mock.calls.length).toBe(1); - // Authorization metadata was set - const auth = mockCall.mock.calls[1][0].authorization; - expect(auth).toBeDefined(); - expect(auth).toBe(clientUtils.encodeAuthFromPassword(password)); - prompts.mockClear(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'retry 2 times on clientErrors.ErrorClientAuthDenied', - async () => { - const password1 = 'first password'; - const password2 = 'second password'; - prompts.mockClear(); - prompts - .mockResolvedValueOnce({ password: password1 }) - .mockResolvedValue({ password: password2 }); - // Call will reject with ErrorClientAuthMissing then succeed - const mockCall = jest - .fn() - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) - .mockResolvedValue('hello world'); - // Make this an attended call - const envRestore = mockedEnv({ - PK_TOKEN: undefined, - PK_PASSWORD: undefined, - }); - const result = await binUtils.retryAuthentication(mockCall); - envRestore(); - // Result is successful - expect(result).toBe('hello world'); - // Call was tried 3 times - expect(mockCall.mock.calls.length).toBe(3); - // Prompted for password 2 times - expect(prompts.mock.calls.length).toBe(2); - // Authorization metadata was set - const auth = mockCall.mock.calls[2][0].authorization; - expect(auth).toBeDefined(); - // Second password succeeded - expect(auth).toBe(clientUtils.encodeAuthFromPassword(password2)); - prompts.mockClear(); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'retry 2+ times on clientErrors.ErrorClientAuthDenied until generic error', - async () => { - const password1 = 'first password'; - const password2 = 'second password'; - prompts.mockClear(); - prompts - .mockResolvedValueOnce({ password: password1 }) - .mockResolvedValue({ password: password2 }); - // Call will reject with ErrorClientAuthMissing then succeed - const mockCall = jest - .fn() - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) - .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) - .mockRejectedValue(new Error('oh no')); - // Make this an attended call - const envRestore = mockedEnv({ - PK_TOKEN: undefined, - PK_PASSWORD: undefined, - }); - await expect(binUtils.retryAuthentication(mockCall)).rejects.toThrow( - /oh no/, - ); - envRestore(); - expect(mockCall.mock.calls.length).toBe(5); - expect(prompts.mock.calls.length).toBe(4); - const auth = mockCall.mock.calls[4][0].authorization; - expect(auth).toBeDefined(); - // Second password was the last used - expect(auth).toBe(clientUtils.encodeAuthFromPassword(password2)); - prompts.mockClear(); - }, - ); + test('no retry on success', async () => { + const mockCallSuccess = jest.fn().mockResolvedValue('hello world'); + const result = await binUtils.retryAuthentication(mockCallSuccess); + expect(mockCallSuccess.mock.calls.length).toBe(1); + expect(result).toBe('hello world'); + }); + test('no retry on generic error', async () => { + const error = new Error('oh no'); + const mockCallFail = jest.fn().mockRejectedValue(error); + await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( + /oh no/, + ); + expect(mockCallFail.mock.calls.length).toBe(1); + }); + test('no retry on unattended call with PK_TOKEN and PK_PASSWORD', async () => { + const mockCallFail = jest + .fn() + .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); + const envRestore = mockedEnv({ + PK_TOKEN: 'hello', + PK_PASSWORD: 'world', + }); + await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( + clientErrors.ErrorClientAuthMissing, + ); + envRestore(); + expect(mockCallFail.mock.calls.length).toBe(1); + }); + test('no retry on unattended call with PK_TOKEN', async () => { + const mockCallFail = jest + .fn() + .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); + const envRestore = mockedEnv({ + PK_TOKEN: 'hello', + PK_PASSWORD: undefined, + }); + await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( + clientErrors.ErrorClientAuthMissing, + ); + envRestore(); + expect(mockCallFail.mock.calls.length).toBe(1); + }); + test('no retry on unattended call with PK_PASSWORD', async () => { + const mockCallFail = jest + .fn() + .mockRejectedValue(new clientErrors.ErrorClientAuthMissing()); + const envRestore = mockedEnv({ + PK_TOKEN: undefined, + PK_PASSWORD: 'world', + }); + await expect(binUtils.retryAuthentication(mockCallFail)).rejects.toThrow( + clientErrors.ErrorClientAuthMissing, + ); + envRestore(); + expect(mockCallFail.mock.calls.length).toBe(1); + }); + test('retry once on clientErrors.ErrorClientAuthMissing', async () => { + const password = 'the password'; + // Password prompt will return hello world + prompts.mockImplementation(async (_opts: any) => { + return { password }; + }); + // Call will reject with ErrorClientAuthMissing then succeed + const mockCall = jest + .fn() + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) + .mockResolvedValue('hello world'); + // Make this an attended call + const envRestore = mockedEnv({ + PK_TOKEN: undefined, + PK_PASSWORD: undefined, + }); + const result = await binUtils.retryAuthentication(mockCall); + envRestore(); + // Result is successful + expect(result).toBe('hello world'); + // Call was tried 2 times + expect(mockCall.mock.calls.length).toBe(2); + // Prompted for password 1 time + expect(prompts.mock.calls.length).toBe(1); + // Authorization metadata was set + const auth = mockCall.mock.calls[1][0].authorization; + expect(auth).toBeDefined(); + expect(auth).toBe(clientUtils.encodeAuthFromPassword(password)); + prompts.mockClear(); + }); + test('retry 2 times on clientErrors.ErrorClientAuthDenied', async () => { + const password1 = 'first password'; + const password2 = 'second password'; + prompts.mockClear(); + prompts + .mockResolvedValueOnce({ password: password1 }) + .mockResolvedValue({ password: password2 }); + // Call will reject with ErrorClientAuthMissing then succeed + const mockCall = jest + .fn() + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) + .mockResolvedValue('hello world'); + // Make this an attended call + const envRestore = mockedEnv({ + PK_TOKEN: undefined, + PK_PASSWORD: undefined, + }); + const result = await binUtils.retryAuthentication(mockCall); + envRestore(); + // Result is successful + expect(result).toBe('hello world'); + // Call was tried 3 times + expect(mockCall.mock.calls.length).toBe(3); + // Prompted for password 2 times + expect(prompts.mock.calls.length).toBe(2); + // Authorization metadata was set + const auth = mockCall.mock.calls[2][0].authorization; + expect(auth).toBeDefined(); + // Second password succeeded + expect(auth).toBe(clientUtils.encodeAuthFromPassword(password2)); + prompts.mockClear(); + }); + test('retry 2+ times on clientErrors.ErrorClientAuthDenied until generic error', async () => { + const password1 = 'first password'; + const password2 = 'second password'; + prompts.mockClear(); + prompts + .mockResolvedValueOnce({ password: password1 }) + .mockResolvedValue({ password: password2 }); + // Call will reject with ErrorClientAuthMissing then succeed + const mockCall = jest + .fn() + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthMissing()) + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) + .mockRejectedValueOnce(new clientErrors.ErrorClientAuthDenied()) + .mockRejectedValue(new Error('oh no')); + // Make this an attended call + const envRestore = mockedEnv({ + PK_TOKEN: undefined, + PK_PASSWORD: undefined, + }); + await expect(binUtils.retryAuthentication(mockCall)).rejects.toThrow( + /oh no/, + ); + envRestore(); + expect(mockCall.mock.calls.length).toBe(5); + expect(prompts.mock.calls.length).toBe(4); + const auth = mockCall.mock.calls[4][0].authorization; + expect(auth).toBeDefined(); + // Second password was the last used + expect(auth).toBe(clientUtils.encodeAuthFromPassword(password2)); + prompts.mockClear(); + }); }); diff --git a/tests/utils.test.ts b/tests/utils.test.ts index c00490ef..8ddd69af 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -5,7 +5,6 @@ import * as nodesUtils from 'polykey/dist/nodes/utils'; import * as polykeyErrors from 'polykey/dist/errors'; import * as fc from 'fast-check'; import * as binUtils from '@/utils/utils'; -import * as testUtils from './utils'; const nonPrintableCharArb = fc .oneof( @@ -19,313 +18,282 @@ const stringWithNonPrintableCharsArb = fc.stringOf( ); describe('bin/utils', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'list in human and json format', - () => { - // List - expect( - binUtils.outputFormatter({ - type: 'list', - data: ['Testing', 'the', 'list', 'output'], - }), - ).toBe('Testing\nthe\nlist\noutput\n'); - // JSON - expect( - binUtils.outputFormatter({ - type: 'json', - data: ['Testing', 'the', 'list', 'output'], - }), - ).toBe('["Testing","the","list","output"]\n'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'table in human and in json format', - async () => { - const tableOutput = binUtils.outputFormatter({ + test('list in human and json format', () => { + // List + expect( + binUtils.outputFormatter({ + type: 'list', + data: ['Testing', 'the', 'list', 'output'], + }), + ).toBe('Testing\nthe\nlist\noutput\n'); + // JSON + expect( + binUtils.outputFormatter({ + type: 'json', + data: ['Testing', 'the', 'list', 'output'], + }), + ).toBe('["Testing","the","list","output"]\n'); + }); + test('table in human and in json format', async () => { + const tableOutput = binUtils.outputFormatter({ + type: 'table', + data: [ + { key1: 'value1', key2: 'value2' }, + { key1: 'data1', key2: 'data2' }, + { key1: null, key2: undefined }, + ], + options: { + includeHeaders: true, + }, + }); + expect(tableOutput).toBe('value1\tvalue2\ndata1 \tdata2\nN/A \tN/A\n'); + + // JSON + const jsonOutput = binUtils.outputFormatter({ + type: 'json', + data: [ + { key1: 'value1', key2: 'value2' }, + { key1: 'data1', key2: 'data2' }, + ], + }); + expect(jsonOutput).toBe( + '[{"key1":"value1","key2":"value2"},{"key1":"data1","key2":"data2"}]\n', + ); + }); + test('table in human format for streaming usage', async () => { + let tableOutput = ''; + const keys = { + key1: 10, + key2: 4, + }; + const generator = function* () { + yield [{ key1: 'value1', key2: 'value2' }]; + yield [{ key1: 'data1', key2: 'data2' }]; + yield [{ key1: null, key2: undefined }]; + }; + let i = 0; + for (const data of generator()) { + tableOutput += binUtils.outputFormatter({ type: 'table', - data: [ - { key1: 'value1', key2: 'value2' }, - { key1: 'data1', key2: 'data2' }, - { key1: null, key2: undefined }, - ], + data: data, options: { - includeHeaders: true, + columns: keys, + includeHeaders: i === 0, }, }); - expect(tableOutput).toBe('value1\tvalue2\ndata1 \tdata2\nN/A \tN/A\n'); - - // JSON - const jsonOutput = binUtils.outputFormatter({ + i++; + } + expect(keys).toStrictEqual({ + key1: 10, + key2: 6, + }); + expect(tableOutput).toBe( + 'key1 \tkey2 \nvalue1 \tvalue2\ndata1 \tdata2\nN/A \tN/A\n', + ); + }); + test('dict in human and in json format', () => { + // Dict + expect( + binUtils.outputFormatter({ + type: 'dict', + data: { key1: 'value1', key2: 'value2' }, + }), + ).toBe('key1\tvalue1\nkey2\tvalue2\n'); + expect( + binUtils.outputFormatter({ + type: 'dict', + data: { key1: 'first\nsecond', key2: 'first\nsecond\n' }, + }), + ).toBe('key1\t"first\\nsecond"\nkey2\t"first\\nsecond\\n"\n'); + expect( + binUtils.outputFormatter({ + type: 'dict', + data: { key1: null, key2: undefined }, + }), + ).toBe('key1\t\nkey2\t\n'); + // JSON + expect( + binUtils.outputFormatter({ type: 'json', - data: [ - { key1: 'value1', key2: 'value2' }, - { key1: 'data1', key2: 'data2' }, - ], - }); - expect(jsonOutput).toBe( - '[{"key1":"value1","key2":"value2"},{"key1":"data1","key2":"data2"}]\n', - ); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'table in human format for streaming usage', - async () => { - let tableOutput = ''; - const keys = { - key1: 10, - key2: 4, - }; - const generator = function* () { - yield [{ key1: 'value1', key2: 'value2' }]; - yield [{ key1: 'data1', key2: 'data2' }]; - yield [{ key1: null, key2: undefined }]; - }; - let i = 0; - for (const data of generator()) { - tableOutput += binUtils.outputFormatter({ - type: 'table', - data: data, - options: { - columns: keys, - includeHeaders: i === 0, - }, - }); - i++; - } - expect(keys).toStrictEqual({ - key1: 10, - key2: 6, - }); - expect(tableOutput).toBe( - 'key1 \tkey2 \nvalue1 \tvalue2\ndata1 \tdata2\nN/A \tN/A\n', - ); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'dict in human and in json format', - () => { - // Dict - expect( - binUtils.outputFormatter({ - type: 'dict', - data: { key1: 'value1', key2: 'value2' }, - }), - ).toBe('key1\tvalue1\nkey2\tvalue2\n'); - expect( - binUtils.outputFormatter({ - type: 'dict', - data: { key1: 'first\nsecond', key2: 'first\nsecond\n' }, - }), - ).toBe('key1\t"first\\nsecond"\nkey2\t"first\\nsecond\\n"\n'); - expect( - binUtils.outputFormatter({ - type: 'dict', - data: { key1: null, key2: undefined }, - }), - ).toBe('key1\t\nkey2\t\n'); - // JSON - expect( - binUtils.outputFormatter({ - type: 'json', - data: { key1: 'value1', key2: 'value2' }, - }), - ).toBe('{"key1":"value1","key2":"value2"}\n'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'outputFormatter should encode non-printable characters within a dict', - () => { - fc.assert( - fc.property( - stringWithNonPrintableCharsArb, - stringWithNonPrintableCharsArb, - (key, value) => { - const formattedOutput = binUtils.outputFormatter({ - type: 'dict', - data: { [key]: value }, - }); + data: { key1: 'value1', key2: 'value2' }, + }), + ).toBe('{"key1":"value1","key2":"value2"}\n'); + }); + test('outputFormatter should encode non-printable characters within a dict', () => { + fc.assert( + fc.property( + stringWithNonPrintableCharsArb, + stringWithNonPrintableCharsArb, + (key, value) => { + const formattedOutput = binUtils.outputFormatter({ + type: 'dict', + data: { [key]: value }, + }); - const expectedKey = binUtils.encodeEscapedWrapped(key); + const expectedKey = binUtils.encodeEscapedWrapped(key); - // Construct the expected output - let expectedValue = value; - expectedValue = binUtils.encodeEscapedWrapped(expectedValue); - expectedValue = expectedValue.replace(/(?:\r\n|\n)$/, ''); - expectedValue = expectedValue.replace(/(\r\n|\n)/g, '$1\t'); + // Construct the expected output + let expectedValue = value; + expectedValue = binUtils.encodeEscapedWrapped(expectedValue); + expectedValue = expectedValue.replace(/(?:\r\n|\n)$/, ''); + expectedValue = expectedValue.replace(/(\r\n|\n)/g, '$1\t'); - const maxKeyLength = Math.max( - ...Object.keys({ [key]: value }).map((k) => k.length), - ); - const padding = ' '.repeat(maxKeyLength - key.length); - const expectedOutput = `${expectedKey}${padding}\t${expectedValue}\n`; - // Assert that the formatted output matches the expected output - expect(formattedOutput).toBe(expectedOutput); + const maxKeyLength = Math.max( + ...Object.keys({ [key]: value }).map((k) => k.length), + ); + const padding = ' '.repeat(maxKeyLength - key.length); + const expectedOutput = `${expectedKey}${padding}\t${expectedValue}\n`; + // Assert that the formatted output matches the expected output + expect(formattedOutput).toBe(expectedOutput); + }, + ), + { numRuns: 100 }, // Number of times to run the test + ); + }); + test('errors in human and json format', () => { + const nodeIdGenerator = ids.createNodeIdGenerator(); + const timestamp = new Date(); + const data = { string: 'one', number: 1 }; + const host = '127.0.0.1' as Host; + const port = 55555 as Port; + const nodeId = nodeIdGenerator(); + const standardError = new TypeError('some error'); + const pkError = new ErrorPolykey('some pk error', { + timestamp, + data, + }); + const remoteError = new polykeyErrors.ErrorPolykeyRemote( + { + nodeId: nodesUtils.encodeNodeId(nodeId), + host, + port, + command: 'some command', + }, + 'some remote error', + { timestamp, cause: pkError }, + ); + const twoRemoteErrors = new polykeyErrors.ErrorPolykeyRemote( + { + nodeId: nodesUtils.encodeNodeId(nodeId), + host, + port, + command: 'command 2', + }, + 'remote error', + { + timestamp, + cause: new polykeyErrors.ErrorPolykeyRemote( + { + nodeId: nodesUtils.encodeNodeId(nodeId), + host, + port, + command: 'command 1', + }, + undefined, + { + timestamp, + cause: new ErrorPolykey('pk error', { + timestamp, + cause: standardError, + }), }, ), - { numRuns: 100 }, // Number of times to run the test - ); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'errors in human and json format', - () => { - const nodeIdGenerator = ids.createNodeIdGenerator(); - const timestamp = new Date(); - const data = { string: 'one', number: 1 }; - const host = '127.0.0.1' as Host; - const port = 55555 as Port; - const nodeId = nodeIdGenerator(); - const standardError = new TypeError('some error'); - const pkError = new ErrorPolykey('some pk error', { - timestamp, - data, - }); - const remoteError = new polykeyErrors.ErrorPolykeyRemote( - { - nodeId: nodesUtils.encodeNodeId(nodeId), - host, - port, - command: 'some command', - }, - 'some remote error', - { timestamp, cause: pkError }, - ); - const twoRemoteErrors = new polykeyErrors.ErrorPolykeyRemote( - { - nodeId: nodesUtils.encodeNodeId(nodeId), - host, - port, - command: 'command 2', - }, - 'remote error', - { - timestamp, - cause: new polykeyErrors.ErrorPolykeyRemote( - { - nodeId: nodesUtils.encodeNodeId(nodeId), - host, - port, - command: 'command 1', + }, + ); + // Human + expect( + binUtils.outputFormatter({ type: 'error', data: standardError }), + ).toBe(`${standardError.name}: ${standardError.message}\n`); + expect(binUtils.outputFormatter({ type: 'error', data: pkError })).toBe( + `${pkError.name}: ${pkError.description} - ${pkError.message}\n` + + ` data\t${JSON.stringify(data)}\n`, + ); + expect(binUtils.outputFormatter({ type: 'error', data: remoteError })).toBe( + `${remoteError.name}: ${remoteError.description} - ${remoteError.message}\n` + + ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + + ` host\t${host}\n` + + ` port\t${port}\n` + + ` command\tsome command\n` + + ` timestamp\t${timestamp.toString()}\n` + + ` cause: ${remoteError.cause.name}: ${remoteError.cause.description} - ${remoteError.cause.message}\n` + + ` data\t${JSON.stringify(data)}\n`, + ); + expect( + binUtils.outputFormatter({ type: 'error', data: twoRemoteErrors }), + ).toBe( + `${twoRemoteErrors.name}: ${twoRemoteErrors.description} - ${twoRemoteErrors.message}\n` + + ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + + ` host\t${host}\n` + + ` port\t${port}\n` + + ` command\tcommand 2\n` + + ` timestamp\t${timestamp.toString()}\n` + + ` cause: ${twoRemoteErrors.cause.name}: ${twoRemoteErrors.cause.description}\n` + + ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + + ` host\t${host}\n` + + ` port\t${port}\n` + + ` command\t${twoRemoteErrors.cause.metadata.command}\n` + + ` timestamp\t${timestamp.toString()}\n` + + ` cause: ${twoRemoteErrors.cause.cause.name}: ${twoRemoteErrors.cause.cause.description} - ${twoRemoteErrors.cause.cause.message}\n` + + ` cause: ${standardError.name}: ${standardError.message}\n`, + ); + // JSON + expect( + binUtils.outputFormatter({ type: 'json', data: standardError }), + ).toBe( + `{"type":"${standardError.name}","data":{"message":"${ + standardError.message + }","stack":"${standardError.stack?.replaceAll('\n', '\\n')}"}}\n`, + ); + expect(binUtils.outputFormatter({ type: 'json', data: pkError })).toBe( + JSON.stringify(pkError.toJSON()) + '\n', + ); + expect(binUtils.outputFormatter({ type: 'json', data: remoteError })).toBe( + JSON.stringify(remoteError.toJSON()) + '\n', + ); + expect( + binUtils.outputFormatter({ type: 'json', data: twoRemoteErrors }), + ).toBe( + JSON.stringify(twoRemoteErrors.toJSON(), binUtils.standardErrorReplacer) + + '\n', + ); + }); + test('encodeEscaped should encode all escapable characters', () => { + fc.assert( + fc.property(stringWithNonPrintableCharsArb, (value) => { + expect(binUtils.decodeEscaped(binUtils.encodeEscaped(value))).toBe( + value, + ); + }), + { numRuns: 100 }, // Number of times to run the test + ); + }); + test('encodeEscapedReplacer should encode all escapable characters', () => { + fc.assert( + fc.property( + stringWithNonPrintableCharsArb, + stringWithNonPrintableCharsArb, + (key, value) => { + const encodedKey = binUtils.encodeEscaped(key); + const encodedValue = binUtils.encodeEscaped(value); + const object = { + [key]: value, + [key]: { + [key]: value, }, - undefined, - { - timestamp, - cause: new ErrorPolykey('pk error', { - timestamp, - cause: standardError, - }), + [key]: [value], + }; + const encodedObject = { + [encodedKey]: encodedValue, + [encodedKey]: { + [encodedKey]: encodedValue, }, - ), + [encodedKey]: [encodedValue], + }; + const output = JSON.stringify(object, binUtils.encodeEscapedReplacer); + expect(JSON.parse(output)).toEqual(encodedObject); }, - ); - // Human - expect( - binUtils.outputFormatter({ type: 'error', data: standardError }), - ).toBe(`${standardError.name}: ${standardError.message}\n`); - expect(binUtils.outputFormatter({ type: 'error', data: pkError })).toBe( - `${pkError.name}: ${pkError.description} - ${pkError.message}\n` + - ` data\t${JSON.stringify(data)}\n`, - ); - expect( - binUtils.outputFormatter({ type: 'error', data: remoteError }), - ).toBe( - `${remoteError.name}: ${remoteError.description} - ${remoteError.message}\n` + - ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + - ` host\t${host}\n` + - ` port\t${port}\n` + - ` command\tsome command\n` + - ` timestamp\t${timestamp.toString()}\n` + - ` cause: ${remoteError.cause.name}: ${remoteError.cause.description} - ${remoteError.cause.message}\n` + - ` data\t${JSON.stringify(data)}\n`, - ); - expect( - binUtils.outputFormatter({ type: 'error', data: twoRemoteErrors }), - ).toBe( - `${twoRemoteErrors.name}: ${twoRemoteErrors.description} - ${twoRemoteErrors.message}\n` + - ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + - ` host\t${host}\n` + - ` port\t${port}\n` + - ` command\tcommand 2\n` + - ` timestamp\t${timestamp.toString()}\n` + - ` cause: ${twoRemoteErrors.cause.name}: ${twoRemoteErrors.cause.description}\n` + - ` nodeId\t${nodesUtils.encodeNodeId(nodeId)}\n` + - ` host\t${host}\n` + - ` port\t${port}\n` + - ` command\t${twoRemoteErrors.cause.metadata.command}\n` + - ` timestamp\t${timestamp.toString()}\n` + - ` cause: ${twoRemoteErrors.cause.cause.name}: ${twoRemoteErrors.cause.cause.description} - ${twoRemoteErrors.cause.cause.message}\n` + - ` cause: ${standardError.name}: ${standardError.message}\n`, - ); - // JSON - expect( - binUtils.outputFormatter({ type: 'json', data: standardError }), - ).toBe( - `{"type":"${standardError.name}","data":{"message":"${ - standardError.message - }","stack":"${standardError.stack?.replaceAll('\n', '\\n')}"}}\n`, - ); - expect(binUtils.outputFormatter({ type: 'json', data: pkError })).toBe( - JSON.stringify(pkError.toJSON()) + '\n', - ); - expect( - binUtils.outputFormatter({ type: 'json', data: remoteError }), - ).toBe(JSON.stringify(remoteError.toJSON()) + '\n'); - expect( - binUtils.outputFormatter({ type: 'json', data: twoRemoteErrors }), - ).toBe( - JSON.stringify( - twoRemoteErrors.toJSON(), - binUtils.standardErrorReplacer, - ) + '\n', - ); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'encodeEscaped should encode all escapable characters', - () => { - fc.assert( - fc.property(stringWithNonPrintableCharsArb, (value) => { - expect(binUtils.decodeEscaped(binUtils.encodeEscaped(value))).toBe( - value, - ); - }), - { numRuns: 100 }, // Number of times to run the test - ); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'encodeEscapedReplacer should encode all escapable characters', - () => { - fc.assert( - fc.property( - stringWithNonPrintableCharsArb, - stringWithNonPrintableCharsArb, - (key, value) => { - const encodedKey = binUtils.encodeEscaped(key); - const encodedValue = binUtils.encodeEscaped(value); - const object = { - [key]: value, - [key]: { - [key]: value, - }, - [key]: [value], - }; - const encodedObject = { - [encodedKey]: encodedValue, - [encodedKey]: { - [encodedKey]: encodedValue, - }, - [encodedKey]: [encodedValue], - }; - const output = JSON.stringify( - object, - binUtils.encodeEscapedReplacer, - ); - expect(JSON.parse(output)).toEqual(encodedObject); - }, - ), - { numRuns: 100 }, // Number of times to run the test - ); - }, - ); + ), + { numRuns: 100 }, // Number of times to run the test + ); + }); }); diff --git a/tests/vaults/vaults.test.ts b/tests/vaults/vaults.test.ts index e088b22b..a99b22f6 100644 --- a/tests/vaults/vaults.test.ts +++ b/tests/vaults/vaults.test.ts @@ -85,139 +85,117 @@ describe('CLI vaults', () => { }); describe('commandListVaults', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should list all vaults', - async () => { - command = ['vaults', 'list', '-np', dataDir]; - await polykeyAgent.vaultManager.createVault('Vault1' as VaultName); - await polykeyAgent.vaultManager.createVault('Vault2' as VaultName); + test('should list all vaults', async () => { + command = ['vaults', 'list', '-np', dataDir]; + await polykeyAgent.vaultManager.createVault('Vault1' as VaultName); + await polykeyAgent.vaultManager.createVault('Vault2' as VaultName); - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); - }, - ); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); + }); }); describe('commandCreateVaults', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should create vaults', - async () => { - command = ['vaults', 'create', '-np', dataDir, 'MyTestVault']; - const result = await testUtils.pkStdio([...command], { + test('should create vaults', async () => { + command = ['vaults', 'create', '-np', dataDir, 'MyTestVault']; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); + const result2 = await testUtils.pkStdio( + ['vaults', 'touch', '-np', dataDir, 'MyTestVault2'], + { env: {}, cwd: dataDir, - }); - expect(result.exitCode).toBe(0); - const result2 = await testUtils.pkStdio( - ['vaults', 'touch', '-np', dataDir, 'MyTestVault2'], - { - env: {}, - cwd: dataDir, - }, - ); - expect(result2.exitCode).toBe(0); - - const list = (await polykeyAgent.vaultManager.listVaults()).keys(); - const namesList: string[] = []; - for await (const name of list) { - namesList.push(name); - } - expect(namesList).toContain('MyTestVault'); - expect(namesList).toContain('MyTestVault2'); - }, - ); + }, + ); + expect(result2.exitCode).toBe(0); + + const list = (await polykeyAgent.vaultManager.listVaults()).keys(); + const namesList: string[] = []; + for await (const name of list) { + namesList.push(name); + } + expect(namesList).toContain('MyTestVault'); + expect(namesList).toContain('MyTestVault2'); + }); }); describe('commandRenameVault', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should rename vault', - async () => { - command = [ - 'vaults', - 'rename', - vaultName, - 'RenamedVault', - '-np', - dataDir, - ]; - await polykeyAgent.vaultManager.createVault(vaultName); - const id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); + test('should rename vault', async () => { + command = ['vaults', 'rename', vaultName, 'RenamedVault', '-np', dataDir]; + await polykeyAgent.vaultManager.createVault(vaultName); + const id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - const list = (await polykeyAgent.vaultManager.listVaults()).keys(); - const namesList: string[] = []; - for await (const name of list) { - namesList.push(name); - } - expect(namesList).toContain('RenamedVault'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should fail to rename non-existent vault', - async () => { - command = [ - 'vaults', - 'rename', - 'z4iAXFwgHGeyUrdC5CiCNU4', // Vault does not exist - 'RenamedVault', - '-np', - dataDir, - ]; - await polykeyAgent.vaultManager.createVault(vaultName); - const id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); + const list = (await polykeyAgent.vaultManager.listVaults()).keys(); + const namesList: string[] = []; + for await (const name of list) { + namesList.push(name); + } + expect(namesList).toContain('RenamedVault'); + }); + test('should fail to rename non-existent vault', async () => { + command = [ + 'vaults', + 'rename', + 'z4iAXFwgHGeyUrdC5CiCNU4', // Vault does not exist + 'RenamedVault', + '-np', + dataDir, + ]; + await polykeyAgent.vaultManager.createVault(vaultName); + const id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - // Exit code of the exception - expect(result.exitCode).toBe(sysexits.USAGE); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + // Exit code of the exception + expect(result.exitCode).toBe(sysexits.USAGE); - const list = (await polykeyAgent.vaultManager.listVaults()).keys(); - const namesList: string[] = []; - for await (const name of list) { - namesList.push(name); - } - expect(namesList).toContain(vaultName); - }, - ); + const list = (await polykeyAgent.vaultManager.listVaults()).keys(); + const namesList: string[] = []; + for await (const name of list) { + namesList.push(name); + } + expect(namesList).toContain(vaultName); + }); }); describe('commandDeleteVault', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should delete vault', - async () => { - command = ['vaults', 'delete', '-np', dataDir, vaultName]; - await polykeyAgent.vaultManager.createVault(vaultName); - let id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); + test('should delete vault', async () => { + command = ['vaults', 'delete', '-np', dataDir, vaultName]; + await polykeyAgent.vaultManager.createVault(vaultName); + let id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); + id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - const result2 = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); - - const list = (await polykeyAgent.vaultManager.listVaults()).keys(); - const namesList: string[] = []; - for await (const name of list) { - namesList.push(name); - } - expect(namesList).not.toContain(vaultName); - }, - ); + const result2 = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + + const list = (await polykeyAgent.vaultManager.listVaults()).keys(); + const namesList: string[] = []; + for await (const name of list) { + namesList.push(name); + } + expect(namesList).not.toContain(vaultName); + }); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'should clone and pull a vault', async () => { const dataDir2 = await fs.promises.mkdtemp( @@ -400,87 +378,31 @@ describe('CLI vaults', () => { globalThis.defaultTimeout * 3, ); describe('commandShare', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'Should share a vault', - async () => { - const mockedSendNotification = jest.spyOn( - NotificationsManager.prototype, - 'sendNotification', - ); - try { - // We don't want to actually send a notification - mockedSendNotification.mockImplementation(async (_) => {}); - const vaultId = - await polykeyAgent.vaultManager.createVault(vaultName); - const vaultIdEncoded = vaultsUtils.encodeVaultId(vaultId); - const targetNodeId = nodeIdGenerator(); - const targetNodeIdEncoded = nodesUtils.encodeNodeId(targetNodeId); - await polykeyAgent.gestaltGraph.setNode({ - nodeId: targetNodeId, - }); - expect( - (await polykeyAgent.acl.getNodePerm(targetNodeId))?.vaults[vaultId], - ).toBeUndefined(); - - command = [ - 'vaults', - 'share', - '-np', - dataDir, - vaultIdEncoded, - targetNodeIdEncoded, - ]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); - - // Check permission - const permissions1 = ( - await polykeyAgent.acl.getNodePerm(targetNodeId) - )?.vaults[vaultId]; - expect(permissions1).toBeDefined(); - expect(permissions1.pull).toBeDefined(); - expect(permissions1.clone).toBeDefined(); - } finally { - mockedSendNotification.mockRestore(); - } - }, - ); - }); - describe('commandUnshare', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'Should unshare a vault', - async () => { - const vaultId1 = await polykeyAgent.vaultManager.createVault(vaultName); - const vaultId2 = await polykeyAgent.vaultManager.createVault( - vaultName + '1', - ); - const vaultIdEncoded1 = vaultsUtils.encodeVaultId(vaultId1); - const vaultIdEncoded2 = vaultsUtils.encodeVaultId(vaultId2); + test('Should share a vault', async () => { + const mockedSendNotification = jest.spyOn( + NotificationsManager.prototype, + 'sendNotification', + ); + try { + // We don't want to actually send a notification + mockedSendNotification.mockImplementation(async (_) => {}); + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + const vaultIdEncoded = vaultsUtils.encodeVaultId(vaultId); const targetNodeId = nodeIdGenerator(); const targetNodeIdEncoded = nodesUtils.encodeNodeId(targetNodeId); await polykeyAgent.gestaltGraph.setNode({ nodeId: targetNodeId, }); - - // Creating permissions - await polykeyAgent.gestaltGraph.setGestaltAction( - ['node', targetNodeId], - 'scan', - ); - await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'clone'); - await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'pull'); - await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'clone'); - await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'pull'); + expect( + (await polykeyAgent.acl.getNodePerm(targetNodeId))?.vaults[vaultId], + ).toBeUndefined(); command = [ 'vaults', - 'unshare', + 'share', '-np', dataDir, - vaultIdEncoded1, + vaultIdEncoded, targetNodeIdEncoded, ]; const result = await testUtils.pkStdio([...command], { @@ -490,241 +412,253 @@ describe('CLI vaults', () => { expect(result.exitCode).toBe(0); // Check permission - const permissions = (await polykeyAgent.acl.getNodePerm(targetNodeId)) - ?.vaults[vaultId1]; - expect(permissions).toBeDefined(); - expect(permissions.pull).toBeUndefined(); - expect(permissions.clone).toBeUndefined(); + const permissions1 = (await polykeyAgent.acl.getNodePerm(targetNodeId)) + ?.vaults[vaultId]; + expect(permissions1).toBeDefined(); + expect(permissions1.pull).toBeDefined(); + expect(permissions1.clone).toBeDefined(); + } finally { + mockedSendNotification.mockRestore(); + } + }); + }); + describe('commandUnshare', () => { + test('Should unshare a vault', async () => { + const vaultId1 = await polykeyAgent.vaultManager.createVault(vaultName); + const vaultId2 = await polykeyAgent.vaultManager.createVault( + vaultName + '1', + ); + const vaultIdEncoded1 = vaultsUtils.encodeVaultId(vaultId1); + const vaultIdEncoded2 = vaultsUtils.encodeVaultId(vaultId2); + const targetNodeId = nodeIdGenerator(); + const targetNodeIdEncoded = nodesUtils.encodeNodeId(targetNodeId); + await polykeyAgent.gestaltGraph.setNode({ + nodeId: targetNodeId, + }); - expect( - (await polykeyAgent.acl.getNodePerm(targetNodeId))?.gestalt['scan'], - ).toBeDefined(); + // Creating permissions + await polykeyAgent.gestaltGraph.setGestaltAction( + ['node', targetNodeId], + 'scan', + ); + await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'clone'); + await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'pull'); + await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'clone'); + await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'pull'); - command = [ - 'vaults', - 'unshare', - '-np', - dataDir, - vaultIdEncoded2, - targetNodeIdEncoded, - ]; - const result2 = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); + command = [ + 'vaults', + 'unshare', + '-np', + dataDir, + vaultIdEncoded1, + targetNodeIdEncoded, + ]; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - // Check permission - const permissions2 = (await polykeyAgent.acl.getNodePerm(targetNodeId)) - ?.vaults[vaultId2]; - expect(permissions2).toBeDefined(); - expect(permissions2.pull).toBeUndefined(); - expect(permissions2.clone).toBeUndefined(); + // Check permission + const permissions = (await polykeyAgent.acl.getNodePerm(targetNodeId)) + ?.vaults[vaultId1]; + expect(permissions).toBeDefined(); + expect(permissions.pull).toBeUndefined(); + expect(permissions.clone).toBeUndefined(); - // And the scan permission should be removed - expect( - (await polykeyAgent.acl.getNodePerm(targetNodeId))?.gestalt['scan'], - ).toBeUndefined(); - }, - ); + expect( + (await polykeyAgent.acl.getNodePerm(targetNodeId))?.gestalt['scan'], + ).toBeDefined(); + + command = [ + 'vaults', + 'unshare', + '-np', + dataDir, + vaultIdEncoded2, + targetNodeIdEncoded, + ]; + const result2 = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + + // Check permission + const permissions2 = (await polykeyAgent.acl.getNodePerm(targetNodeId)) + ?.vaults[vaultId2]; + expect(permissions2).toBeDefined(); + expect(permissions2.pull).toBeUndefined(); + expect(permissions2.clone).toBeUndefined(); + + // And the scan permission should be removed + expect( + (await polykeyAgent.acl.getNodePerm(targetNodeId))?.gestalt['scan'], + ).toBeUndefined(); + }); }); describe('commandPermissions', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'Should get a vaults permissions', - async () => { - const vaultId1 = await polykeyAgent.vaultManager.createVault(vaultName); - const vaultId2 = await polykeyAgent.vaultManager.createVault( - vaultName + '1', - ); - const vaultIdEncoded1 = vaultsUtils.encodeVaultId(vaultId1); - const vaultIdEncoded2 = vaultsUtils.encodeVaultId(vaultId2); - const targetNodeId = nodeIdGenerator(); - const targetNodeIdEncoded = nodesUtils.encodeNodeId(targetNodeId); - await polykeyAgent.gestaltGraph.setNode({ - nodeId: targetNodeId, - }); + test('Should get a vaults permissions', async () => { + const vaultId1 = await polykeyAgent.vaultManager.createVault(vaultName); + const vaultId2 = await polykeyAgent.vaultManager.createVault( + vaultName + '1', + ); + const vaultIdEncoded1 = vaultsUtils.encodeVaultId(vaultId1); + const vaultIdEncoded2 = vaultsUtils.encodeVaultId(vaultId2); + const targetNodeId = nodeIdGenerator(); + const targetNodeIdEncoded = nodesUtils.encodeNodeId(targetNodeId); + await polykeyAgent.gestaltGraph.setNode({ + nodeId: targetNodeId, + }); - // Creating permissions - await polykeyAgent.gestaltGraph.setGestaltAction( - ['node', targetNodeId], - 'scan', - ); - await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'clone'); - await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'pull'); - await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'pull'); + // Creating permissions + await polykeyAgent.gestaltGraph.setGestaltAction( + ['node', targetNodeId], + 'scan', + ); + await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'clone'); + await polykeyAgent.acl.setVaultAction(vaultId1, targetNodeId, 'pull'); + await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'pull'); - command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded1]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); - expect(result.stdout).toContain(targetNodeIdEncoded); - expect(result.stdout).toContain('clone'); - expect(result.stdout).toContain('pull'); + command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded1]; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain(targetNodeIdEncoded); + expect(result.stdout).toContain('clone'); + expect(result.stdout).toContain('pull'); - command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded2]; - const result2 = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); - expect(result2.stdout).toContain(targetNodeIdEncoded); - expect(result2.stdout).not.toContain('clone'); - expect(result2.stdout).toContain('pull'); - }, - ); + command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded2]; + const result2 = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + expect(result2.stdout).toContain(targetNodeIdEncoded); + expect(result2.stdout).not.toContain('clone'); + expect(result2.stdout).toContain('pull'); + }); }); describe('commandVaultVersion', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should switch the version of a vault', - async () => { - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - const id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); - - const secret1 = { name: 'Secret-1', content: 'Secret-1-content' }; - const secret2 = { name: 'Secret-1', content: 'Secret-2-content' }; - - const ver1Oid = await polykeyAgent.vaultManager.withVaults( - [vaultId], - async (vault) => { - await vault.writeF(async (efs) => { - await efs.writeFile(secret1.name, secret1.content); - }); - const ver1Oid = (await vault.log(undefined, 1))[0].commitId; - - await vault.writeF(async (efs) => { - await efs.writeFile(secret2.name, secret2.content); - }); - return ver1Oid; - }, - ); + test('should switch the version of a vault', async () => { + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + const id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - const command = [ - 'vaults', - 'version', - '-np', - dataDir, - vaultName, - ver1Oid, - ]; + const secret1 = { name: 'Secret-1', content: 'Secret-1-content' }; + const secret2 = { name: 'Secret-1', content: 'Secret-2-content' }; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(0); + const ver1Oid = await polykeyAgent.vaultManager.withVaults( + [vaultId], + async (vault) => { + await vault.writeF(async (efs) => { + await efs.writeFile(secret1.name, secret1.content); + }); + const ver1Oid = (await vault.log(undefined, 1))[0].commitId; - await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { - const fileContents = await vault.readF(async (efs) => { - return (await efs.readFile(secret1.name)).toString(); + await vault.writeF(async (efs) => { + await efs.writeFile(secret2.name, secret2.content); }); - expect(fileContents).toStrictEqual(secret1.content); - }); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should switch the version of a vault to the latest version', - async () => { - const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); - const id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); - - const secret1 = { name: 'Secret-1', content: 'Secret-1-content' }; - const secret2 = { name: 'Secret-1', content: 'Secret-2-content' }; - - const ver1Oid = await polykeyAgent.vaultManager.withVaults( - [vaultId], - async (vault) => { - await vault.writeF(async (efs) => { - await efs.writeFile(secret1.name, secret1.content); - }); - const ver1Oid = (await vault.log(undefined, 1))[0].commitId; - - await vault.writeF(async (efs) => { - await efs.writeFile(secret2.name, secret2.content); - }); - return ver1Oid; - }, - ); + return ver1Oid; + }, + ); - const command = [ - 'vaults', - 'version', - '-np', - dataDir, - vaultName, - ver1Oid, - ]; + const command = ['vaults', 'version', '-np', dataDir, vaultName, ver1Oid]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); + + await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { + const fileContents = await vault.readF(async (efs) => { + return (await efs.readFile(secret1.name)).toString(); }); - expect(result.exitCode).toBe(0); + expect(fileContents).toStrictEqual(secret1.content); + }); + }); + test('should switch the version of a vault to the latest version', async () => { + const vaultId = await polykeyAgent.vaultManager.createVault(vaultName); + const id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); - const command2 = [ - 'vaults', - 'version', - '-np', - dataDir, - vaultName, - 'last', - ]; + const secret1 = { name: 'Secret-1', content: 'Secret-1-content' }; + const secret2 = { name: 'Secret-1', content: 'Secret-2-content' }; - const result2 = await testUtils.pkStdio([...command2], { - env: {}, - cwd: dataDir, - }); - expect(result2.exitCode).toBe(0); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should handle invalid version IDs', - async () => { - await polykeyAgent.vaultManager.createVault(vaultName); - const id = polykeyAgent.vaultManager.getVaultId(vaultName); - expect(id).toBeTruthy(); + const ver1Oid = await polykeyAgent.vaultManager.withVaults( + [vaultId], + async (vault) => { + await vault.writeF(async (efs) => { + await efs.writeFile(secret1.name, secret1.content); + }); + const ver1Oid = (await vault.log(undefined, 1))[0].commitId; - const command = [ - 'vaults', - 'version', - '-np', - dataDir, - vaultName, - 'NOT_A_VALID_CHECKOUT_ID', - ]; + await vault.writeF(async (efs) => { + await efs.writeFile(secret2.name, secret2.content); + }); + return ver1Oid; + }, + ); - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(sysexits.USAGE); + const command = ['vaults', 'version', '-np', dataDir, vaultName, ver1Oid]; - expect(result.stderr).toContain('ErrorVaultReferenceInvalid'); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should throw an error if the vault is not found', - async () => { - const command = [ - 'vaults', - 'version', - '-np', - dataDir, - 'zLnM7puKobbh4YXEz66StAq', - 'NOT_A_VALID_CHECKOUT_ID', - ]; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(0); - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toBe(sysexits.USAGE); - expect(result.stderr).toContain('ErrorVaultsVaultUndefined'); - }, - ); + const command2 = ['vaults', 'version', '-np', dataDir, vaultName, 'last']; + + const result2 = await testUtils.pkStdio([...command2], { + env: {}, + cwd: dataDir, + }); + expect(result2.exitCode).toBe(0); + }); + test('should handle invalid version IDs', async () => { + await polykeyAgent.vaultManager.createVault(vaultName); + const id = polykeyAgent.vaultManager.getVaultId(vaultName); + expect(id).toBeTruthy(); + + const command = [ + 'vaults', + 'version', + '-np', + dataDir, + vaultName, + 'NOT_A_VALID_CHECKOUT_ID', + ]; + + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(sysexits.USAGE); + + expect(result.stderr).toContain('ErrorVaultReferenceInvalid'); + }); + test('should throw an error if the vault is not found', async () => { + const command = [ + 'vaults', + 'version', + '-np', + dataDir, + 'zLnM7puKobbh4YXEz66StAq', + 'NOT_A_VALID_CHECKOUT_ID', + ]; + + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toBe(sysexits.USAGE); + expect(result.stderr).toContain('ErrorVaultsVaultUndefined'); + }); }); describe('commandVaultLog', () => { const secret1 = { name: 'secret1', content: 'Secret-1-content' }; @@ -759,66 +693,57 @@ describe('CLI vaults', () => { await polykeyAgent.vaultManager.destroyVault(vaultId); }); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'Should get all writeFs', - async () => { - const command = ['vaults', 'log', '-np', dataDir, vaultName]; + test('Should get all writeFs', async () => { + const command = ['vaults', 'log', '-np', dataDir, vaultName]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toEqual(0); - expect(result.stdout).toContain(writeF1Oid); - expect(result.stdout).toContain(writeF2Oid); - expect(result.stdout).toContain(writeF3Oid); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should get a part of the log', - async () => { - const command = ['vaults', 'log', '-np', dataDir, '-d', '2', vaultName]; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toEqual(0); + expect(result.stdout).toContain(writeF1Oid); + expect(result.stdout).toContain(writeF2Oid); + expect(result.stdout).toContain(writeF3Oid); + }); + test('should get a part of the log', async () => { + const command = ['vaults', 'log', '-np', dataDir, '-d', '2', vaultName]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toEqual(0); - expect(result.stdout).not.toContain(writeF1Oid); - expect(result.stdout).toContain(writeF2Oid); - expect(result.stdout).toContain(writeF3Oid); - }, - ); - testUtils.testIf(testUtils.isTestPlatformEmpty)( - 'should get a specific writeF', - async () => { - const command = [ - 'vaults', - 'log', - '-np', - dataDir, - '-d', - '1', - vaultName, - '-ci', - writeF2Oid, - ]; + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toEqual(0); + expect(result.stdout).not.toContain(writeF1Oid); + expect(result.stdout).toContain(writeF2Oid); + expect(result.stdout).toContain(writeF3Oid); + }); + test('should get a specific writeF', async () => { + const command = [ + 'vaults', + 'log', + '-np', + dataDir, + '-d', + '1', + vaultName, + '-ci', + writeF2Oid, + ]; - const result = await testUtils.pkStdio([...command], { - env: {}, - cwd: dataDir, - }); - expect(result.exitCode).toEqual(0); - expect(result.stdout).not.toContain(writeF1Oid); - expect(result.stdout).toContain(writeF2Oid); - expect(result.stdout).not.toContain(writeF3Oid); - }, - ); + const result = await testUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); + expect(result.exitCode).toEqual(0); + expect(result.stdout).not.toContain(writeF1Oid); + expect(result.stdout).toContain(writeF2Oid); + expect(result.stdout).not.toContain(writeF3Oid); + }); test.todo('test formatting of the output'); }); // Fixme: tempermental problem with formatting the output. Fails sometimes due to an added space describe('commandScanNode', () => { - testUtils.testIf(testUtils.isTestPlatformEmpty)( + test( 'should return the vaults names and ids of the remote vault', async () => { let remoteOnline: PolykeyAgent | undefined; From 39569b9723910ce09b84d389d0af34997bd03f46 Mon Sep 17 00:00:00 2001 From: Brian Botha Date: Mon, 18 Dec 2023 13:56:49 +1100 Subject: [PATCH 2/5] tests: all standard tests do not connect to any seed nodes Only integration testing should attempt any network connections. [ci skip] --- tests/agent/start.test.ts | 71 +++++++++++++++++++------------------- tests/agent/status.test.ts | 4 +-- tests/agent/stop.test.ts | 16 ++++----- tests/nat/DMZ.test.ts | 4 +-- tests/nat/utils.ts | 12 +++---- tests/polykey.test.ts | 4 +-- tests/utils/testAgent.ts | 4 +-- 7 files changed, 58 insertions(+), 57 deletions(-) diff --git a/tests/agent/start.test.ts b/tests/agent/start.test.ts index f6a951df..04ed006c 100644 --- a/tests/agent/start.test.ts +++ b/tests/agent/start.test.ts @@ -11,7 +11,7 @@ import Status from 'polykey/dist/status/Status'; import * as statusErrors from 'polykey/dist/status/errors'; import config from 'polykey/dist/config'; import * as keysUtils from 'polykey/dist/keys/utils'; -import { promise } from 'polykey/dist/utils'; +import { promise, sleep } from 'polykey/dist/utils'; import * as nodesUtils from 'polykey/dist/nodes/utils'; import * as testUtils from '../utils'; @@ -50,8 +50,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -86,6 +86,7 @@ describe('start', () => { statusLiveData.recoveryCode.split(' ').length === 12 || statusLiveData.recoveryCode.split(' ').length === 24, ).toBe(true); + await sleep(5000); agentProcess.kill('SIGTERM'); const status = new Status({ statusPath: path.join(dataDir, 'polykey', config.paths.statusBase), @@ -125,8 +126,8 @@ describe('start', () => { path.join(dataDir, 'err.log'), '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -220,8 +221,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -248,8 +249,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -331,8 +332,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -425,8 +426,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -457,8 +458,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -505,8 +506,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -548,8 +549,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--fresh', '--verbose', '--format', @@ -631,8 +632,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -673,8 +674,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -702,8 +703,8 @@ describe('start', () => { 'start', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -740,8 +741,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -799,8 +800,8 @@ describe('start', () => { agentHost, '--agent-port', agentPort.toString(), - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -864,8 +865,8 @@ describe('start', () => { '--workers', 'none', '--verbose', - '--network', - 'testnet', + '--seed-nodes', + '', '--private-key-file', privateKeyPath, ], @@ -961,8 +962,8 @@ describe('start', () => { 'none', '--seed-nodes', `${seedNodeId1}@${seedNodeHost1}:${seedNodePort1};`, - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { @@ -1022,8 +1023,8 @@ describe('start', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { diff --git a/tests/agent/status.test.ts b/tests/agent/status.test.ts index f13d8b6c..035b2fde 100644 --- a/tests/agent/status.test.ts +++ b/tests/agent/status.test.ts @@ -47,8 +47,8 @@ describe('status', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', ], { diff --git a/tests/agent/stop.test.ts b/tests/agent/stop.test.ts index 5aab308c..e6dec6d5 100644 --- a/tests/agent/stop.test.ts +++ b/tests/agent/stop.test.ts @@ -36,8 +36,8 @@ describe('stop', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', ], { env: { @@ -102,8 +102,8 @@ describe('stop', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', ], { env: { @@ -203,8 +203,8 @@ describe('stop', () => { '--workers', 'none', '--verbose', - '--network', - 'testnet', + '--seed-nodes', + '', ], { env: { @@ -256,8 +256,8 @@ describe('stop', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', ], { env: { diff --git a/tests/nat/DMZ.test.ts b/tests/nat/DMZ.test.ts index 5844a49f..65b7185f 100644 --- a/tests/nat/DMZ.test.ts +++ b/tests/nat/DMZ.test.ts @@ -55,8 +55,8 @@ describe.skip('DMZ', () => { '127.0.0.1', '--workers', '0', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', diff --git a/tests/nat/utils.ts b/tests/nat/utils.ts index c9839003..e2c7ed0e 100644 --- a/tests/nat/utils.ts +++ b/tests/nat/utils.ts @@ -1042,8 +1042,8 @@ async function setupNATWithSeedNode( '1000', '--workers', '0', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -1298,8 +1298,8 @@ async function setupNAT( '1000', '--workers', '0', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', @@ -1339,8 +1339,8 @@ async function setupNAT( '1000', '--workers', '0', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', diff --git a/tests/polykey.test.ts b/tests/polykey.test.ts index 012db0ee..ad5a299b 100644 --- a/tests/polykey.test.ts +++ b/tests/polykey.test.ts @@ -33,8 +33,8 @@ describe('polykey', () => { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--verbose', '--format', 'json', diff --git a/tests/utils/testAgent.ts b/tests/utils/testAgent.ts index fd8c8a42..b7dde70d 100644 --- a/tests/utils/testAgent.ts +++ b/tests/utils/testAgent.ts @@ -24,8 +24,8 @@ async function setupTestAgent(logger: Logger) { '127.0.0.1', '--workers', 'none', - '--network', - 'testnet', + '--seed-nodes', + '', '--format', 'json', '--verbose', From 9d4f30769bd2de9a07f62e5bd2e6445419bd3f5a Mon Sep 17 00:00:00 2001 From: Brian Botha Date: Mon, 18 Dec 2023 16:15:40 +1100 Subject: [PATCH 3/5] tests: removing usage of `globalThis.testCmd` as command for normal tests [ci skip] --- tests/agent/lock.test.ts | 2 -- tests/agent/lockall.test.ts | 5 ----- tests/agent/start.test.ts | 19 +------------------ tests/agent/status.test.ts | 7 ------- tests/agent/stop.test.ts | 10 ---------- tests/agent/unlock.test.ts | 3 --- tests/bootstrap.test.ts | 9 --------- .../allowDisallowPermissions.test.ts | 5 ----- tests/keys/cert.test.ts | 1 - tests/keys/certchain.test.ts | 1 - tests/keys/encryptDecrypt.test.ts | 4 ---- tests/keys/keypair.test.ts | 1 - tests/keys/password.test.ts | 2 -- tests/keys/private.test.ts | 1 - tests/keys/public.test.ts | 1 - tests/keys/signVerify.test.ts | 4 ---- tests/notifications/sendReadClear.test.ts | 12 ------------ tests/polykey.test.ts | 1 - tests/utils/exec.ts | 5 ----- tests/utils/testAgent.ts | 1 - 20 files changed, 1 insertion(+), 93 deletions(-) diff --git a/tests/agent/lock.test.ts b/tests/agent/lock.test.ts index 035d1bdd..1d507e44 100644 --- a/tests/agent/lock.test.ts +++ b/tests/agent/lock.test.ts @@ -27,14 +27,12 @@ describe('lock', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }); const { exitCode } = await testUtils.pkExec(['agent', 'lock'], { env: { PK_NODE_PATH: agentDir, }, cwd: agentDir, - command: globalThis.testCmd, }); expect(exitCode).toBe(0); const session = await Session.createSession({ diff --git a/tests/agent/lockall.test.ts b/tests/agent/lockall.test.ts index 87fe9827..b0a3fcc5 100644 --- a/tests/agent/lockall.test.ts +++ b/tests/agent/lockall.test.ts @@ -33,12 +33,10 @@ describe('lockall', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }); const { exitCode } = await testUtils.pkExec(['agent', 'lockall'], { env: { PK_NODE_PATH: agentDir }, cwd: agentDir, - command: globalThis.testCmd, }); expect(exitCode).toBe(0); const session = await Session.createSession({ @@ -82,7 +80,6 @@ describe('lockall', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }); const session = await Session.createSession({ sessionTokenPath: path.join(agentDir, config.paths.tokenBase), @@ -97,7 +94,6 @@ describe('lockall', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }); // Old token is invalid const { exitCode, stderr } = await testUtils.pkExec( @@ -108,7 +104,6 @@ describe('lockall', () => { PK_TOKEN: token, }, cwd: agentDir, - command: globalThis.testCmd, }, ); testUtils.expectProcessError(exitCode, stderr, [ diff --git a/tests/agent/start.test.ts b/tests/agent/start.test.ts index 04ed006c..d56b82b1 100644 --- a/tests/agent/start.test.ts +++ b/tests/agent/start.test.ts @@ -11,7 +11,7 @@ import Status from 'polykey/dist/status/Status'; import * as statusErrors from 'polykey/dist/status/errors'; import config from 'polykey/dist/config'; import * as keysUtils from 'polykey/dist/keys/utils'; -import { promise, sleep } from 'polykey/dist/utils'; +import { promise } from 'polykey/dist/utils'; import * as nodesUtils from 'polykey/dist/nodes/utils'; import * as testUtils from '../utils'; @@ -63,7 +63,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -86,7 +85,6 @@ describe('start', () => { statusLiveData.recoveryCode.split(' ').length === 12 || statusLiveData.recoveryCode.split(' ').length === 24, ).toBe(true); - await sleep(5000); agentProcess.kill('SIGTERM'); const status = new Status({ statusPath: path.join(dataDir, 'polykey', config.paths.statusBase), @@ -139,7 +137,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -235,7 +232,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess1'), ), @@ -263,7 +259,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess2'), ), @@ -346,7 +341,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess'), ), @@ -360,7 +354,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('bootstrapProcess'), ), @@ -438,7 +431,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -470,7 +462,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -518,7 +509,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess1'), ); @@ -564,7 +554,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess2'), ); @@ -645,7 +634,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess1'), ); @@ -686,7 +674,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess2'), ); @@ -715,7 +702,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess3'), ); @@ -754,7 +740,6 @@ describe('start', () => { PK_RECOVERY_CODE: recoveryCode, }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess4'), ); @@ -812,7 +797,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('agentProcess'), ); @@ -878,7 +862,6 @@ describe('start', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); diff --git a/tests/agent/status.test.ts b/tests/agent/status.test.ts index 035b2fde..cf98daf7 100644 --- a/tests/agent/status.test.ts +++ b/tests/agent/status.test.ts @@ -59,7 +59,6 @@ describe('status', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -73,7 +72,6 @@ describe('status', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -95,7 +93,6 @@ describe('status', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -113,7 +110,6 @@ describe('status', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -128,7 +124,6 @@ describe('status', () => { ['agent', 'status', '--format', 'json'], { env: { PK_NODE_PATH: path.join(dataDir, 'polykey') }, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -163,7 +158,6 @@ describe('status', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -212,7 +206,6 @@ describe('status', () => { { env: {}, cwd: dataDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/agent/stop.test.ts b/tests/agent/stop.test.ts index e6dec6d5..5aa0c68f 100644 --- a/tests/agent/stop.test.ts +++ b/tests/agent/stop.test.ts @@ -47,7 +47,6 @@ describe('stop', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -68,7 +67,6 @@ describe('stop', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }); await status.waitFor('DEAD'); await sleep(5000); @@ -113,7 +111,6 @@ describe('stop', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -125,14 +122,12 @@ describe('stop', () => { PK_NODE_PATH: path.join(dataDir, 'polykey'), }, cwd: dataDir, - command: globalThis.testCmd, }), testUtils.pkExec(['agent', 'stop', '--password-file', passwordPath], { env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), }, cwd: dataDir, - command: globalThis.testCmd, }), ]); // Cannot await for STOPPING @@ -146,7 +141,6 @@ describe('stop', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, ); await status.waitFor('DEAD'); @@ -157,7 +151,6 @@ describe('stop', () => { PK_NODE_PATH: path.join(dataDir, 'polykey'), }, cwd: dataDir, - command: globalThis.testCmd, }, ); // If the GRPC server gets closed after the GRPC connection is established @@ -267,7 +260,6 @@ describe('stop', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); @@ -290,7 +282,6 @@ describe('stop', () => { PK_PASSWORD: 'wrong password', }, cwd: dataDir, - command: globalThis.testCmd, }, ); testUtils.expectProcessError(exitCode, stderr, [ @@ -304,7 +295,6 @@ describe('stop', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }); await status.waitFor('DEAD'); agentProcess.kill(); diff --git a/tests/agent/unlock.test.ts b/tests/agent/unlock.test.ts index 67441a0c..2221ce5c 100644 --- a/tests/agent/unlock.test.ts +++ b/tests/agent/unlock.test.ts @@ -34,7 +34,6 @@ describe('unlock', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, })); expect(exitCode).toBe(0); // Run command without password @@ -45,7 +44,6 @@ describe('unlock', () => { PK_NODE_PATH: agentDir, }, cwd: agentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -59,7 +57,6 @@ describe('unlock', () => { PK_TOKEN: await session.readToken(), }, cwd: agentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); diff --git a/tests/bootstrap.test.ts b/tests/bootstrap.test.ts index 43353620..ceb23736 100644 --- a/tests/bootstrap.test.ts +++ b/tests/bootstrap.test.ts @@ -38,7 +38,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -88,7 +87,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, ); expect(exitCode1).toBe(0); @@ -118,7 +116,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, )); const errorBootstrapExistingState = @@ -141,7 +138,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -168,7 +164,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('bootstrapProcess1'), ), @@ -182,7 +177,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('bootstrapProcess2'), ), @@ -244,7 +238,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger.getChild('bootstrapProcess1'), ); @@ -279,7 +272,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, ); const errorBootstrapExistingState = @@ -300,7 +292,6 @@ describe('bootstrap', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, ); expect(bootstrapProcess3.exitCode).toBe(0); diff --git a/tests/identities/allowDisallowPermissions.test.ts b/tests/identities/allowDisallowPermissions.test.ts index e0e4d5f0..c31e5452 100644 --- a/tests/identities/allowDisallowPermissions.test.ts +++ b/tests/identities/allowDisallowPermissions.test.ts @@ -352,7 +352,6 @@ describe('allow/disallow/permissions', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(sysexits.USAGE); @@ -365,7 +364,6 @@ describe('allow/disallow/permissions', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(sysexits.USAGE); @@ -379,7 +377,6 @@ describe('allow/disallow/permissions', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(sysexits.USAGE); @@ -393,7 +390,6 @@ describe('allow/disallow/permissions', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(sysexits.USAGE); @@ -406,7 +402,6 @@ describe('allow/disallow/permissions', () => { PK_PASSWORD: password, }, cwd: dataDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(sysexits.USAGE); diff --git a/tests/keys/cert.test.ts b/tests/keys/cert.test.ts index 3416e0e1..4fb281fb 100644 --- a/tests/keys/cert.test.ts +++ b/tests/keys/cert.test.ts @@ -22,7 +22,6 @@ describe('cert', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/keys/certchain.test.ts b/tests/keys/certchain.test.ts index 9bbc8e2f..c2f70a66 100644 --- a/tests/keys/certchain.test.ts +++ b/tests/keys/certchain.test.ts @@ -24,7 +24,6 @@ describe('certchain', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/keys/encryptDecrypt.test.ts b/tests/keys/encryptDecrypt.test.ts index f9801204..65988197 100644 --- a/tests/keys/encryptDecrypt.test.ts +++ b/tests/keys/encryptDecrypt.test.ts @@ -40,7 +40,6 @@ describe('encrypt-decrypt', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -71,7 +70,6 @@ describe('encrypt-decrypt', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -103,7 +101,6 @@ describe('encrypt-decrypt', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -131,7 +128,6 @@ describe('encrypt-decrypt', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(sysexits.NOINPUT); diff --git a/tests/keys/keypair.test.ts b/tests/keys/keypair.test.ts index b010246d..3bdfa930 100644 --- a/tests/keys/keypair.test.ts +++ b/tests/keys/keypair.test.ts @@ -25,7 +25,6 @@ describe('keypair', () => { PK_PASSWORD_NEW: 'newPassword', }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/keys/password.test.ts b/tests/keys/password.test.ts index 794df581..b6f85fab 100644 --- a/tests/keys/password.test.ts +++ b/tests/keys/password.test.ts @@ -28,7 +28,6 @@ describe('password', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -40,7 +39,6 @@ describe('password', () => { PK_PASSWORD_NEW: 'newPassword2', }, cwd: agentDir, - command: globalThis.testCmd, })); expect(exitCode).toBe(77); }, 80000); diff --git a/tests/keys/private.test.ts b/tests/keys/private.test.ts index 8516ee47..93f5d9c3 100644 --- a/tests/keys/private.test.ts +++ b/tests/keys/private.test.ts @@ -25,7 +25,6 @@ describe('private', () => { PK_PASSWORD_NEW: 'newPassword', }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/keys/public.test.ts b/tests/keys/public.test.ts index 521bd509..93365791 100644 --- a/tests/keys/public.test.ts +++ b/tests/keys/public.test.ts @@ -24,7 +24,6 @@ describe('public', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); diff --git a/tests/keys/signVerify.test.ts b/tests/keys/signVerify.test.ts index 97dfe298..039b035f 100644 --- a/tests/keys/signVerify.test.ts +++ b/tests/keys/signVerify.test.ts @@ -37,7 +37,6 @@ describe('sign-verify', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -85,7 +84,6 @@ describe('sign-verify', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -120,7 +118,6 @@ describe('sign-verify', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(0); @@ -147,7 +144,6 @@ describe('sign-verify', () => { PK_PASSWORD: agentPassword, }, cwd: agentDir, - command: globalThis.testCmd, }, ); expect(exitCode).toBe(sysexits.NOINPUT); diff --git a/tests/notifications/sendReadClear.test.ts b/tests/notifications/sendReadClear.test.ts index a4b0e44c..aab51d3f 100644 --- a/tests/notifications/sendReadClear.test.ts +++ b/tests/notifications/sendReadClear.test.ts @@ -79,7 +79,6 @@ describe('send/read/claim', () => { PK_PASSWORD: senderAgentPassword, }, cwd: senderAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -98,7 +97,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -111,7 +109,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -129,7 +126,6 @@ describe('send/read/claim', () => { PK_PASSWORD: senderAgentPassword, }, cwd: senderAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -146,7 +142,6 @@ describe('send/read/claim', () => { PK_PASSWORD: senderAgentPassword, }, cwd: senderAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -163,7 +158,6 @@ describe('send/read/claim', () => { PK_PASSWORD: senderAgentPassword, }, cwd: senderAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -176,7 +170,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -221,7 +214,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -239,7 +231,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -284,7 +275,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); @@ -309,7 +299,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, })); // Check there are no more notifications ({ exitCode, stdout } = await testUtils.pkExec( @@ -320,7 +309,6 @@ describe('send/read/claim', () => { PK_PASSWORD: receiverAgentPassword, }, cwd: receiverAgentDir, - command: globalThis.testCmd, }, )); expect(exitCode).toBe(0); diff --git a/tests/polykey.test.ts b/tests/polykey.test.ts index ad5a299b..a0b10fc9 100644 --- a/tests/polykey.test.ts +++ b/tests/polykey.test.ts @@ -47,7 +47,6 @@ describe('polykey', () => { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: dataDir, - command: globalThis.testCmd, }, logger, ); diff --git a/tests/utils/exec.ts b/tests/utils/exec.ts index e6f159ef..3a722b3e 100644 --- a/tests/utils/exec.ts +++ b/tests/utils/exec.ts @@ -396,11 +396,6 @@ async function pkSpawnWithoutShell( ...process.env, ...opts.env, }; - // Recall that we attempt to connect to all specified seed nodes on agent start. - // Therefore, for testing purposes only, we default the seed nodes as empty - // (if not defined in the env) to ensure no attempted connections. A regular - // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; const subprocess = childProcess.spawn( 'ts-node', ['--project', tsConfigPath, polykeyPath, ...args], diff --git a/tests/utils/testAgent.ts b/tests/utils/testAgent.ts index b7dde70d..d07668cd 100644 --- a/tests/utils/testAgent.ts +++ b/tests/utils/testAgent.ts @@ -37,7 +37,6 @@ async function setupTestAgent(logger: Logger) { PK_PASSWORD_MEM_LIMIT: 'min', }, cwd: agentDir, - command: globalThis.testCmd, }, logger, ); From 0a707517dffea66c0a0d287f635d408101f9897a Mon Sep 17 00:00:00 2001 From: Brian Botha Date: Mon, 18 Dec 2023 17:03:47 +1100 Subject: [PATCH 4/5] tests: updating how docker tests are run [ci skip] --- .gitlab-ci.yml | 31 +- jest.config.js | 2 - tests/global.d.ts | 2 - tests/integration/docker/docker.test.ts | 318 ++++++++++++++++++ .../testnet/testnetConnection.test.ts | 312 ----------------- tests/utils/exec.ts | 9 +- 6 files changed, 322 insertions(+), 352 deletions(-) create mode 100644 tests/integration/docker/docker.test.ts delete mode 100644 tests/integration/testnet/testnetConnection.test.ts diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4c7a0efc..8bf3c66e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -325,33 +325,6 @@ integration:nix: # Runs on tag pipeline where the tag is a prerelease or release version - if: $CI_COMMIT_TAG =~ /^v[0-9]+\.[0-9]+\.[0-9]+(?:-.*[0-9]+)?$/ -.integration:docker-disabled: - stage: integration - needs: - - integration:builds - - job: integration:deployment - optional: true - services: - - docker:20.10.16-dind - variables: - DOCKER_TLS_CERTDIR: "/certs" - FF_NETWORK_PER_BUILD: "true" - PK_TEST_PLATFORM: "docker" - PK_TEST_TMPDIR: "${CI_PROJECT_DIR}/tmp/test" - script: - - docker info - - mkdir $PK_TEST_TMPDIR - - > - nix-shell --arg ci true --run $' - image_and_tag="$(docker load --input ./builds/*docker* | cut -d\' \' -f3)"; - PK_TEST_COMMAND="docker run \$DOCKER_OPTIONS $image_and_tag" npm run test; - ' - rules: - # Runs on staging commits and ignores version commits - - if: $CI_COMMIT_BRANCH == 'staging' && $CI_COMMIT_TITLE !~ /^[0-9]+\.[0-9]+\.[0-9]+(?:-.*[0-9]+)?$/ - # Runs on tag pipeline where the tag is a prerelease or release version - - if: $CI_COMMIT_TAG =~ /^v[0-9]+\.[0-9]+\.[0-9]+(?:-.*[0-9]+)?$/ - integration:docker: stage: integration needs: @@ -363,7 +336,6 @@ integration:docker: variables: DOCKER_TLS_CERTDIR: "/certs" FF_NETWORK_PER_BUILD: "true" - PK_TEST_PLATFORM: "docker" PK_TEST_TMPDIR: "${CI_PROJECT_DIR}/tmp/test" script: - docker info @@ -371,7 +343,8 @@ integration:docker: - > nix-shell --arg ci true --run $' image_and_tag="$(docker load --input ./builds/*docker* | cut -d\' \' -f3)"; - docker run $image_and_tag; + docker tag "$image_and_tag" "polykey-cli:testtarget"; + npm run test tests/integration/docker; ' rules: # Runs on staging commits and ignores version commits diff --git a/jest.config.js b/jest.config.js index 137d6ce6..fe962ed8 100644 --- a/jest.config.js +++ b/jest.config.js @@ -26,8 +26,6 @@ const globals = { failedConnectionTimeout: 50000, // Timeouts rely on setTimeout which takes 32 bit numbers maxTimeout: Math.pow(2, 31) - 1, - testCmd: process.env.PK_TEST_COMMAND, - testPlatform: process.env.PK_TEST_PLATFORM, tmpDir: path.resolve(process.env.PK_TEST_TMPDIR ?? os.tmpdir()), }; diff --git a/tests/global.d.ts b/tests/global.d.ts index f131dcf7..e80d3e92 100644 --- a/tests/global.d.ts +++ b/tests/global.d.ts @@ -12,6 +12,4 @@ declare var dataDir: string; declare var defaultTimeout: number; declare var failedConnectionTimeout: number; declare var maxTimeout: number; -declare var testCmd: string | undefined; -declare var testPlatform: string; declare var tmpDir: string; diff --git a/tests/integration/docker/docker.test.ts b/tests/integration/docker/docker.test.ts new file mode 100644 index 00000000..9b5550f6 --- /dev/null +++ b/tests/integration/docker/docker.test.ts @@ -0,0 +1,318 @@ +import path from 'path'; +import fs from 'fs'; +import readline from 'readline'; +import process from 'process'; +import { sleep } from 'polykey/dist/utils'; +import Status from 'polykey/dist/status/Status'; +import config from 'polykey/dist/config'; +import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; +import { encodeNodeId } from 'polykey/dist/ids'; +import * as testUtils from '../../utils'; + +/** + * These tests run against a docker image of a PolykeyAgent. + * For these tests to run properly the image must be tagged as `polykey-cli:testtarget` + */ + +describe('asd', () => { + const commandFactory = (cwd: string) => { + const dockerOptions = testUtils.generateDockerArgs(cwd).join(' '); + // Return undefined + return `docker run ${dockerOptions} polykey-cli:testtarget`; + }; + + const logger = new Logger('start test', LogLevel.WARN, [new StreamHandler()]); + let dataDir: string; + let cleanup: Array<() => Promise>; + + beforeEach(async () => { + dataDir = await fs.promises.mkdtemp( + path.join(globalThis.tmpDir, 'polykey-test-'), + ); + cleanup = []; + }); + afterEach(async () => { + await Promise.allSettled(cleanup.map((v) => v())); + await fs.promises + .rm(dataDir, { + force: true, + recursive: true, + }) + // Just ignore failures here + .catch(() => {}); + }); + test( + 'start in foreground', + async () => { + const password = 'abc123'; + const polykeyPath = path.join(dataDir, 'polykey'); + await fs.promises.mkdir(polykeyPath); + const agentProcess = await testUtils.pkSpawn( + [ + 'agent', + 'start', + '--node-path', + path.join(dataDir, 'polykey'), + '--workers', + 'none', + '--seed-nodes', + '', + '--verbose', + '--format', + 'json', + ], + { + env: { + PK_PASSWORD: password, + PK_PASSWORD_OPS_LIMIT: 'min', + PK_PASSWORD_MEM_LIMIT: 'min', + }, + cwd: dataDir, + command: commandFactory(dataDir), + }, + logger, + ); + const rlOut = readline.createInterface(agentProcess.stdout!); + const stdout = await new Promise((resolve, reject) => { + rlOut.once('line', resolve); + rlOut.once('close', () => reject(Error('closed early'))); + }); + const statusLiveData = JSON.parse(stdout); + expect(statusLiveData).toMatchObject({ + pid: expect.any(Number), + nodeId: expect.any(String), + clientHost: expect.any(String), + clientPort: expect.any(Number), + agentHost: expect.any(String), + agentPort: expect.any(Number), + recoveryCode: expect.any(String), + }); + expect( + statusLiveData.recoveryCode.split(' ').length === 12 || + statusLiveData.recoveryCode.split(' ').length === 24, + ).toBe(true); + + const status = new Status({ + statusPath: path.join(dataDir, 'polykey', config.paths.statusBase), + statusLockPath: path.join( + dataDir, + 'polykey', + config.paths.statusLockBase, + ), + fs, + logger, + }); + const statusInfoProm = status.waitFor('DEAD'); + cleanup.push(async () => { + agentProcess.kill('SIGTERM'); + }); + expect((await statusInfoProm).status).toBe('DEAD'); + }, + globalThis.defaultTimeout * 2, + ); + test( + 'start in background', + async () => { + const password = 'abc123'; + const passwordPath = path.join(dataDir, 'password'); + await fs.promises.writeFile(passwordPath, password); + const agentProcess = await testUtils.pkSpawn( + [ + 'agent', + 'start', + '--password-file', + passwordPath, + '--background', + '--background-out-file', + path.join(dataDir, 'out.log'), + '--background-err-file', + path.join(dataDir, 'err.log'), + '--workers', + 'none', + '--seed-nodes', + '', + '--verbose', + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD_OPS_LIMIT: 'min', + PK_PASSWORD_MEM_LIMIT: 'min', + }, + cwd: dataDir, + command: commandFactory(dataDir), + }, + logger, + ); + const agentProcessExit = new Promise((resolve, reject) => { + agentProcess.on('exit', (code, signal) => { + if (code === 0) { + resolve(); + } else { + reject( + new Error( + `Agent process exited with code: ${code} and signal: ${signal}`, + ), + ); + } + }); + }); + + // Setting up cleanup + const status = new Status({ + statusPath: path.join(dataDir, 'polykey', config.paths.statusBase), + statusLockPath: path.join( + dataDir, + 'polykey', + config.paths.statusLockBase, + ), + fs, + logger, + }); + + cleanup.push(async () => { + const statusInfo = (await status.readStatus())!; + if (statusInfo.data.pid != null) { + process.kill(statusInfo.data.pid, 'SIGINT'); + } + await status.waitFor('DEAD'); + }); + + const rlOut = readline.createInterface(agentProcess.stdout!); + const stdout = await new Promise((resolve, reject) => { + rlOut.once('line', resolve); + rlOut.once('close', () => reject(Error('closed early'))); + }); + const statusLiveData = JSON.parse(stdout); + expect(statusLiveData).toMatchObject({ + pid: expect.any(Number), + nodeId: expect.any(String), + clientHost: expect.any(String), + clientPort: expect.any(Number), + agentHost: expect.any(String), + agentPort: expect.any(Number), + recoveryCode: expect.any(String), + }); + // The foreground process PID should nto be the background process PID + expect(statusLiveData.pid).not.toBe(agentProcess.pid); + expect( + statusLiveData.recoveryCode.split(' ').length === 12 || + statusLiveData.recoveryCode.split(' ').length === 24, + ).toBe(true); + await agentProcessExit; + // Make sure that the daemon does output the recovery code + // The recovery code was already written out on agentProcess + const polykeyAgentOut = await fs.promises.readFile( + path.join(dataDir, 'out.log'), + 'utf-8', + ); + expect(polykeyAgentOut).toHaveLength(0); + const statusInfo1 = (await status.readStatus())!; + expect(statusInfo1).toBeDefined(); + expect(statusInfo1.status).toBe('LIVE'); + process.kill(statusInfo1.data.pid, 'SIGINT'); + // Check for graceful exit + const statusInfo2 = await status.waitFor('DEAD'); + expect(statusInfo2.status).toBe('DEAD'); + }, + globalThis.defaultTimeout * 2, + ); + // TODO: this should check for the existance of our node and other nodes in the seed nodes graph + // We can't test for hole punching on the same network, but we can see that all the nodes connect. + test('connect to testnet', async () => { + const password = 'abc123'; + const polykeyPath = path.join(dataDir, 'polykey'); + await fs.promises.mkdir(polykeyPath); + const agentProcess = await testUtils.pkSpawn( + [ + 'agent', + 'start', + '--node-path', + path.join(dataDir, 'polykey'), + '--workers', + 'none', + '--network', + 'testnet', + '--verbose', + '--format', + 'json', + ], + { + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_PASSWORD_OPS_LIMIT: 'min', + PK_PASSWORD_MEM_LIMIT: 'min', + }, + cwd: dataDir, + command: commandFactory(dataDir), + }, + logger, + ); + const status = new Status({ + statusPath: path.join(dataDir, 'polykey', config.paths.statusBase), + statusLockPath: path.join( + dataDir, + 'polykey', + config.paths.statusLockBase, + ), + fs, + logger, + }); + const waitForLiveP = status.waitFor('LIVE'); + + cleanup.push(async () => { + await waitForLiveP; + agentProcess.kill('SIGTERM'); + await status.waitFor('DEAD'); + }); + + await waitForLiveP; + + // Checking for connections + await sleep(2000); + const { stdout } = await testUtils.pkStdio( + ['nodes', 'connections', '--format', 'json'], + { + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, + }, + ); + const connections = JSON.parse(stdout); + // Expect at least 1 connection + expect(connections.length).toBeGreaterThanOrEqual(1); + }); + test.skip('connect to peer using MDNS', async () => { + const agentA = await testUtils.setupTestAgent(logger); + const agentB = await testUtils.setupTestAgent(logger); + + // Checking for connections + const { exitCode } = await testUtils.pkStdio( + [ + 'nodes', + 'ping', + '--format', + 'json', + `${encodeNodeId(agentA.agentStatus.data.nodeId)}`, + ], + { + env: { + PK_NODE_PATH: agentA.agentDir, + PK_PASSWORD: agentA.agentPassword, + }, + cwd: dataDir, + }, + ); + + expect(exitCode).toBe(0); + + // Killing + await agentA.agentClose(); + await agentB.agentClose(); + }); +}); diff --git a/tests/integration/testnet/testnetConnection.test.ts b/tests/integration/testnet/testnetConnection.test.ts deleted file mode 100644 index 4757c1a9..00000000 --- a/tests/integration/testnet/testnetConnection.test.ts +++ /dev/null @@ -1,312 +0,0 @@ -import type { NodeIdEncoded } from 'polykey/dist/nodes/types'; -import path from 'path'; -import fs from 'fs'; -import readline from 'readline'; -import Logger, { LogLevel, StreamHandler, formatting } from '@matrixai/logger'; -import PolykeyAgent from 'polykey/dist/PolykeyAgent'; -import config from 'polykey/dist/config'; -import { sleep } from 'polykey/dist/utils'; -import * as keysUtils from 'polykey/dist/keys/utils'; -import * as testUtils from '../../utils'; - -test('dummy test', async () => {}); - -describe.skip('testnet connection', () => { - const logger = new Logger('TCT', LogLevel.WARN, [new StreamHandler()]); - const format = formatting.format`${formatting.keys}:${formatting.msg}`; - logger.handlers.forEach((handler) => handler.setFormatter(format)); - const seedNodes = Object.entries(config.network.testnet); - const seedNodeId1 = seedNodes[0][0] as NodeIdEncoded; - const _seedNodeAddress1 = seedNodes[0][1]; - let dataDir: string; - beforeEach(async () => { - dataDir = await fs.promises.mkdtemp( - path.join(globalThis.tmpDir, 'polykey-test-'), - ); - }); - afterEach(async () => { - await fs.promises.rm(dataDir, { - force: true, - recursive: true, - }); - }); - test('can connect to `testnet.polykey.io` seed node', async () => { - const password = 'abc123'; - const nodePath = path.join(dataDir, 'polykey'); - // Starting an agent with the testnet as a seed node - const agentProcess = await testUtils.pkSpawn( - [ - 'agent', - 'start', - '--network', - 'testnet', - '--format', - 'json', - '--verbose', - '--workers', - '0', - ], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - logger, - ); - try { - const rlOut = readline.createInterface(agentProcess.stdout!); - await new Promise((resolve, reject) => { - rlOut.once('line', resolve); - rlOut.once('close', reject); - }); - - // Pinging the seed node - const { exitCode: exitCode1 } = await testUtils.pkStdio( - ['nodes', 'ping', seedNodeId1, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - expect(exitCode1).toBe(0); - } finally { - agentProcess.kill('SIGINT'); - await testUtils.processExit(agentProcess); - } - }); - test('network expands when connecting to seed node', async () => { - const password = 'abc123'; - // Starting two nodes with the testnet as the seed node - const nodePathA = path.join(dataDir, 'polykeyA'); - const nodePathB = path.join(dataDir, 'polykeyB'); - const agentProcessA = await testUtils.pkSpawn( - [ - 'agent', - 'start', - '--network', - 'testnet', - '--format', - 'json', - '--verbose', - '--workers', - '0', - ], - { - env: { - PK_NODE_PATH: nodePathA, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - logger, - ); - const agentProcessB = await testUtils.pkSpawn( - [ - 'agent', - 'start', - '--network', - 'testnet', - '--format', - 'json', - '--verbose', - '--workers', - '0', - ], - { - env: { - PK_NODE_PATH: nodePathB, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - logger, - ); - - try { - const rlOutA = readline.createInterface(agentProcessA.stdout!); - const stdoutA = await new Promise((resolve, reject) => { - rlOutA.once('line', resolve); - rlOutA.once('close', reject); - }); - const statusLiveDataA = JSON.parse(stdoutA); - const nodeIdA = statusLiveDataA.nodeId; - - const rlOutB = readline.createInterface(agentProcessB.stdout!); - const stdoutB = await new Promise((resolve, reject) => { - rlOutB.once('line', resolve); - rlOutB.once('close', reject); - }); - const statusLiveDataB = JSON.parse(stdoutB); - const nodeIdB = statusLiveDataB.nodeId; - - // NodeA should ping the seed node - const { exitCode: exitCode1 } = await testUtils.pkStdio( - ['nodes', 'ping', seedNodeId1, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePathA, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - expect(exitCode1).toBe(0); - - // NodeB should ping the seed node - const { exitCode: exitCode2 } = await testUtils.pkStdio( - ['nodes', 'ping', seedNodeId1, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePathB, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - expect(exitCode2).toBe(0); - - // NodeA should be able to ping to NodeB - const { exitCode: exitCode3 } = await testUtils.pkStdio( - ['nodes', 'ping', nodeIdB, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePathA, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - expect(exitCode3).toBe(0); - - // NodeB should be able to ping to NodeA - const { exitCode: exitCode4 } = await testUtils.pkStdio( - ['nodes', 'ping', nodeIdA, '--format', 'json'], - { - env: { - PK_NODE_PATH: nodePathB, - PK_PASSWORD: password, - }, - cwd: dataDir, - }, - ); - expect(exitCode4).toBe(0); - } finally { - agentProcessA.kill('SIGINT'); - agentProcessB.kill('SIGINT'); - await testUtils.processExit(agentProcessA); - await testUtils.processExit(agentProcessB); - } - }); - // This test is known to fail, two nodes on the same network can't hole punch - test.skip('testing hole punching', async () => { - // Const nodePathS = path.join(dataDir, 'seed'); - const nodePath1 = path.join(dataDir, 'node1'); - const nodePath2 = path.join(dataDir, 'node2'); - const password = 'password'; - const localhost = '127.0.0.1'; - logger.setLevel(LogLevel.WARN); - // Console.log('Starting Seed'); - // const seed = await PolykeyAgent.createPolykeyAgent({ - // password, - // nodePath: nodePathS, - // networkConfig: { - // proxyHost: localhost, - // agentHost: localhost, - // clientHost: localhost, - // forwardHost: localhost, - // proxyPort: 55550, - // }, - // keysConfig: { - // privateKeyPemOverride: globalRootKeyPems[0], - // }, - // logger: logger.getChild('S'), - // }); - // const seedNodes: SeedNodes = { - // [nodesUtils.encodeNodeId(seed.keyManager.getNodeId())]: { - // host: seed.proxy.getProxyHost(), - // port: seed.proxy.getProxyPort(), - // }, - // }; - // const seedNodes: SeedNodes = { - // [seedNodeId1]: seedNodeAddress1, - // }; - // Console.log('Starting Agent1'); - const agent1 = await PolykeyAgent.createPolykeyAgent({ - password, - options: { - nodePath: nodePath1, - seedNodes, - agentServiceHost: localhost, - clientServiceHost: localhost, - agentServicePort: 55551, - keys: { - passwordOpsLimit: keysUtils.passwordOpsLimits.min, - passwordMemLimit: keysUtils.passwordMemLimits.min, - strictMemoryLock: false, - }, - }, - logger: logger.getChild('A1'), - }); - // Console.log('Starting Agent2'); - logger.setLevel(LogLevel.WARN); - const agent2 = await PolykeyAgent.createPolykeyAgent({ - password, - options: { - nodePath: nodePath2, - seedNodes, - agentServiceHost: localhost, - clientServiceHost: localhost, - agentServicePort: 55552, - keys: { - passwordOpsLimit: keysUtils.passwordOpsLimits.min, - passwordMemLimit: keysUtils.passwordMemLimits.min, - strictMemoryLock: false, - }, - }, - logger: logger.getChild('A2'), - }); - try { - logger.setLevel(LogLevel.WARN); - // Console.log('syncing 1'); - // await agent1.nodeManager.syncNodeGraph(true); - // console.log('syncing 2'); - // await agent2.nodeManager.syncNodeGraph(true); - - // seed hun0 - // agent1 ijtg - // agent2 fhmg - - // Ping the node - await sleep(5000); - // Console.log( - // nodesUtils.encodeNodeId(agent1.keyManager.getNodeId()), - // agent1.proxy.getProxyHost(), - // agent1.proxy.getProxyPort(), - // ); - // console.log( - // nodesUtils.encodeNodeId(agent2.keyManager.getNodeId()), - // agent2.proxy.getProxyHost(), - // agent2.proxy.getProxyPort(), - // ); - // console.log('Attempting ping'); - const pingResult = await agent2.nodeManager.pingNode( - agent1.keyRing.getNodeId(), - ); - // Console.log(pingResult); - expect(pingResult).toBe(true); - } finally { - logger.setLevel(LogLevel.WARN); - // Console.log('cleaning up'); - // Await seed.stop(); - await agent1.stop(); - await agent2.stop(); - } - }); - - // We want to ping each other -}); diff --git a/tests/utils/exec.ts b/tests/utils/exec.ts index 3a722b3e..8215eb4f 100644 --- a/tests/utils/exec.ts +++ b/tests/utils/exec.ts @@ -263,7 +263,7 @@ async function pkExec( */ async function pkSpawn( args: Array = [], - opts: ExecOpts = { env: {}, command: globalThis.testCmd }, + opts: ExecOpts = { env: {} }, logger: Logger = new Logger(pkSpawn.name), ): Promise { if (opts.command == null) { @@ -347,9 +347,6 @@ async function pkExecWithShell( ...process.env, ...opts.env, }; - if (globalThis.testPlatform === 'docker') { - env.DOCKER_OPTIONS = generateDockerArgs(cwd).join(' '); - } // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular @@ -442,9 +439,6 @@ async function pkSpawnWithShell( ...process.env, ...opts.env, }; - if (globalThis.testPlatform === 'docker') { - env.DOCKER_OPTIONS = generateDockerArgs(cwd).join(' '); - } // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular @@ -585,6 +579,7 @@ function escapeShellArgs(arg: string): string { export { tsConfigPath, polykeyPath, + generateDockerArgs, exec, spawn, pk, From d6a87a3e916920956ca6d749775f973a7b8f9c7b Mon Sep 17 00:00:00 2001 From: Brian Botha Date: Tue, 19 Dec 2023 15:50:54 +1100 Subject: [PATCH 5/5] ci: ignore integration domain for normal tests [ci skip] --- scripts/check-test-generate.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/check-test-generate.sh b/scripts/check-test-generate.sh index 061b1ea4..c284320f 100755 --- a/scripts/check-test-generate.sh +++ b/scripts/check-test-generate.sh @@ -52,6 +52,10 @@ for test_dir in tests/**/*/; do if [[ "$test_dir" =~ discovery ]]; then continue fi + # Ignore integration domain for now + if [[ "$test_dir" =~ integration ]]; then + continue + fi test_files=("$test_dir"*.test.ts) if [ ${#test_files[@]} -eq 0 ]; then continue