diff options
| author | Shinigami <[email protected]> | 2023-03-16 09:45:48 +0100 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-03-16 09:45:48 +0100 |
| commit | 256631d6be4b2b40ae660a7e9052cde07a3da18c (patch) | |
| tree | 0356ec41753c439df7bc30de7e2c4403e8f000d1 | |
| parent | f2abf8b49439fc3c6197ecc9a16e212c9e64497a (diff) | |
| download | faker-256631d6be4b2b40ae660a7e9052cde07a3da18c.tar.xz faker-256631d6be4b2b40ae660a7e9052cde07a3da18c.zip | |
fix(random): prevent infinite do-while (#1938)
| -rw-r--r-- | src/modules/random/index.ts | 10 | ||||
| -rw-r--r-- | test/random.spec.ts | 8 |
2 files changed, 17 insertions, 1 deletions
diff --git a/src/modules/random/index.ts b/src/modules/random/index.ts index a2847bbc..b35b7c87 100644 --- a/src/modules/random/index.ts +++ b/src/modules/random/index.ts @@ -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); @@ -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))); diff --git a/test/random.spec.ts b/test/random.spec.ts index 3818274f..5e6a93b2 100644 --- a/test/random.spec.ts +++ b/test/random.spec.ts @@ -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'; @@ -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', () => { |
