2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-05-29 09:09:30 +00:00
|
|
|
import { assert, assertEquals, assertRejects } from "@std/assert";
|
2023-04-25 02:03:15 +00:00
|
|
|
import { generate, validate } from "./v3.ts";
|
|
|
|
|
|
|
|
const NAMESPACE = "1b671a64-40d5-491e-99b0-da01ff1f3341";
|
|
|
|
|
2023-12-20 21:52:37 +00:00
|
|
|
Deno.test("generate() generates a non-empty string", async () => {
|
2023-04-25 02:03:15 +00:00
|
|
|
const u = await generate(NAMESPACE, new Uint8Array());
|
|
|
|
assertEquals(typeof u, "string", "returns a string");
|
|
|
|
assert(u !== "", "return string is not empty");
|
|
|
|
});
|
|
|
|
|
2023-12-20 21:52:37 +00:00
|
|
|
Deno.test("generate() generates UUIDs in version 3 format", async () => {
|
2023-04-25 02:03:15 +00:00
|
|
|
for (let i = 0; i < 10000; i++) {
|
|
|
|
const u = await generate(
|
|
|
|
NAMESPACE,
|
|
|
|
new TextEncoder().encode(i.toString()),
|
|
|
|
) as string;
|
2023-12-20 21:52:37 +00:00
|
|
|
assert(validate(u), `${u} is not a valid uuid v3`);
|
2023-04-25 02:03:15 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-12-20 21:52:37 +00:00
|
|
|
Deno.test("generate() generates a name-based UUID using MD5 hash", async () => {
|
2023-04-25 02:03:15 +00:00
|
|
|
const u = await generate(NAMESPACE, new TextEncoder().encode("Hello, World"));
|
|
|
|
assertEquals(u, "71d7129f-e809-30ed-a2c6-ea9032b43c0d");
|
|
|
|
});
|
|
|
|
|
2023-12-20 21:52:37 +00:00
|
|
|
Deno.test("validate() checks if a string is a valid v3 UUID", async () => {
|
2023-04-25 02:03:15 +00:00
|
|
|
const u = await generate(
|
|
|
|
"1b671a64-40d5-491e-99b0-da01ff1f3341",
|
|
|
|
new TextEncoder().encode("Hello, World"),
|
|
|
|
);
|
|
|
|
const t = "4b4f2adc-5b27-37b5-8e3a-c4c4bcf94f05";
|
|
|
|
const n = "4b4f2adc-5b27-17b5-8e3a-c4c4bcf94f05";
|
|
|
|
|
|
|
|
assert(validate(u), `generated ${u} should be valid`);
|
|
|
|
assert(validate(t), `${t} should be valid`);
|
|
|
|
assert(!validate(n), `${n} should not be valid`);
|
|
|
|
});
|
2024-05-29 08:19:55 +00:00
|
|
|
|
|
|
|
Deno.test("generate() throws on invalid namespace", async () => {
|
|
|
|
await assertRejects(
|
|
|
|
async () => await generate("invalid-uuid", new Uint8Array()),
|
2024-05-29 09:09:30 +00:00
|
|
|
TypeError,
|
2024-08-26 04:36:01 +00:00
|
|
|
"Cannot generate UUID: invalid namespace invalid-uuid",
|
2024-05-29 09:09:30 +00:00
|
|
|
);
|
|
|
|
await assertRejects(
|
|
|
|
async () =>
|
|
|
|
await generate("1b671a64-40d5-491e-99b0-da01ff1f334Z", new Uint8Array()),
|
|
|
|
TypeError,
|
2024-08-26 04:36:01 +00:00
|
|
|
"Cannot generate UUID: invalid namespace 1b671a64-40d5-491e-99b0-da01ff1f334Z",
|
2024-05-29 08:19:55 +00:00
|
|
|
);
|
|
|
|
});
|