Skip to content

Commit

Permalink
Merge branch 'main' into fix/locale-definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT authored May 4, 2022
2 parents 43385c2 + f1dba1b commit f2bd56f
Show file tree
Hide file tree
Showing 7 changed files with 150 additions and 10 deletions.
10 changes: 4 additions & 6 deletions scripts/copyMimeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import options from '../.prettierrc.cjs';

const rootPath = path.resolve(__dirname, '..');
const mimeDbPath = path.resolve(rootPath, 'node_modules/mime-db/db.json');
const mimeDbLicencePath = path.resolve(
const mimeDbLicensePath = path.resolve(
rootPath,
'node_modules/mime-db/LICENSE'
);
Expand All @@ -20,10 +20,8 @@ fs.readFile(mimeDbPath, 'utf8', (err, data) => {
throw err;
}

const licence = fs.readFileSync(mimeDbLicencePath, { encoding: 'utf8' });
const mimeTypeFileContent = `// This file is generated by scripts/copyMimeTypes.ts\n// Do not edit this file directly. Instead, update mime-db and run \`pnpm run copy:mime-types\`\n\n/*\n${
licence as string
}*/\n\nexport default ${data as string};\n`;
const license = fs.readFileSync(mimeDbLicensePath, { encoding: 'utf8' });
const mimeTypeFileContent = `// This file is generated by scripts/copyMimeTypes.ts\n// Do not edit this file directly. Instead, update mime-db and run \`pnpm run copy:mime-types\`\n\n/*\n${license}*/\n\nexport default ${data};\n`;

fs.writeFile(
mimeTypesTsPath,
Expand All @@ -33,7 +31,7 @@ fs.readFile(mimeDbPath, 'utf8', (err, data) => {
throw err;
}

console.log(`Mime types copied to ${mimeTypesTsPath as string}`);
console.log(`Mime types copied to ${mimeTypesTsPath}`);
}
);
});
2 changes: 0 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,3 @@ export { Faker };
export const faker: Faker = new Faker({
locales: allLocales,
});

export default faker;
1 change: 1 addition & 0 deletions test/scripts/apidoc/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
*.actuals.json
temp/
111 changes: 111 additions & 0 deletions test/scripts/apidoc/examplesAndDeprecations.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { mkdirSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { DeclarationReflection, SignatureReflection } from 'typedoc';
import { ReflectionKind } from 'typedoc';
import type { SpyInstance } from 'vitest';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { faker } from '../../../src';
import { loadProject } from './utils';

/*
* This test ensures, that every method
* - has working examples
* - and running these does not log anything, unless the method is deprecated
*/

const locales: Record<string, string> = {
GH: 'en_GH',
US: 'en_US',
};

describe('examples and deprecations', () => {
const project = loadProject();

const directs: DeclarationReflection[] = project
.getChildrenByKind(ReflectionKind.Class)
.filter((ref) => ref.name === 'Faker')[0]
.getChildrenByKind(ReflectionKind.Property)
.filter((ref) => ['fake', 'unique'].includes(ref.name));

const modules: Record<string, DeclarationReflection[]> = project
.getChildrenByKind(ReflectionKind.Namespace)[0]
.getChildrenByKind(ReflectionKind.Class)
.filter((ref) => faker[ref.name.toLowerCase()] && ref.name !== 'Mersenne')
.reduce(
(a, v) => ({
...a,
[v.name]: v.getChildrenByKind(ReflectionKind.Method),
}),
{ directs }
);

const consoleSpies: Array<SpyInstance> = Object.keys(console)
.filter((key) => typeof console[key] === 'function')
.map((methodName) => vi.spyOn(console, methodName as keyof typeof console));

afterAll(() => {
faker.locale = 'en';
for (const spy of consoleSpies) {
spy.mockRestore();
}
});

describe.each(Object.entries(modules))('%s', (moduleName, methods) => {
const methodsByName: Record<string, DeclarationReflection> = methods.reduce(
(a, v) => ({ ...a, [v.name]: v }),
{}
);

beforeEach(() => {
faker.locale = 'en';
for (const spy of consoleSpies) {
spy.mockReset();
}
});

// eslint-disable-next-line @typescript-eslint/no-misused-promises
it.each(Object.entries(methodsByName))('%s', async (methodName, method) => {
const signatures: SignatureReflection[] =
method.signatures || method.type['declaration'].signatures;
const signature = signatures[signatures.length - 1];

// Extract examples and make them runnable
let examples =
signature?.comment?.tags
.filter((tag) => tag.tagName === 'example')
.map((tag) => tag.text.trimEnd())
.join('')
.trim() ?? '';
examples = examples.replace(
/faker([A-Z]{2})\./g,
(_, locale: string) => `faker.locale = '${locales[locale]}';\nfaker.`
);

expect(examples, `${moduleName}.${methodName} to have examples`).not.toBe(
''
);

// Save examples to a file to run it
const dir = resolve(__dirname, 'temp', moduleName);
mkdirSync(dir, { recursive: true });
const path = resolve(dir, `${methodName}.ts`);
writeFileSync(
path,
`import { faker } from '../../../../../src';\n${examples}`
);

// Run the examples
await import(path);

// Verify logging
const deprecatedFlag = signature.comment?.hasTag('deprecated') ?? false;
if (deprecatedFlag) {
expect(consoleSpies[1]).toHaveBeenCalled();
} else {
for (const spy of consoleSpies) {
expect(spy).not.toHaveBeenCalled();
}
}
});
});
});
19 changes: 18 additions & 1 deletion test/scripts/apidoc/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DeclarationReflection } from 'typedoc';
import type { DeclarationReflection, ProjectReflection } from 'typedoc';
import { ReflectionKind } from 'typedoc';
import { newTypeDocApp, patchProject } from '../../../scripts/apidoc/utils';

Expand All @@ -24,3 +24,20 @@ export function loadExampleMethods(): Record<string, DeclarationReflection> {

return methods;
}

/**
* Loads the project using TypeDoc.
*/
export function loadProject(): ProjectReflection {
const app = newTypeDocApp();

app.bootstrap({
entryPoints: ['src/index.ts'],
});

const project = app.convert();

patchProject(project);

return project;
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"target": "ES5",
"target": "ES2020",
"moduleResolution": "Node",
"rootDir": "src",
"outDir": "dist",
"declaration": true,
Expand Down
14 changes: 14 additions & 0 deletions tsconfig.lint.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
{
"compilerOptions": {
"target": "ES2020",
"moduleResolution": "Node",
"esModuleInterop": true,
"allowJs": true,
"alwaysStrict": true,
// "strictNullChecks": true,
// "strictBindCallApply": true,
"strictFunctionTypes": true,
// "strictPropertyInitialization": true,
// "noImplicitAny": true,
// "noImplicitThis": true,
"useUnknownInCatchVariables": true,
"stripInternal": true,

"rootDir": ".",
"noEmit": true
},
Expand Down

0 comments on commit f2bd56f

Please sign in to comment.