Skip to content

Commit

Permalink
refactor(chore): improvements testing (#46)
Browse files Browse the repository at this point in the history
This PR includes:
- a refactoring for the test helper to mock schemas
- updated imports
- adoptions to the schemas (removes `label`)
  • Loading branch information
BioPhoton authored Sep 16, 2023
1 parent ba048be commit ce21d87
Show file tree
Hide file tree
Showing 17 changed files with 3,116 additions and 1,712 deletions.
4,568 changes: 3,043 additions & 1,525 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion packages/cli/src/lib/collect/command-object.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ function mockPlugin(): PluginConfig {
slug: 'command-object-audit-slug',
title: 'audit title',
description: 'audit description',
label: 'mock audit label',
docsUrl: 'http://www.my-docs.dev',
},
],
Expand Down
2 changes: 1 addition & 1 deletion packages/models/src/lib/category-config.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { categoryConfigSchema } from './category-config';
import { mockCategory } from './implementation/helpers.mock';
import { mockCategory } from '../../test';

describe('categoryConfigSchema', () => {
it('should parse if configuration with audit refs is valid', () => {
Expand Down
6 changes: 1 addition & 5 deletions packages/models/src/lib/core-config.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { describe, expect, it } from 'vitest';
import { coreConfigSchema } from './core-config';
import {
mockCategory,
mockConfig,
mockPluginConfig,
} from './implementation/helpers.mock';
import { mockCategory, mockConfig, mockPluginConfig } from '../../test';

/*
- plugin slug: es-lint
Expand Down
19 changes: 19 additions & 0 deletions packages/models/src/lib/implementation/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export function weightSchema(
export function positiveIntSchema(description: string) {
return z.number({ description }).int().nonnegative();
}

/**
* Schema for a unixFilePath
* @param description
Expand All @@ -89,6 +90,24 @@ export function unixFilePathSchema(description: string) {
return z.string({ description }).regex(unixFilePathRegex);
}

export function packageVersionSchema(options?: {
versionDescription?: string;
optional?: boolean;
}) {
let { versionDescription, optional } = options || {};
versionDescription = versionDescription || 'NPM version of the package';
optional = !!optional;
const packageSchema = z.string({ description: 'NPM package name' });
const versionSchema = z.string({ description: versionDescription });
return z.object(
{
package: optional ? packageSchema.optional() : packageSchema,
version: optional ? versionSchema.optional() : versionSchema,
},
{ description: 'NPM package name and version of a published package' },
);
}

export function weightedRefSchema(
description: string,
slugDescription: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/models/src/lib/persist-config.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { mockPersistConfig } from './implementation/helpers.mock';
import { mockPersistConfig } from '../../test';
import { persistConfigSchema } from './persist-config';

describe('persistConfigSchema', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/models/src/lib/plugin-config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
mockGroupConfig,
mockPluginConfig,
mockRunnerOutput,
} from './implementation/helpers.mock';
} from '../../test';
import {
auditGroupSchema,
pluginConfigSchema,
Expand Down
63 changes: 21 additions & 42 deletions packages/models/src/lib/plugin-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
descriptionSchema,
docsUrlSchema,
generalFilePathSchema,
packageVersionSchema,
positiveIntSchema,
scorableSchema,
slugSchema,
Expand All @@ -18,22 +19,26 @@ import {
} from './implementation/utils';

// Define Zod schema for the PluginMetadata type
export const pluginMetadataSchema = z.object(
{
slug: slugSchema(),
name: z
.string({
description: 'Display name',
})
.max(128),
icon: z.union([z.unknown(), z.string()], {
description: 'Icon from VSCode Material Icons extension',
}),
docsUrl: docsUrlSchema('Plugin documentation site'),
},
{
description: 'Plugin metadata',
},
export const pluginMetadataSchema = packageVersionSchema({
optional: true,
}).merge(
z.object(
{
slug: slugSchema(),
name: z
.string({
description: 'Display name',
})
.max(128),
icon: z.union([z.unknown(), z.string()], {
description: 'Icon from VSCode Material Icons extension',
}),
docsUrl: docsUrlSchema('Plugin documentation site'),
},
{
description: 'Plugin metadata',
},
),
);

// Define Zod schema for the RunnerConfig type
Expand All @@ -54,11 +59,6 @@ const runnerConfigSchema = z.object(
export const auditMetadataSchema = z.object(
{
slug: slugSchema('ID (unique within plugin)'),
label: z
.string({
description: 'Abbreviated name',
})
.max(128),
title: titleSchema('Descriptive name'),
description: descriptionSchema('Description (Markdown)'),
docsUrl: docsUrlSchema('Link to documentation (rationale)'),
Expand Down Expand Up @@ -138,27 +138,6 @@ export const pluginConfigSchema = z

export type PluginConfig = z.infer<typeof pluginConfigSchema>;

/**
* Define Zod schema for the SourceFileLocation type.
*
* @example
*
* // Example data for the RunnerOutput type
* const runnerOutputData = {
* audits: [
* // ... populate with example audit data ...
* ],
* };
*
* // Validate the data against the schema
* const validationResult = runnerOutputSchema.safeParse(runnerOutputData);
*
* if (validationResult.success) {
* console.log('Valid runner output:', validationResult.data);
* } else {
* console.error('Invalid runner output:', validationResult.error);
* }
*/
const sourceFileLocationSchema = z.object(
{
file: unixFilePathSchema('Relative path to source file in Git repo'),
Expand Down
5 changes: 1 addition & 4 deletions packages/models/src/lib/report.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { describe, expect, it } from 'vitest';
import {
mockPluginConfig,
mockRunnerOutput,
} from './implementation/helpers.mock';
import { mockPluginConfig, mockRunnerOutput } from '../../test';
import { runnerOutputAuditRefsPresentInPluginConfigs } from './report';

describe('RunnerOutput', () => {
Expand Down
21 changes: 12 additions & 9 deletions packages/models/src/lib/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
auditResultSchema,
pluginMetadataSchema,
} from './plugin-config';
import { packageVersionSchema } from './implementation/schemas';

export type PluginOutput = RunnerOutput & {
slug: string;
Expand All @@ -25,15 +26,17 @@ export const pluginReportSchema = z.object({
});
export type PluginReport = z.infer<typeof pluginReportSchema>;

export const reportSchema = z.object(
{
package: z.string({ description: 'NPM package name' }),
version: z.string({ description: 'NPM version of the CLI' }),
date: z.string({ description: 'Start date and time of the collect run' }),
duration: z.number({ description: 'Duration of the collect run in ms' }),
plugins: z.array(pluginReportSchema),
},
{ description: 'Collect output data.' },
export const reportSchema = packageVersionSchema({
versionDescription: 'NPM version of the CLI',
}).merge(
z.object(
{
date: z.string({ description: 'Start date and time of the collect run' }),
duration: z.number({ description: 'Duration of the collect run in ms' }),
plugins: z.array(pluginReportSchema),
},
{ description: 'Collect output data.' },
),
);

export type Report = z.infer<typeof reportSchema>;
Expand Down
2 changes: 1 addition & 1 deletion packages/models/src/lib/upload-config.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { mockUploadConfig } from './implementation/helpers.mock';
import { mockUploadConfig } from '../../test';
import { uploadConfigSchema } from './upload-config';

describe('uploadConfigSchema', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { CategoryConfig } from '../category-config';
import { CoreConfig } from '../core-config';
import { PersistConfig } from '../persist-config';
import { CategoryConfig } from '../src/lib/category-config';
import { CoreConfig } from '../src/lib/core-config';
import { PersistConfig } from '../src/lib/persist-config';
import {
AuditGroup,
AuditMetadata,
PluginConfig,
RunnerOutput,
} from '../plugin-config';
import { UploadConfig } from '../upload-config';
} from '../src/lib/plugin-config';
import { UploadConfig } from '../src/lib/upload-config';

export function mockConfig(opt?: {
pluginSlug?: string | string[];
Expand All @@ -31,13 +31,14 @@ export function mockPluginConfig(opt?: {
pluginSlug?: string;
auditSlug?: string | string[];
groupSlug?: string | string[];
outputPath?: string;
}): PluginConfig {
const { groupSlug } = opt || {};
let { pluginSlug, auditSlug } = opt || {};
let { pluginSlug, auditSlug, outputPath } = opt || {};
pluginSlug = pluginSlug || 'mock-plugin-slug';
auditSlug = auditSlug || 'mock-audit-slug';
const addGroups = groupSlug !== undefined;
const outputPath = 'out-execute-plugin.json';
outputPath = outputPath || 'out-execute-plugin.json';

const audits = Array.isArray(auditSlug)
? auditSlug.map(slug => mockAuditConfig({ auditSlug: slug }))
Expand All @@ -59,7 +60,7 @@ export function mockPluginConfig(opt?: {
'-c',
`echo '${JSON.stringify({
audits: audits.map(({ slug }, idx) => ({
slug: `${pluginSlug}#${slug}`,
slug: `${slug}`,
value: parseFloat('0.' + idx),
})),
} satisfies RunnerOutput)}' > ${outputPath}`,
Expand All @@ -81,7 +82,6 @@ export function mockAuditConfig(opt?: { auditSlug?: string }): AuditMetadata {
slug: auditSlug,
title: 'audit title',
description: 'audit description',
label: 'mock audit label',
docsUrl: 'http://www.my-docs.dev',
};
}
Expand Down
1 change: 1 addition & 0 deletions packages/models/test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './helpers.mock';
3 changes: 2 additions & 1 deletion packages/models/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"vite.config.ts",
"src/**/*.spec.ts",
"src/**/*.test.ts",
"src/**/*.mock.ts"
"src/**/*.mock.ts",
"test/**/*.ts"
]
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { executePlugin, executePlugins } from './execute-plugin';
import { mockPluginConfig } from './mock/schema-helper.mock';
import { mockPluginConfig } from '@quality-metrics/models/testing';
import {
pluginConfigSchema,
runnerOutputSchema,
Expand All @@ -9,16 +9,10 @@ import {
describe('executePlugin', () => {
it('should work with valid plugin', async () => {
const cfg = pluginConfigSchema.parse(mockPluginConfig());
const expectedResult = [
{
slug: 'mock-audit-slug',
value: 0,
},
];
const errorSpy = vi.fn();
const pluginResult = await executePlugin(cfg).catch(errorSpy);
expect(pluginResult.audits).toEqual(expectedResult);
expect(errorSpy).toHaveBeenCalledTimes(0);
expect(pluginResult.audits[0].slug).toBe('mock-audit-slug');
expect(() => runnerOutputSchema.parse(pluginResult)).not.toThrow();
});

Expand Down
Loading

0 comments on commit ce21d87

Please sign in to comment.