|
| 1 | +import fs from "fs"; |
| 2 | +import os from "os"; |
| 3 | +import path from "path"; |
| 4 | +import { afterEach, beforeEach, describe, expect, it } from "vitest"; |
| 5 | +import { checkAndSaveFile } from "src/utils/qrDecode"; |
| 6 | + |
| 7 | +const SAMPLE_KEYSTORE = JSON.stringify({ |
| 8 | + version: 3, |
| 9 | + id: "00000000-0000-0000-0000-000000000000", |
| 10 | + address: "0000000000000000000000000000000000000000", |
| 11 | +}); |
| 12 | +const SAMPLE_UUID = "00000000-0000-0000-0000-000000000000"; |
| 13 | + |
| 14 | +describe("checkAndSaveFile", () => { |
| 15 | + let baseDir: string; |
| 16 | + |
| 17 | + beforeEach(() => { |
| 18 | + baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "qr-decode-test-")); |
| 19 | + }); |
| 20 | + |
| 21 | + afterEach(() => { |
| 22 | + fs.rmSync(baseDir, { recursive: true, force: true }); |
| 23 | + }); |
| 24 | + |
| 25 | + it("creates the keystore directory when it does not exist (PLD-1393)", async () => { |
| 26 | + // Simulate a PC that has never created an account: the keystore folder |
| 27 | + // does not exist yet. |
| 28 | + const keyStorePath = path.join(baseDir, "planetarium", "keystore"); |
| 29 | + expect(fs.existsSync(keyStorePath)).toBe(false); |
| 30 | + |
| 31 | + await expect( |
| 32 | + checkAndSaveFile(keyStorePath, SAMPLE_KEYSTORE, SAMPLE_UUID), |
| 33 | + ).resolves.toBeUndefined(); |
| 34 | + |
| 35 | + expect(fs.existsSync(keyStorePath)).toBe(true); |
| 36 | + const files = fs.readdirSync(keyStorePath); |
| 37 | + expect(files.some((f) => f.includes(SAMPLE_UUID))).toBe(true); |
| 38 | + }); |
| 39 | + |
| 40 | + it("saves into an already-existing directory", async () => { |
| 41 | + await expect( |
| 42 | + checkAndSaveFile(baseDir, SAMPLE_KEYSTORE, SAMPLE_UUID), |
| 43 | + ).resolves.toBeUndefined(); |
| 44 | + |
| 45 | + const files = fs.readdirSync(baseDir); |
| 46 | + expect(files.some((f) => f.includes(SAMPLE_UUID))).toBe(true); |
| 47 | + }); |
| 48 | + |
| 49 | + it("rejects when a key with the same uuid already exists", async () => { |
| 50 | + await checkAndSaveFile(baseDir, SAMPLE_KEYSTORE, SAMPLE_UUID); |
| 51 | + |
| 52 | + await expect( |
| 53 | + checkAndSaveFile(baseDir, SAMPLE_KEYSTORE, SAMPLE_UUID), |
| 54 | + ).rejects.toThrow("This key already exists."); |
| 55 | + }); |
| 56 | +}); |
0 commit comments