Skip to content

Commit

Permalink
chore: add some additional test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
alharris-at committed Sep 19, 2023
1 parent e9f98db commit 1e421b6
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 20 deletions.
15 changes: 8 additions & 7 deletions packages/amplify-codegen-e2e-core/src/categories/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ export function generateTypes(cwd: string) : Promise<void> {
// CLI workflow to add codegen to Amplify project
export function addCodegen(cwd: string, settings: any = {}): Promise<void> {
return new Promise((resolve, reject) => {
const chain = spawn(getCLIPath(), ['codegen', 'add'], { cwd, stripColors: true });
const params = settings.params
? ['codegen', 'add', ...settings.params]
: ['codegen', 'add'];
const chain = spawn(getCLIPath(), params, { cwd, stripColors: true });
if (settings.isAPINotAdded) {
chain.wait("There are no GraphQL APIs available.");
chain.wait("Add by running $amplify api add");
Expand Down Expand Up @@ -197,10 +200,9 @@ export function generateModelIntrospection(cwd: string, settings: { outputDir?:
}

// CLI workflow to add codegen to non-Amplify JS project
export function addCodegenNonAmplifyJS(cwd: string, initialFailureMessage?: string): Promise<void> {
export function addCodegenNonAmplifyJS(cwd: string, params: Array<string>, initialFailureMessage?: string): Promise<void> {
return new Promise((resolve, reject) => {
const cmdOptions = ['codegen', 'add'];
const chain = spawn(getCLIPath(), cmdOptions, { cwd, stripColors: true });
const chain = spawn(getCLIPath(), ['codegen', 'add', ...params], { cwd, stripColors: true });

if (initialFailureMessage) {
chain.wait(initialFailureMessage)
Expand Down Expand Up @@ -229,10 +231,9 @@ export function addCodegenNonAmplifyJS(cwd: string, initialFailureMessage?: stri
});
}

export function addCodegenNonAmplifyTS(cwd: string, initialFailureMessage?: string): Promise<void> {
export function addCodegenNonAmplifyTS(cwd: string, params: Array<string>, initialFailureMessage?: string): Promise<void> {
return new Promise((resolve, reject) => {
const cmdOptions = ['codegen', 'add'];
const chain = spawn(getCLIPath(), cmdOptions, { cwd, stripColors: true });
const chain = spawn(getCLIPath(), ['codegen', 'add', ...params], { cwd, stripColors: true });

if (initialFailureMessage) {
chain.wait(initialFailureMessage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,12 @@ describe('codegen add tests - JS', () => {
it(`Adding codegen works as expected`, async () => {
await testAddCodegen(config, projectRoot, schema);
});

it(`supports add codegen with redundant region parameter`, async () => {
await testAddCodegen(config, projectRoot, schema, ['--region', 'us-fake-1']);
});

it(`supports add codegen with redundant apiId parameter`, async () => {
await testAddCodegen(config, projectRoot, schema, ['--apiId', 'mockApiId']);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ describe('codegen add tests - JS', () => {
});
});

it(`region is ignored if schema file is provided`, async () => {
await testAddCodegenUninitialized({
projectRoot,
config: javascriptConfig,
sdlFilename: 'schema.graphql',
expectedFilenames: ['mutations.js', 'queries.js', 'subscriptions.js'],
additionalParams: ['--region', 'us-fake-1'],
});
});

it(`json sdl file`, async () => {
await testAddCodegenUninitialized({
projectRoot,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import path from 'path';
import { isNotEmptyDir } from '../utils';
import { getGraphQLConfigFilePath, testSetupBeforeAddCodegen, testValidGraphQLConfig } from "./test-setup";

export async function testAddCodegen(config: AmplifyFrontendConfig, projectRoot: string, schema: string) {
export async function testAddCodegen(config: AmplifyFrontendConfig, projectRoot: string, schema: string, additionalParams?: Array<string>) {
// init project and add API category
await initProjectWithProfile(projectRoot, { ...config });
const projectName = createRandomName();
Expand All @@ -27,7 +27,7 @@ export async function testAddCodegen(config: AmplifyFrontendConfig, projectRoot:
const userSourceCodePath = testSetupBeforeAddCodegen(projectRoot, config);

// add codegen succeeds
await expect(addCodegen(projectRoot, { ...config })).resolves.not.toThrow();
await expect(addCodegen(projectRoot, { ...config, params: additionalParams ?? [] })).resolves.not.toThrow();

// pre-existing file should still exist
expect(existsSync(userSourceCodePath)).toBe(true);
Expand All @@ -45,12 +45,24 @@ export type TestAddCodegenUninitializedProps = {
dropAndRunCodegenStatements?: boolean;
dropAndRunCodegenTypes?: boolean;
initialFailureMessage?: string;
additionalParams?: Array<string>;
};

const assertTypeFileExists = (projectRoot: string): void => {
expect(existsSync(path.join(projectRoot, 'src', 'API.ts'))).toBe(true)
};

/**
* Ensure that all values provided in the expected set are present in the received set, allowing for additional values in received.
* @param expectedValues the expected values to check
* @param receivedValues the received values to check
*/
const ensureAllExpectedValuesAreReceived = <T>(expectedValues: Array<T>, receivedValues: Array<T>): void => {
const receivedValueSet = new Set(receivedValues);
console.log(`Comparing received values: ${JSON.stringify(receivedValues)} to expected values: ${JSON.stringify(expectedValues)}`);
expectedValues.forEach((expectedFilename) => expect(receivedValueSet.has(expectedFilename)).toBe(true));
};

export async function testAddCodegenUninitialized({
config,
projectRoot,
Expand All @@ -60,6 +72,7 @@ export async function testAddCodegenUninitialized({
dropAndRunCodegenStatements,
dropAndRunCodegenTypes,
initialFailureMessage,
additionalParams,
}: TestAddCodegenUninitializedProps) {
// Setup the non-amplify project with schema and pre-existing files
const userSourceCodePath = testSetupBeforeAddCodegen(projectRoot, config);
Expand All @@ -73,10 +86,10 @@ export async function testAddCodegenUninitialized({
// add codegen without init
switch (config.frontendType) {
case AmplifyFrontend.javascript:
await addCodegenNonAmplifyJS(projectRoot, initialFailureMessage);
await addCodegenNonAmplifyJS(projectRoot, additionalParams ?? [], initialFailureMessage);
break;
case AmplifyFrontend.typescript:
await addCodegenNonAmplifyTS(projectRoot, initialFailureMessage);
await addCodegenNonAmplifyTS(projectRoot, additionalParams ?? [], initialFailureMessage);
break;
default:
throw new Error(`Received unexpected frontendType ${config.frontendType}`);
Expand All @@ -90,9 +103,7 @@ export async function testAddCodegenUninitialized({
// pre-existing file should still exist
expect(existsSync(userSourceCodePath)).toBe(true);
// GraphQL statements are generated
const generatedStatementFiles = new Set(readdirSync(path.join(projectRoot, config.graphqlCodegenDir)));
console.log(`Comparing written files: ${JSON.stringify(Array.from(generatedStatementFiles))} to expected files: ${JSON.stringify(expectedFilenames)}`);
expectedFilenames.forEach((expectedFilename) => expect(generatedStatementFiles.has(expectedFilename)).toBe(true));
ensureAllExpectedValuesAreReceived(expectedFilenames, readdirSync(path.join(projectRoot, config.graphqlCodegenDir)))
// graphql configuration should be added
expect(existsSync(getGraphQLConfigFilePath(projectRoot))).toBe(true);
if (config.frontendType === AmplifyFrontend.typescript) {
Expand All @@ -111,9 +122,7 @@ export async function testAddCodegenUninitialized({
await generateStatementsAndTypes(projectRoot);

// GraphQL statements are regenerated
const regeneratedStatementFiles = new Set(readdirSync(path.join(projectRoot, config.graphqlCodegenDir)));
console.log(`Comparing written files: ${JSON.stringify(Array.from(regeneratedStatementFiles))} to expected files: ${JSON.stringify(expectedFilenames)}`);
expectedFilenames.forEach((expectedFilename) => expect(regeneratedStatementFiles.has(expectedFilename)).toBe(true));
ensureAllExpectedValuesAreReceived(expectedFilenames, readdirSync(path.join(projectRoot, config.graphqlCodegenDir)))

if (config.frontendType === AmplifyFrontend.typescript) {
assertTypeFileExists(projectRoot)
Expand All @@ -124,9 +133,7 @@ export async function testAddCodegenUninitialized({
await generateStatements(projectRoot);

// GraphQL statements are regenerated
const regeneratedStatementFiles = new Set(readdirSync(path.join(projectRoot, config.graphqlCodegenDir)));
console.log(`Comparing written files: ${JSON.stringify(Array.from(regeneratedStatementFiles))} to expected files: ${JSON.stringify(expectedFilenames)}`);
expectedFilenames.forEach((expectedFilename) => expect(regeneratedStatementFiles.has(expectedFilename)).toBe(true));
ensureAllExpectedValuesAreReceived(expectedFilenames, readdirSync(path.join(projectRoot, config.graphqlCodegenDir)))
}

if (dropAndRunCodegenTypes) {
Expand Down

0 comments on commit 1e421b6

Please sign in to comment.