Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/json-type/src/random/Random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ export class Random {
let max = Number.MAX_SAFE_INTEGER;
const schema = type.getSchema();
const {lt, lte, gt, gte} = schema;
const isIntegerFormat = schema.format && ['i8', 'i16', 'i32', 'i64', 'i', 'u8', 'u16', 'u32', 'u64', 'u'].includes(schema.format);
if (gt !== undefined) min = gt;
if (gte !== undefined)
if (gte === lte) return gte;
else min = gte + 0.000000000000001;
else min = isIntegerFormat ? gte : gte + 0.000000000000001;
if (lt !== undefined) max = lt;
if (lte !== undefined) max = lte - 0.000000000000001;
if (lte !== undefined) max = isIntegerFormat ? lte : lte - 0.000000000000001;
if (min >= max) return max;
if (schema.format) {
switch (schema.format) {
Expand Down
28 changes: 28 additions & 0 deletions packages/json-type/src/random/__tests__/random.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,34 @@ describe('Random', () => {
}
});

test('num with integer format and gte/lte always produces clean integers', () => {
// Test u16 format with gte/lte constraints (the configuration that was failing)
const type = t.Number({format: 'u16', gte: 1, lte: 65535});
for (let i = 0; i < 100; i++) {
const value = Random.gen(type);
expect(typeof value).toBe('number');
expect(Number.isInteger(value)).toBe(true);
expect(value).toBeGreaterThanOrEqual(1);
expect(value).toBeLessThanOrEqual(65535);
// Verify no floating-point artifacts
expect(value).toBe(Math.floor(value));
validate(type, value);
}
});

test('num with all integer formats produces clean integers', () => {
const integerFormats = ['i8', 'i16', 'i32', 'u8', 'u16', 'u32'] as const;
for (const format of integerFormats) {
const type = t.Number({format, gte: 1, lte: 100});
for (let i = 0; i < 50; i++) {
const value = Random.gen(type);
expect(Number.isInteger(value)).toBe(true);
expect(value).toBe(Math.floor(value));
validate(type, value);
}
}
});

test('bool generates valid booleans', () => {
const type = t.Boolean();
for (let i = 0; i < 10; i++) {
Expand Down
Loading