chore: 补充单元测试

This commit is contained in:
xiaojunnuo
2026-05-01 09:16:46 +08:00
parent 80092823db
commit 0a0f1e90e1
24 changed files with 656 additions and 187 deletions
@@ -0,0 +1,54 @@
/// <reference types="mocha" />
/// <reference types="node" />
import assert from "node:assert/strict";
import { RandomUtil } from "./random.js";
describe("RandomUtil.randomStr", () => {
it("generates an 8-character alphanumeric string by default", () => {
const result = RandomUtil.randomStr();
assert.equal(result.length, 8);
assert.match(result, /^[A-Za-z0-9]+$/);
});
it("uses the requested length", () => {
assert.equal(RandomUtil.randomStr(0), "");
assert.equal(RandomUtil.randomStr(1).length, 1);
assert.equal(RandomUtil.randomStr(16).length, 16);
});
it("supports a custom character set", () => {
assert.equal(RandomUtil.randomStr(6, "A"), "AAAAAA");
});
it("supports the legacy true option as alphanumeric mode", () => {
const result = RandomUtil.randomStr(32, true);
assert.match(result, /^[A-Za-z0-9]+$/);
});
it("can generate from numbers only", () => {
const result = RandomUtil.randomStr(12, { letters: false });
assert.match(result, /^[0-9]+$/);
});
it("can generate from caller-provided option character sets", () => {
assert.equal(RandomUtil.randomStr(4, { numbers: "7", letters: false }), "7777");
assert.equal(RandomUtil.randomStr(4, { numbers: false, letters: "x" }), "xxxx");
assert.equal(RandomUtil.randomStr(4, { numbers: false, letters: false, specials: "!" }), "!!!!");
});
it("can generate from built-in specials only", () => {
const result = RandomUtil.randomStr(20, { numbers: false, letters: false, specials: true });
assert.match(result, /^[~!@#$%^*()_+\-=[\]{}|;:,./<>?]+$/);
});
it("rejects an empty character set", () => {
assert.throws(() => RandomUtil.randomStr(4, ""), /at least one available character/);
assert.throws(() => RandomUtil.randomStr(4, { numbers: false, letters: false }), /at least one available character/);
});
});
+9 -4
View File
@@ -2,14 +2,16 @@ const numbers = "0123456789";
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const specials = "~!@#$%^*()_+-=[]{}|;:,./<>?";
type RandomStrOptions = true | string | { numbers?: false | string; letters?: false | string; specials?: boolean | string };
/**
* Generate random string
* @param {Number} length
* @param {Object} options
*/
function randomStr(length, options?) {
length || (length = 8);
options || (options = {});
function randomStr(length?: number, options?: RandomStrOptions) {
length ?? (length = 8);
options ?? (options = {});
let chars = "";
let result = "";
@@ -32,6 +34,10 @@ function randomStr(length, options?) {
}
}
if (chars.length === 0) {
throw new Error("randomStr requires at least one available character");
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
@@ -40,4 +46,3 @@ function randomStr(length, options?) {
}
export const RandomUtil = { randomStr };