Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test types adjusts #26156

Merged
merged 4 commits into from
May 17, 2024
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
23 changes: 15 additions & 8 deletions cli/cli.spec.mts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { after, before, it, describe, expect, resetAllMocks, esmocha } from 'esmocha';
import { execaCommandSync } from 'execa';
import { BaseEnvironment } from '@yeoman/types';
import type { GeneratorMeta } from '@yeoman/types';
import type FullEnvironment from 'yeoman-environment';
import { coerce } from 'semver';
import quibble from 'quibble';

Expand Down Expand Up @@ -99,6 +100,7 @@ describe('cli', () => {
const { buildJHipster } = await import('./program.mjs');

mockCli = async (argv: string[], opts = {}) => {
// @ts-expect-error
const program = await buildJHipster({ printLogo: () => {}, ...opts, program: createProgram(), loadCommand: key => opts[`./${key}`] });
return program.parseAsync(argv);
};
Expand Down Expand Up @@ -161,13 +163,14 @@ describe('cli', () => {
const commands = { mocked: {} };
let generator;
let runArgs;
let env: BaseEnvironment;
let env: FullEnvironment;

beforeEach(async () => {
getCommand.mockImplementation(actualGetCommonand);
getCommand.mockImplementation(actualGetCommonand as any);

const BaseGenerator = (await import('../generators/base/index.js')).default;
env = await helpers.createTestEnv();
env = (await helpers.createTestEnv()) as FullEnvironment;
// @ts-expect-error
generator = new (helpers.createDummyGenerator(BaseGenerator))({ env, sharedData: {} });
generator._options = {
foo: {
Expand All @@ -181,17 +184,21 @@ describe('cli', () => {
runArgs = args;
return Promise.resolve();
});
env.composeWith = esmocha.fn<typeof env.composeWith>();
env.composeWith = esmocha.fn<typeof env.composeWith>() as any;
const originalGetGeneratorMeta = env.getGeneratorMeta.bind(env);
env.getGeneratorMeta = esmocha.fn<typeof env.create>().mockImplementation((namespace, args, options) => {
env.getGeneratorMeta = esmocha.fn((namespace: any): GeneratorMeta | undefined => {
if (namespace === 'jhipster:mocked') {
return {
importModule: () => ({}),
namespace,
importModule: async () => ({}),
resolved: __filename,
instantiateHelp: () => generator,
packageNamespace: undefined,
importGenerator: undefined as any,
instantiate: generator,
};
}
return originalGetGeneratorMeta(namespace, args, options);
return originalGetGeneratorMeta(namespace);
});
});

Expand Down
40 changes: 25 additions & 15 deletions cli/environment-builder.spec.mts
Original file line number Diff line number Diff line change
Expand Up @@ -115,32 +115,41 @@ describe('cli - EnvironmentBuilder', () => {
});

describe('createDefaultBuilder', () => {
before(async () => {
let createSpy: sinon.SinonSpy;
let _lookupJHipsterSpy: sinon.SinonSpy;
let _loadBlueprintsSpy: sinon.SinonSpy;
let _lookupBlueprintsSpy: sinon.SinonSpy;

beforeEach(async () => {
await helpers.prepareTemporaryDir();
sinon.spy(EnvironmentBuilder, 'create');
sinon.spy(EnvironmentBuilder.prototype, '_lookupJHipster');
sinon.spy(EnvironmentBuilder.prototype, '_loadBlueprints');
sinon.spy(EnvironmentBuilder.prototype, '_lookupBlueprints');
createSpy = sinon.spy(EnvironmentBuilder, 'create');
// @ts-expect-error
_lookupJHipsterSpy = sinon.spy(EnvironmentBuilder.prototype, '_lookupJHipster');
// @ts-expect-error
_loadBlueprintsSpy = sinon.spy(EnvironmentBuilder.prototype, '_loadBlueprints');
// @ts-expect-error
_lookupBlueprintsSpy = sinon.spy(EnvironmentBuilder.prototype, '_lookupBlueprints');
// Use localOnly to lookup at local node_modules only to improve lookup speed.
EnvironmentBuilder.createDefaultBuilder();
await EnvironmentBuilder.createDefaultBuilder();
});
after(() => {
EnvironmentBuilder.create.restore();
EnvironmentBuilder.prototype._lookupJHipster.restore();
EnvironmentBuilder.prototype._loadBlueprints.restore();
EnvironmentBuilder.prototype._lookupBlueprints.restore();
afterEach(() => {
createSpy.restore();
_lookupJHipsterSpy.restore();
_loadBlueprintsSpy.restore();
_lookupBlueprintsSpy.restore();
});
it('should call create, _lookupJHipster, _loadBlueprints and _lookupBlueprints', () => {
expect(EnvironmentBuilder.create.callCount).to.be.equal(1);
expect(EnvironmentBuilder.prototype._lookupJHipster.callCount).to.be.equal(1);
expect(EnvironmentBuilder.prototype._loadBlueprints.callCount).to.be.equal(1);
expect(EnvironmentBuilder.prototype._lookupBlueprints.callCount).to.be.equal(1);
expect(createSpy.callCount).to.be.equal(1);
expect(_lookupJHipsterSpy.callCount).to.be.equal(1);
expect(_loadBlueprintsSpy.callCount).to.be.equal(1);
expect(_lookupBlueprintsSpy.callCount).to.be.equal(1);
});
});

describe('_loadBlueprints', () => {
let envBuilder;
beforeEach(() => {
// @ts-expect-error
envBuilder = EnvironmentBuilder.create([])._loadBlueprints();
});
describe('when there is no .yo-rc.json', () => {
Expand Down Expand Up @@ -311,6 +320,7 @@ describe('cli - EnvironmentBuilder', () => {
let envBuilder;
beforeEach(async () => {
// Use localOnly to lookup at local node_modules only to improve lookup speed.
// @ts-expect-error
envBuilder = await EnvironmentBuilder.create()._loadBlueprints()._lookupBlueprints({ localOnly: true });
await envBuilder._loadSharedOptions();
});
Expand Down
5 changes: 2 additions & 3 deletions generators/base-application/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { snakeCase } from 'lodash-es';

import EnvironmentBuilder from '../../cli/environment-builder.mjs';
import Generator from './index.js';
import type { BaseApplication } from '../base-application/types.js';
import { defaultHelpers as helpers } from '../../testing/index.js';
import { shouldSupportFeatures } from '../../test/support/tests.js';

Expand Down Expand Up @@ -76,7 +75,7 @@ describe(`generator - ${generator}`, () => {
const writingEntities = esmocha.fn();
const postWritingEntities = esmocha.fn();

class CustomGenerator extends Generator<BaseApplication> {
class CustomGenerator extends Generator {
async beforeQueue() {
await this.dependsOnJHipster('bootstrap-application');
}
Expand Down Expand Up @@ -318,7 +317,7 @@ describe(`generator - ${generator}`, () => {
const writingEntities = esmocha.fn();
const postWritingEntities = esmocha.fn();

class CustomGenerator extends Generator<BaseApplication> {
class CustomGenerator extends Generator {
async beforeQueue() {
await this.dependsOnJHipster('bootstrap-application');
}
Expand Down
2 changes: 1 addition & 1 deletion generators/client/generator-needles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const mockBlueprintSubGen: any = class extends ClientGenerator {
get [ClientGenerator.POST_WRITING]() {
return this.asPostWritingTaskGroup({
webpackPhase({ source }) {
source.addWebpackConfig({ config: '{devServer:{}}' });
source!.addWebpackConfig!({ config: '{devServer:{}}' });
},
});
}
Expand Down
4 changes: 2 additions & 2 deletions generators/client/needle-client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const mockBlueprintSubGen: any = class extends ClientGenerator {
return this.asPostWritingTaskGroup({
// @ts-ignore
async additionalResource({ source }) {
source.addExternalResourceToRoot({
source!.addExternalResourceToRoot!({
resource: '<link rel="stylesheet" href="content/css/my.css">',
comment: 'Comment added by JHipster API',
});
Expand All @@ -38,7 +38,7 @@ describe('needle API Client: JHipster client generator with blueprint', () => {
.withOptions({
blueprint: 'myblueprint',
})
.withGenerators([[mockBlueprintSubGen, 'jhipster-myblueprint:client']]);
.withGenerators([[mockBlueprintSubGen, { namespace: 'jhipster-myblueprint:client' }]]);
});

it('Assert index.html contain the comment and the resource added', () => {
Expand Down
4 changes: 2 additions & 2 deletions generators/entity/database-changelog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('generator - entity database changelogs', () => {
before(async () => {
await helpers
.run(getGenerator('entity'))
.withGenerators([[MockedLanguagesGenerator, 'jhipster:languages']])
.withGenerators([[MockedLanguagesGenerator, { namespace: 'jhipster:languages' }]])
.withJHipsterConfig({ databaseType: 'cassandra' }, [entityFoo])
.withArguments(['Foo'])
.withOptions({ regenerate: true, force: true, ignoreNeedlesError: true });
Expand All @@ -35,7 +35,7 @@ describe('generator - entity database changelogs', () => {
before(async () => {
await helpers
.run(getGenerator('entity'))
.withGenerators([[MockedLanguagesGenerator, 'jhipster:languages']])
.withGenerators([[MockedLanguagesGenerator, { namespace: 'jhipster:languages' }]])
.withJHipsterConfig({ applicationType: 'gateway' }, [
{ ...entityFoo, microservicePath: 'microservice1', microserviceName: 'microservice1' },
])
Expand Down
4 changes: 2 additions & 2 deletions generators/entity/single-entity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('generator - entity --single-entity', () => {
before(async () => {
await helpers
.runJHipster(GENERATOR_ENTITY)
.withGenerators([[MockedLanguagesGenerator, 'jhipster:languages']])
.withGenerators([[MockedLanguagesGenerator, { namespace: 'jhipster:languages' }]])
.withJHipsterConfig({}, [entityFoo, entityBar])
.withArguments(['Foo'])
.withOptions({ ignoreNeedlesError: true, regenerate: true, force: true, singleEntity: true })
Expand Down Expand Up @@ -56,7 +56,7 @@ describe('generator - entity --single-entity', () => {
before(async () => {
runResult = await helpers
.runJHipster(GENERATOR_ENTITY)
.withGenerators([[MockedLanguagesGenerator, 'jhipster:languages']])
.withGenerators([[MockedLanguagesGenerator, { namespace: 'jhipster:languages' }]])
.withJHipsterConfig({ databaseType: 'cassandra' }, [entityFoo, entityBar])
.withArguments(['Foo'])
.withOptions({ ignoreNeedlesError: true, regenerate: true, force: true, singleEntity: true });
Expand Down
2 changes: 1 addition & 1 deletion generators/gradle/needles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('needle API server gradle: JHipster server generator with blueprint', (
clientFramework: 'no',
buildTool: 'gradle',
})
.withGenerators([[mockBlueprintSubGen, 'jhipster-myblueprint:server']]);
.withGenerators([[mockBlueprintSubGen, { namespace: 'jhipster-myblueprint:server' }]]);
});

it('Assert gradle.properties has the property added', () => {
Expand Down
14 changes: 7 additions & 7 deletions generators/java/support/checks/check-java.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { after, before, it, describe, expect, resetAllMocks, esmocha } from 'esmocha';
import { ExecaSyncReturnValue } from 'execa';
import { SyncResult } from 'execa';
import quibble from 'quibble';

const execa = { execa: esmocha.fn(), execaSync: esmocha.fn(), execaCommandSync: esmocha.fn(), execaCommand: esmocha.fn() };

const baseResult: ExecaSyncReturnValue<string> = {
const baseResult: SyncResult = {
cwd: '',
command: 'java',
escapedCommand: 'java',
exitCode: 0,
stdout: '',
stderr: '',
failed: false,
timedOut: false,
killed: false,
};
} as any;

describe('generator - server - checkJava', () => {
before(async () => {
Expand All @@ -34,7 +34,7 @@ describe('generator - server - checkJava', () => {
before(async () => {
execa.execaCommandSync.mockReturnValue({ ...baseResult, stderr } as any);
const { default: checkJava } = await import('./check-java.js');
result = checkJava();
result = checkJava([]);
});

it('should return info and javaVersion', async () => {
Expand All @@ -53,7 +53,7 @@ describe('generator - server - checkJava', () => {
before(async () => {
execa.execaCommandSync.mockReturnValue({ ...baseResult, exitCode, stderr } as any);
const { default: checkJava } = await import('./check-java.js');
result = checkJava();
result = checkJava([]);
});

it('should return error', async () => {
Expand All @@ -69,7 +69,7 @@ describe('generator - server - checkJava', () => {
throw new Error('foo');
});
const { default: checkJava } = await import('./check-java.js');
result = checkJava();
result = checkJava([]);
});

it('should return error', async () => {
Expand Down
2 changes: 1 addition & 1 deletion generators/java/support/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const formatDocAsJavaDoc = (text: string, indentSize = 0): string => {
return rows.join('\n');
};

export const formatDocAsApiDescription = (text: string): string => {
export const formatDocAsApiDescription = (text?: string): string | undefined => {
if (!text) {
return text;
}
Expand Down
2 changes: 1 addition & 1 deletion generators/liquibase/needles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('generator - liquibase - needles', () => {
.withOptions({
skipPriorities: ['writing'],
})
.withGenerators([[mockBlueprintSubGen, 'jhipster-myblueprint:liquibase']]);
.withGenerators([[mockBlueprintSubGen, { namespace: 'jhipster-myblueprint:liquibase' }]]);
});

it('Assert changelog is added to master.xml', () => {
Expand Down
2 changes: 1 addition & 1 deletion generators/maven/generator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ describe(`generator - ${generator}`, () => {
});
}
},
'jhipster-blueprint:maven',
{ namespace: 'jhipster-blueprint:maven' },
],
]);
});
Expand Down
2 changes: 1 addition & 1 deletion generators/maven/needles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class mockBlueprintSubGen extends BaseApplicationGenerator {
get [BaseApplicationGenerator.POST_WRITING]() {
return this.asPostWritingTaskGroup({
mavenStep({ source }) {
const inProfile = this.options.profile;
const inProfile = (this.options as any).profile;
function asItemOrArray<T>(item: T): T | T[] {
return inProfile ? [item] : item;
}
Expand Down
2 changes: 1 addition & 1 deletion generators/server/options/database-migration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { DATABASE_MIGRATION as optionName } from './index.js';
import optionDefinition from './database-migration.js';

describe(`generators - server - jdl - ${optionName}`, () => {
optionDefinition.knownChoices.forEach(optionValue => {
optionDefinition.knownChoices!.forEach(optionValue => {
describe(`with ${optionValue} value`, () => {
let state: ImportState;

Expand Down
2 changes: 1 addition & 1 deletion generators/server/options/message-broker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { MESSAGE_BROKER } from './index.js';
import optionDefinition from './message-broker.js';

describe('generators - server - jdl - messageBroker', () => {
optionDefinition.knownChoices.forEach(optionValue => {
optionDefinition.knownChoices!.forEach(optionValue => {
describe(`with ${optionValue} value`, () => {
let state: ImportState;

Expand Down
8 changes: 4 additions & 4 deletions generators/server/support/needles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
* limitations under the License.
*/
import { before, it, describe, expect } from 'esmocha';
import { defaultHelpers as helpers } from '../../../testing/index.js';
import { defaultHelpers as helpers, runResult } from '../../../testing/index.js';
import { GENERATOR_SPRING_BOOT } from '../../generator-list.js';
import { insertContentIntoApplicationProperties } from './needles.js';
import type { SpringBootApplication } from '../types.js';

describe('generator - server - support - needles', () => {
describe('generated project', () => {
let runResult;
before(async () => {
runResult = await helpers
await helpers
.runJHipster(GENERATOR_SPRING_BOOT)
.withMockedGenerators(['jhipster:common', 'jhipster:languages', 'jhipster:liquibase']);
});
Expand All @@ -36,7 +36,7 @@ describe('generator - server - support - needles', () => {

describe('insertContentIntoApplicationProperties needle', () => {
it('with a non existing needle', () => {
const application = runResult.generator.sharedData.getApplication();
const application: SpringBootApplication = runResult.generator.sharedData.getApplication();
expect(() => insertContentIntoApplicationProperties.call(runResult.generator, application, { foo: 'foo' })).toThrow(
/Missing required jhipster-needle application-properties-foo not found at/,
);
Expand Down
6 changes: 5 additions & 1 deletion generators/upgrade/upgrade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ describe('generator - upgrade', function () {
baseName: 'upgradeTest',
})
.withOptions({ useVersionPlaceholders: false });
await runResult.create(getGenerator(GENERATOR_UPGRADE)).withSpawnMock().withOptions({ useVersionPlaceholders: false }).run();
await runResult
.create(getGenerator(GENERATOR_UPGRADE))
.withSpawnMock()
.withOptions({ useVersionPlaceholders: false } as any)
.run();
});

it('generated git commits to match snapshot', () => {
Expand Down
7 changes: 6 additions & 1 deletion testing/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ import BaseGenerator from '../generators/base/index.js';
import type { JHipsterGeneratorOptions } from '../generators/base/api.js';
import { getPackageRoot, isDistFolder } from '../lib/index.js';
import type { JSONEntity } from '../jdl/converters/types.js';
import CoreGenerator from '../generators/base-core/generator.js';

type BaseEntity = { name: string } & JSONEntity;
type GeneratorTestType = YeomanGenerator<JHipsterGeneratorOptions>;
type GeneratorTestOptions = JHipsterGeneratorOptions;

type JHipsterRunResult<GeneratorType extends YeomanGenerator = YeomanGenerator> = RunResult<GeneratorType> & {
type JHipsterRunResult<GeneratorType extends CoreGenerator = CoreGenerator> = RunResult<GeneratorType> & {
/**
* First argument of mocked source calls.
*/
Expand Down Expand Up @@ -130,6 +131,10 @@ class JHipsterRunContext extends RunContext<GeneratorTestType> {
private commonWorkspacesConfig!: Record<string, unknown>;
private generateApplicationsSet = false;

withOptions(options: Partial<Omit<JHipsterGeneratorOptions, 'env' | 'resolved' | 'namespace'> & Record<string, any>>): this {
return super.withOptions(options as any);
}

withJHipsterConfig(configuration?: Record<string, unknown>, entities?: BaseEntity[]): this {
return this.withFiles(
createFiles('', { baseName: 'jhipster', creationTimestamp: parseCreationTimestamp('2020-01-01'), ...configuration }, entities),
Expand Down
Loading
Loading