Skip to content

Commit

Permalink
fix(random): prevent infinite do-while (#1938)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinigami92 committed Mar 16, 2023
1 parent f2abf8b commit 256631d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/modules/random/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ export class RandomModule {
];
let result: string;

let iteration = 0;

do {
// randomly pick from the many faker methods that can generate words
const randomWordMethod = this.faker.helpers.arrayElement(wordMethods);
Expand All @@ -133,6 +135,14 @@ export class RandomModule {
result = randomWordMethod();
} catch {
// catch missing locale data potentially required by randomWordMethod
iteration++;

if (iteration > 100) {
throw new FakerError(
'No matching word data available for the current locale'
);
}

continue;
}
} while (!result || bannedChars.some((char) => result.includes(char)));
Expand Down
8 changes: 7 additions & 1 deletion test/random.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { faker, FakerError, fakerZH_CN } from '../src';
import { Faker, faker, FakerError, fakerZH_CN } from '../src';
import { seededTests } from './support/seededRuns';
import { times } from './support/times';

Expand Down Expand Up @@ -81,6 +81,12 @@ describe('random', () => {
);
}
);

it('should throw error if no data are available', () => {
const faker = new Faker({ locale: [{ title: 'custom' }] });

expect(() => faker.random.word()).toThrowError();
});
});

describe('words', () => {
Expand Down

0 comments on commit 256631d

Please sign in to comment.