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 sample generation for several mgmt plane RPs #1289

Merged
merged 19 commits into from
Feb 17, 2022
Merged
Show file tree
Hide file tree
Changes from 16 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
10 changes: 10 additions & 0 deletions src/generators/modelsGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ export function generateModels(clientDetails: ClientDetails, project: Project) {
writeOperationModels(clientDetails, modelsIndexFile);
writeClientModels(clientDetails, modelsIndexFile);
modelsIndexFile.fixUnusedIdentifiers();
const allTypes = modelsIndexFile.getTypeAliases();
clientDetails.allTypes = allTypes.filter(item => {
return item.isExported()
}).map(item => {
return item.getName()
});
}

const writeClientModels = (
Expand Down Expand Up @@ -771,6 +777,10 @@ function getPropertyTypeName(
ignoreNullableOnOptional: boolean
) {
if (property.isConstant) {
if (property.type === SchemaType.Number
|| property.type === SchemaType.Boolean) {
return `${property.defaultValue}`;
}
return `"${getStringForValue(
property.defaultValue,
property.type,
Expand Down
6 changes: 4 additions & 2 deletions src/generators/static/samples.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
* x-ms-original-file: {{originalFileLocation}}
*/
import {
{{#if hasBody }}
{{bodySchemaName}},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we don't use these two columns does that mean we could delete them in model and transform.ts?

{{#if importedTypes.length }}
{{#each importedTypes}}
{{this}},
{{/each}}
{{/if}}
{{clientClassName}},
} from "{{clientPackageName}}";
Expand Down
1 change: 1 addition & 0 deletions src/models/clientDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ export interface ClientDetails {
options: ClientOptions;
endpoint: EndpointDetails;
samples?: SampleDetails[];
allTypes: string[];
}
4 changes: 2 additions & 2 deletions src/models/modelDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export type PolymorphicObjectDetails = BasicObjectDetails & {
export interface PropertyDetails {
name: string;
description?: string;
defaultValue?: string;
defaultValue?: string | number | boolean;
serializedName: string;
type: string;
required: boolean;
Expand All @@ -83,7 +83,7 @@ export interface TypeDetails {
typeName: string;
isConstant?: boolean;
nullable?: boolean;
defaultValue?: string;
defaultValue?: string | number | boolean;
kind: PropertyKind;
usedModels: string[];
}
Expand Down
2 changes: 2 additions & 0 deletions src/models/sampleDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ export interface SampleDetails {
isTopLevel: boolean,
isPaging: boolean,
originalFileLocation?: string
isAnyTypeBody?: boolean,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't notice any usage for this column - isAnyTypeBody, does that mean we could delete it?

importedTypes?: string[]
}
42 changes: 30 additions & 12 deletions src/transforms/samplesTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { calculateMethodName } from "../generators/utils/operationsUtils";
import { camelCase } from "@azure-tools/codegen";
import { OperationGroupDetails } from "../models/operationDetails";
import { getPublicMethodName } from '../generators/utils/pagingOperations';
import { BodiedNode } from "ts-morph";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No usage delete this import?

import { getTypeForSchema } from "../utils/schemaHelpers";

export async function transformSamples(
codeModel: CodeModel,
Expand Down Expand Up @@ -69,20 +71,22 @@ export async function getAllExamples(codeModel: TestCodeModel, clientDetails: Cl
example.operation.language
).description,
operationName: methodName,
operationGroupName: normalizeName(opGroupName, NameType.Property),
operationGroupName: normalizeName(opGroupName, NameType.Property, true),
clientClassName: clientName,
clientPackageName: packageDetails.name,
clientParameterNames: "",
methodParameterNames: "",
bodySchemaName: "",
isAnyTypeBody: false,
hasBody: false,
hasOptional: false,
sampleFunctionName: camelCase(example.name.replace(/\//g, " Or ").replace(/,|\.|\(|\)/g, " ").replace('\'s ', ' ')),
methodParamAssignments: [],
clientParamAssignments: [],
isTopLevel: ogDetails.isTopLevel,
isPaging: opDetails.pagination !== undefined,
originalFileLocation: example.originalFile
originalFileLocation: example.originalFile,
importedTypes: []
};
const clientParameterNames = ["credential"];
const requiredParams = clientDetails.parameters.filter(
Expand All @@ -100,7 +104,8 @@ export async function getAllExamples(codeModel: TestCodeModel, clientDetails: Cl
}
const parameterName = normalizeName(
getLanguageMetadata(clientParameter.exampleValue.language).name,
NameType.Parameter
NameType.Parameter,
true
);
const paramAssignment =
`const ${parameterName} = ` +
Expand All @@ -117,22 +122,31 @@ export async function getAllExamples(codeModel: TestCodeModel, clientDetails: Cl
sample.clientParameterNames = clientParameterNames.join(", ");
}
const methodParameterNames = [];
const optionalParams = [];
const optionalParams: [string, string][]= [];
for (const methodParameter of example.methodParameters) {
if (
methodParameter.exampleValue.schema.type === SchemaType.Constant
) {
continue;
}
const parameterName = getLanguageMetadata(
methodParameter.exampleValue.language
).name;
const parameterName = normalizeName(
getLanguageMetadata(methodParameter.exampleValue.language).name,
NameType.Parameter,
true
);
const parameterTypeDetails = getTypeForSchema(
methodParameter.exampleValue.schema
);
const parameterTypeName = parameterTypeDetails.typeName;
let paramAssignment = "";
if (methodParameter.parameter.protocol?.http?.["in"] === "body") {
sample.hasBody = true;
sample.bodySchemaName = getLanguageMetadata(
methodParameter.exampleValue.schema.language
).name;
sample.bodySchemaName = parameterTypeName;
sample.importedTypes?.push(parameterTypeName);
if (methodParameter.exampleValue.schema.type === SchemaType.AnyObject || methodParameter.exampleValue.schema.type === SchemaType.Any) {
sample.bodySchemaName = "Record<string, unknown>"
sample.isAnyTypeBody = true;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We re-correct the value of bodySchemaName & isAnyTypeBody but we didn't put the latest into importedTypes list or any usage directly, do we need to refine this?

}
paramAssignment =
`const ${parameterName}: ${sample.bodySchemaName} = ` +
getParameterAssignment(methodParameter.exampleValue);
Expand All @@ -142,7 +156,7 @@ export async function getAllExamples(codeModel: TestCodeModel, clientDetails: Cl
getParameterAssignment(methodParameter.exampleValue);
}
if (!methodParameter.parameter.required) {
optionalParams.push(parameterName);
optionalParams.push([ parameterName, parameterTypeName ]);
} else {
methodParameterNames.push(parameterName);
}
Expand All @@ -151,7 +165,10 @@ export async function getAllExamples(codeModel: TestCodeModel, clientDetails: Cl
if (optionalParams.length > 0) {
const optionAssignment = `const options = {${optionalParams
.map(item => {
return item + ": " + item;
if (sample.importedTypes?.indexOf(item[1]) === -1 && clientDetails.allTypes.indexOf(item[1]) > -1 ) {
sample.importedTypes?.push(item[1]);
}
return item[0] + ": " + item[0] + " as " + item[1];
})
.join(", ")}}`;
sample.methodParamAssignments.push(optionAssignment);
Expand Down Expand Up @@ -193,6 +210,7 @@ function getParameterAssignment(exampleValue: ExampleValue) {
case SchemaType.Object:
case SchemaType.Any:
case SchemaType.Dictionary:
case SchemaType.AnyObject:
retValue = `{}`;
break;
case SchemaType.Array:
Expand Down
3 changes: 2 additions & 1 deletion src/transforms/transforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ export async function transformCodeModel(
operationGroups,
parameters,
options,
endpoint: baseUrl
endpoint: baseUrl,
allTypes: []
};
}

Expand Down
5 changes: 2 additions & 3 deletions src/typescriptGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ export async function generateTypeScriptLibrary(

const clientDetails = await transformCodeModel(codeModel);
conflictResolver(clientDetails);

generateModels(clientDetails, project);
if (generateSample) {
clientDetails.samples = await transformSamples(codeModel, clientDetails);
}


// Skip metadata generation if `generate-metadata` is explicitly false
generatePackageJson(project, clientDetails);
generateLicenseFile(project);
Expand All @@ -87,7 +87,6 @@ export async function generateTypeScriptLibrary(
generateApiExtractorConfig(project);

generateClient(clientDetails, project);
generateModels(clientDetails, project);

generateMappers(clientDetails, project);
generateOperations(clientDetails, project);
Expand Down
4 changes: 2 additions & 2 deletions src/utils/schemaHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function getTypeForSchema(
): TypeDetails {
let typeName: string = "";
let usedModels: string[] = [];
let defaultValue: string = "";
let defaultValue = undefined;
let kind: PropertyKind = PropertyKind.Primitive;
switch (schema.type) {
case SchemaType.Any:
Expand Down Expand Up @@ -194,7 +194,7 @@ export function getTypeForSchema(
usedModels,
isConstant: schema.type === SchemaType.Constant,
nullable: isNullable,
...(defaultValue && { defaultValue })
defaultValue
};
}

Expand Down
2 changes: 1 addition & 1 deletion test/integration/bodyComplex.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert } from "chai";
import * as moment from "moment";
import { BodyComplexWithTracing } from "./generated/bodyComplexWithTracing/src";
import { BodyComplexWithTracing, DotFishUnion } from "./generated/bodyComplexWithTracing/src";
import {
BodyComplexClient,
Sawshark,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import * as coreClient from "@azure/core-client";

export interface ErrorModel {
status?: number;
constantId: "1";
constantId: 1;
message?: string;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface Product {
/** The product documentation. */
constChild: ConstantProduct;
/** Constant int */
constInt: "undefined";
constInt: 0;
/** Constant string */
constString: "constant";
/** Constant string as Enum */
Expand Down
2 changes: 1 addition & 1 deletion test/integration/validation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const constantBody: Product = {
constProperty: "constant",
constProperty2: "constant2"
},
constInt: "undefined",
constInt: 0,
constString: "constant"
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async function createNewCloudServiceWithMultipleRoles() {
upgradeMode: "Auto"
}
};
const options = { parameters: parameters };
const options = { parameters: parameters as CloudService };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.cloudServices.beginCreateOrUpdateAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async function createNewCloudServiceWithSingleRole() {
upgradeMode: "Auto"
}
};
const options = { parameters: parameters };
const options = { parameters: parameters as CloudService };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.cloudServices.beginCreateOrUpdateAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async function createNewCloudServiceWithSingleRoleAndCertificateFromKeyVault() {
upgradeMode: "Auto"
}
};
const options = { parameters: parameters };
const options = { parameters: parameters as CloudService };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.cloudServices.beginCreateOrUpdateAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ async function createNewCloudServiceWithSingleRoleAndRdpExtension() {
upgradeMode: "Auto"
}
};
const options = { parameters: parameters };
const options = { parameters: parameters as CloudService };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.cloudServices.beginCreateOrUpdateAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async function deleteCloudServiceRoleInstances() {
const parameters: RoleInstances = {
roleInstances: ["ContosoFrontend_IN_0", "ContosoBackend_IN_1"]
};
const options = { parameters: parameters };
const options = { parameters: parameters as RoleInstances };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.cloudServices.beginDeleteInstancesAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function forceDeleteAVM() {
const resourceGroupName = "myResourceGroup";
const vmName = "myVM";
const forceDeletion = true;
const options = { forceDeletion: forceDeletion };
const options = { forceDeletion: forceDeletion as boolean };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachines.beginDeleteAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function forceDeleteAVMScaleSet() {
const resourceGroupName = "myResourceGroup";
const vmScaleSetName = "myvmScaleSet";
const forceDeletion = true;
const options = { forceDeletion: forceDeletion };
const options = { forceDeletion: forceDeletion as boolean };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachineScaleSets.beginDeleteAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function forceDeleteAVirtualMachineFromAVMScaleSet() {
const vmScaleSetName = "myvmScaleSet";
const instanceId = "0";
const forceDeletion = true;
const options = { forceDeletion: forceDeletion };
const options = { forceDeletion: forceDeletion as boolean };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.virtualMachineScaleSetVMs.beginDeleteAndWait(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
* @summary Retrieves information about a gallery Application Version.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-07-01/examples/gallery/GetAGalleryApplicationVersionWithReplicationStatus.json
*/
import { ComputeManagementClient } from "@msinternal/compute-resource-manager";
import {
ReplicationStatusTypes,
ComputeManagementClient
} from "@msinternal/compute-resource-manager";
import { DefaultAzureCredential } from "@azure/identity";

async function getAGalleryApplicationVersionWithReplicationStatus() {
Expand All @@ -24,7 +27,7 @@ async function getAGalleryApplicationVersionWithReplicationStatus() {
const galleryApplicationName = "myGalleryApplicationName";
const galleryApplicationVersionName = "1.0.0";
const expand = "ReplicationStatus";
const options = { expand: expand };
const options = { expand: expand as ReplicationStatusTypes };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.galleryApplicationVersions.get(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
* @summary Retrieves information about a gallery image version.
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-07-01/examples/gallery/GetAGalleryImageVersionWithReplicationStatus.json
*/
import { ComputeManagementClient } from "@msinternal/compute-resource-manager";
import {
ReplicationStatusTypes,
ComputeManagementClient
} from "@msinternal/compute-resource-manager";
import { DefaultAzureCredential } from "@azure/identity";

async function getAGalleryImageVersionWithReplicationStatus() {
Expand All @@ -24,7 +27,7 @@ async function getAGalleryImageVersionWithReplicationStatus() {
const galleryImageName = "myGalleryImageName";
const galleryImageVersionName = "1.0.0";
const expand = "ReplicationStatus";
const options = { expand: expand };
const options = { expand: expand as ReplicationStatusTypes };
const credential = new DefaultAzureCredential();
const client = new ComputeManagementClient(credential, subscriptionId);
const result = await client.galleryImageVersions.get(
Expand Down
Loading