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

Fix e2e tests for pluralization #7590

Merged
merged 3 commits into from
Jun 24, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ const path = require('path');
const { RelationalDBSchemaTransformer } = require('graphql-relational-schema-transformer');
const { RelationalDBTemplateGenerator, AuroraServerlessMySQLDatabaseReader } = require('graphql-relational-schema-transformer');
const { mergeTypeDefs } = require('@graphql-tools/merge');
const { ResourceDoesNotExistError, exitOnNextTick } = require('amplify-cli-core');

const { FeatureFlags, ResourceDoesNotExistError, exitOnNextTick } = require('amplify-cli-core');
const subcommand = 'add-graphql-datasource';
const categories = 'categories';
const category = 'api';
Expand Down Expand Up @@ -143,7 +142,11 @@ module.exports = {
context[rdsResourceName] = resourceName;
context[rdsDatasource] = datasource;
let template = templateGenerator.createTemplate(context);
template = templateGenerator.addRelationalResolvers(template, resolversDir);
template = templateGenerator.addRelationalResolvers(
template,
resolversDir,
FeatureFlags.getBoolean('graphqltransformer.improvePluralization'),
);
const cfn = templateGenerator.printCloudformationTemplate(template);

/**
Expand Down
6 changes: 6 additions & 0 deletions packages/amplify-cli-core/src/feature-flags/featureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,12 @@ export class FeatureFlags {
defaultValueForExistingProjects: false,
defaultValueForNewProjects: true,
},
{
name: 'improvePluralization',
type: 'boolean',
defaultValueForExistingProjects: false,
defaultValueForNewProjects: true,
},
{
name: 'validateTypeNameReservedWords',
type: 'boolean',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
type Comment @model @key(name: "byTodos", fields: ["todoID"]) {
type Comment @model @key(name: "byTask", fields: ["todoID"]) {
id: ID!
todoID: ID!
}

type Todos @model {
type Task @model {
id: ID!
name: String!
description: String
addfield2: String
Comments: [Comment] @connection(keyName: "byTodos", fields: ["id"])
Comments: [Comment] @connection(keyName: "byTask", fields: ["id"])
}
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ export const expected_result_query6 = {

export const query7 = `
## 7. See all employees hired recently:
#Having '@key(name: "newHire", fields: ["newHire", "id"])' on the 'Employee' model allows one to query by whether an employee has been hired recently.
#Having '@key(name: "newHire", fields: ["newHire", "id"])' on the 'Employee' model allows one to query by whether an employee has been hired recently.

query employeesNewHire {
employeesNewHire(newHire: "true") {
Expand Down Expand Up @@ -685,8 +685,8 @@ export const query16 = `
## 16. Get total product inventory:
#How this would be done depends on the use case. If one just wants a list of all inventories in all warehouses, one could just run a list inventories on the Inventory model:

query listInventorys {
listInventorys {
query listInventories {
listInventories {
items {
productID
warehouseID
Expand All @@ -696,7 +696,7 @@ query listInventorys {
}`;
export const expected_result_query16 = {
data: {
listInventorys: {
listInventories: {
items: [
{
productID: 'yeezyboost',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ import { SearchableModelTransformer } from '../';
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { anything, countResources, expect as cdkExpect, haveResource } from '@aws-cdk/assert';
import { parse } from 'graphql';
const featureFlags = {
getBoolean: jest.fn().mockImplementation((name, defaultValue) => {
if (name === 'improvePluralization') {
return true;
}
return;
}),
getNumber: jest.fn(),
getObject: jest.fn(),
getString: jest.fn(),
};

test('Test SearchableModelTransformer validation happy case', () => {
const validSchema = `
Expand All @@ -15,6 +26,7 @@ test('Test SearchableModelTransformer validation happy case', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand All @@ -33,6 +45,7 @@ test('Test SearchableModelTransformer vtl', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});

const out = transformer.transform(validSchema);
Expand All @@ -50,6 +63,7 @@ test('Test SearchableModelTransformer with query overrides', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand All @@ -67,6 +81,7 @@ test('Test SearchableModelTransformer with only create mutations', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand All @@ -90,6 +105,7 @@ test('Test SearchableModelTransformer with multiple model searchable directives'
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand All @@ -108,6 +124,7 @@ test('Test SearchableModelTransformer with sort fields', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand Down Expand Up @@ -137,6 +154,7 @@ test('it generates expected resources', () => {
`;
const transformer = new GraphQLTransform({
transformers: [new ModelTransformer(), new SearchableModelTransformer()],
featureFlags,
});
const out = transformer.transform(validSchema);
expect(out).toBeDefined();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ export class SearchableModelTransformer extends TransformerPluginBase {
searchFieldNameOverride = directiveArguments.queries.search;
}
}
const fieldName = searchFieldNameOverride ? searchFieldNameOverride : graphqlName(`search${plurality(toUpper(definition.name.value))}`);
const fieldName = searchFieldNameOverride
? searchFieldNameOverride
: graphqlName(`search${plurality(toUpper(definition.name.value), ctx.featureFlags.getBoolean('improvePluralization'))}`);
this.searchableObjectTypeDefinitions.push({
node: definition,
fieldName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export interface GraphQLTransformOptions {
readonly authConfig?: AppSyncAuthConfiguration;
readonly buildParameters?: Record<string, any>;
readonly stacks?: Record<string, Template>;
readonly featuerFlags?: FeatureFlagProvider;
readonly featureFlags?: FeatureFlagProvider;
}
export type StackMapping = { [resourceId: string]: string };
export class GraphQLTransform {
Expand Down Expand Up @@ -110,7 +110,7 @@ export class GraphQLTransform {
this.seenTransformations = {};
const parsedDocument = parse(schema);
this.app = new App();
const context = new TransformerContext(this.app, parsedDocument, this.stackMappingOverrides, this.options.featuerFlags);
const context = new TransformerContext(this.app, parsedDocument, this.stackMappingOverrides, this.options.featureFlags);
const validDirectiveNameMap = this.transformers.reduce(
(acc: any, t: TransformerPluginProvider) => ({ ...acc, [t.directive.name.value]: true }),
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ export class TransformerContext implements TransformerContextProvider {
public readonly resourceHelper: TransformerResourceHelper;
public readonly featureFlags: FeatureFlagProvider;
public _api?: GraphQLAPIProvider;
constructor(app: App, public readonly inputDocument: DocumentNode, stackMapping: Record<string, string>, featuerFlags?: FeatureFlagProvider) {
constructor(
app: App,
public readonly inputDocument: DocumentNode,
stackMapping: Record<string, string>,
featureFlags?: FeatureFlagProvider,
) {
this.output = new TransformerOutput(inputDocument);
this.resolvers = new ResolverManager();
this.dataSources = new TransformerDataSourceManager();
this.providerRegistry = new TransformerContextProviderRegistry();
const stackManager = new StackManager(app, stackMapping);
this.stackManager = stackManager
const stackManager = new StackManager(app, stackMapping);
this.stackManager = stackManager;
this.resourceHelper = new TransformerResourceHelper(stackManager);
this.featureFlags = featuerFlags ?? new NoopFeatureFlagProvider();
this.featureFlags = featureFlags ?? new NoopFeatureFlagProvider();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ async function _buildProject(opts: ProjectOptions<TransformerFactoryArgs>) {
authConfig: opts.authConfig,
buildParameters: opts.buildParameters,
stacks: opts.projectConfig.stacks || {},
featuerFlags: new AmplifyCLIFeatureFlagAdapter(),
featureFlags: new AmplifyCLIFeatureFlagAdapter(),
});
return transform.transform(userProjectConfig.schema.toString());
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ModelAuthTransformer } from 'graphql-auth-transformer';
import { ModelConnectionTransformer } from 'graphql-connection-transformer';
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { GraphQLTransform } from 'graphql-transformer-core';
import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core';
import { signUpAddToGroupAndGetJwtToken } from './utils/cognito-utils';
import { GraphQLClient } from './utils/graphql-client';
import { deploy, launchDDBLocal, logDebug, terminateDDB } from './utils/index';
Expand Down Expand Up @@ -112,6 +112,9 @@ type Stage @model @auth(rules: [{ allow: groups, groups: ["Admin"]}]) {
},
}),
],
featureFlags: {
getBoolean: name => (name === 'improvePluralization' ? true : false),
} as FeatureFlagProvider,
});

try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ModelAuthTransformer } from 'graphql-auth-transformer';
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { GraphQLTransform } from 'graphql-transformer-core';
import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core';
import { GraphQLClient } from './utils/graphql-client';
import { deploy, launchDDBLocal, terminateDDB, logDebug } from './utils/index';

Expand Down Expand Up @@ -59,6 +59,9 @@ beforeAll(async () => {
},
}),
],
featureFlags: {
getBoolean: name => (name === 'improvePluralization' ? true : false),
} as FeatureFlagProvider,
});
const out = await transformer.transform(validSchema);
let ddbClient;
Expand Down Expand Up @@ -179,27 +182,33 @@ test('Test createPost mutation', async () => {
});

test('Test query on get query with null field', async () => {
const createResponse = await GRAPHQL_CLIENT.query(`
const createResponse = await GRAPHQL_CLIENT.query(
`
mutation {
createPost(input: { title: "Cool Post" }) {
id
title
createdAt
updatedAt
}
}`, {});
}`,
{},
);
expect(createResponse.data.createPost.id).toBeDefined();
expect(createResponse.data.createPost.title).toEqual('Cool Post');
const postID = createResponse.data.createPost.id;
try {
const queryResponse = await GRAPHQL_CLIENT.query(`
const queryResponse = await GRAPHQL_CLIENT.query(
`
query {
getPost(id: "${postID}") {
id
title
episode
}
}`, {});
}`,
{},
);
expect(queryResponse.data.getPost.id).toEqual(postID);
expect(queryResponse.data.getPost.episode).toBeNull();
} catch (err) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { FunctionTransformer } from 'graphql-function-transformer';
import { GraphQLTransform } from 'graphql-transformer-core';
import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core';
import { GraphQLClient } from './utils/graphql-client';
import { deploy, logDebug } from './utils/index';

Expand Down Expand Up @@ -36,6 +36,9 @@ beforeAll(async () => {
try {
const transformer = new GraphQLTransform({
transformers: [new DynamoDBModelTransformer(), new FunctionTransformer()],
featureFlags: {
getBoolean: name => (name === 'improvePluralization' ? true : false),
} as FeatureFlagProvider,
});
const out = transformer.transform(validSchema);

Expand Down Expand Up @@ -78,7 +81,7 @@ test('Test simple echo function', async () => {
fieldName
}
}`,
{}
{},
);
logDebug(JSON.stringify(response, null, 4));
expect(response.data.echo.arguments.msg).toEqual('Hello');
Expand All @@ -97,7 +100,7 @@ test('Test simple duplicate function', async () => {
fieldName
}
}`,
{}
{},
);
logDebug(JSON.stringify(response, null, 4));
expect(response.data.duplicate.arguments.msg).toEqual('Hello');
Expand All @@ -110,7 +113,7 @@ test('Test pipeline of @function(s)', async () => {
`query {
pipeline(msg: "IGNORED")
}`,
{}
{},
);
logDebug(JSON.stringify(response, null, 4));
expect(response.data.pipeline).toEqual('Hello, world!');
Expand All @@ -127,7 +130,7 @@ test('Test pipelineReverse of @function(s)', async () => {
fieldName
}
}`,
{}
{},
);
logDebug(JSON.stringify(response, null, 4));
expect(response.data.pipelineReverse.arguments.msg).toEqual('Hello');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { deploy, launchDDBLocal, logDebug, terminateDDB } from './utils/index';

import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { GraphQLClient } from './utils/graphql-client';
import { GraphQLTransform } from 'graphql-transformer-core';
import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core';
import { KeyTransformer } from 'graphql-key-transformer';

jest.setTimeout(2000000);
Expand Down Expand Up @@ -62,6 +62,9 @@ beforeAll(async () => {
`;
const transformer = new GraphQLTransform({
transformers: [new DynamoDBModelTransformer(), new KeyTransformer()],
featureFlags: {
getBoolean: name => (name === 'improvePluralization' ? true : false),
} as FeatureFlagProvider,
});
const out = transformer.transform(validSchema);
let ddbClient;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ModelAuthTransformer } from 'graphql-auth-transformer';
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { KeyTransformer } from 'graphql-key-transformer';
import { GraphQLTransform } from 'graphql-transformer-core';
import { FeatureFlagProvider, GraphQLTransform } from 'graphql-transformer-core';
import { signUpAddToGroupAndGetJwtToken } from './utils/cognito-utils';
import { GraphQLClient } from './utils/graphql-client';
import { deploy, launchDDBLocal, logDebug, terminateDDB } from './utils/index';
Expand Down Expand Up @@ -67,6 +67,9 @@ beforeAll(async () => {
},
}),
],
featureFlags: {
getBoolean: name => (name === 'improvePluralization' ? true : false),
} as FeatureFlagProvider,
});

try {
Expand Down
Loading