|
| 1 | +import { afterEach, describe, expect, test } from "bun:test" |
| 2 | +import { uuid } from "./uuid" |
| 3 | + |
| 4 | +const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto") |
| 5 | +const secureDescriptor = Object.getOwnPropertyDescriptor(globalThis, "isSecureContext") |
| 6 | +const randomDescriptor = Object.getOwnPropertyDescriptor(Math, "random") |
| 7 | + |
| 8 | +const setCrypto = (value: Partial<Crypto>) => { |
| 9 | + Object.defineProperty(globalThis, "crypto", { |
| 10 | + configurable: true, |
| 11 | + value: value as Crypto, |
| 12 | + }) |
| 13 | +} |
| 14 | + |
| 15 | +const setSecure = (value: boolean) => { |
| 16 | + Object.defineProperty(globalThis, "isSecureContext", { |
| 17 | + configurable: true, |
| 18 | + value, |
| 19 | + }) |
| 20 | +} |
| 21 | + |
| 22 | +const setRandom = (value: () => number) => { |
| 23 | + Object.defineProperty(Math, "random", { |
| 24 | + configurable: true, |
| 25 | + value, |
| 26 | + }) |
| 27 | +} |
| 28 | + |
| 29 | +afterEach(() => { |
| 30 | + if (cryptoDescriptor) { |
| 31 | + Object.defineProperty(globalThis, "crypto", cryptoDescriptor) |
| 32 | + } |
| 33 | + |
| 34 | + if (secureDescriptor) { |
| 35 | + Object.defineProperty(globalThis, "isSecureContext", secureDescriptor) |
| 36 | + } |
| 37 | + |
| 38 | + if (!secureDescriptor) { |
| 39 | + delete (globalThis as { isSecureContext?: boolean }).isSecureContext |
| 40 | + } |
| 41 | + |
| 42 | + if (randomDescriptor) { |
| 43 | + Object.defineProperty(Math, "random", randomDescriptor) |
| 44 | + } |
| 45 | +}) |
| 46 | + |
| 47 | +describe("uuid", () => { |
| 48 | + test("uses randomUUID in secure contexts", () => { |
| 49 | + setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" }) |
| 50 | + setSecure(true) |
| 51 | + expect(uuid()).toBe("00000000-0000-0000-0000-000000000000") |
| 52 | + }) |
| 53 | + |
| 54 | + test("falls back in insecure contexts", () => { |
| 55 | + setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" }) |
| 56 | + setSecure(false) |
| 57 | + setRandom(() => 0.5) |
| 58 | + expect(uuid()).toBe("8") |
| 59 | + }) |
| 60 | + |
| 61 | + test("falls back when randomUUID throws", () => { |
| 62 | + setCrypto({ |
| 63 | + randomUUID: () => { |
| 64 | + throw new DOMException("Failed", "OperationError") |
| 65 | + }, |
| 66 | + }) |
| 67 | + setSecure(true) |
| 68 | + setRandom(() => 0.5) |
| 69 | + expect(uuid()).toBe("8") |
| 70 | + }) |
| 71 | + |
| 72 | + test("falls back when randomUUID is unavailable", () => { |
| 73 | + setCrypto({}) |
| 74 | + setSecure(true) |
| 75 | + setRandom(() => 0.5) |
| 76 | + expect(uuid()).toBe("8") |
| 77 | + }) |
| 78 | +}) |
0 commit comments