зеркало из https://github.com/Azure/autorest.az.git
20210426 swagger scenario (#838)
* use oav 2.3.2 * use oav 2.3.2 * handle wrong test scenario * remove old scenario * gen rest call * fix rest call body * test output * clear code * rename swagger test filename * clean code * output * scenario steps file * use swagger_steps * fix spell issue * configurable use-swagger-scenario and location * spell fix
This commit is contained in:
Родитель
e57ffffae8
Коммит
a573427e94
|
@ -448,3 +448,18 @@ or configure in readme.az.md:
|
|||
gen-cmdlet-test: true
|
||||
~~~
|
||||
|
||||
## How to customize test location
|
||||
The default test location is 'westus', you can change it with below configuration:
|
||||
~~~
|
||||
az:
|
||||
...
|
||||
test-location: eastus
|
||||
~~~
|
||||
|
||||
## How to disable swagger test scenario
|
||||
The swagger test scenario can be disabled with below configuration:
|
||||
~~~
|
||||
az:
|
||||
...
|
||||
use-swagger-test-scenario: false
|
||||
~~~
|
||||
|
|
|
@ -77,8 +77,9 @@
|
|||
"mkdirp": "1.0.4",
|
||||
"node-yaml": "^3.2.0",
|
||||
"nunjucks": "^3.2.2",
|
||||
"oav": "2.2.0",
|
||||
"oav": "2.3.2",
|
||||
"prettier": "2.2.1",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"request": "^2.87.0",
|
||||
"request-promise-native": "1.0.8",
|
||||
"typescript": "^3.7.5"
|
||||
|
|
|
@ -33,6 +33,7 @@ cli:
|
|||
cli-flatten-all-overwrite-swagger: false
|
||||
|
||||
az:
|
||||
use-swagger-test-scenario: true
|
||||
preparers:
|
||||
virtualNetworks:
|
||||
abbr: vn
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*-------------------------------------------------------------------------------------------- */
|
||||
|
||||
import { Operation, OperationGroup, Parameter } from '@azure-tools/codemodel';
|
||||
import { Operation, OperationGroup, Parameter, CodeModel } from '@azure-tools/codemodel';
|
||||
import { CodeModelTypes, DataGraph, RenderInput } from '../../utils/models';
|
||||
import { ExtensionModel } from './Extension';
|
||||
import { CommandGroupModel } from './CommandGroup';
|
||||
|
|
|
@ -17,8 +17,9 @@ import {
|
|||
ObjectStatus,
|
||||
GroupTestScenario,
|
||||
LoadPreparesConfig,
|
||||
matchExample,
|
||||
} from '../renders/tests/ScenarioTool';
|
||||
import { TestStepExampleFileRestCall } from 'oav/dist/lib/testScenario/testResourceTypes';
|
||||
import { TestStepRestCall } from 'oav/dist/lib/testScenario/testResourceTypes';
|
||||
import { CodeModelCliImpl } from './CodeModelAzImpl';
|
||||
import { CommandModel } from './Command';
|
||||
import { CommandGroupModel } from './CommandGroup';
|
||||
|
@ -31,7 +32,7 @@ import { AzConfiguration, CodeGenConstants } from '../../utils/models';
|
|||
import { readFile } from '@azure-tools/async-io';
|
||||
import * as process from 'process';
|
||||
import * as path from 'path';
|
||||
import { Property } from '@azure-tools/codemodel';
|
||||
import { Operation, Property } from '@azure-tools/codemodel';
|
||||
|
||||
export class MethodParam {
|
||||
public value: any;
|
||||
|
@ -107,6 +108,7 @@ export class CommandExample {
|
|||
public ExampleObj: any;
|
||||
public commandStringItems: string[];
|
||||
public CommandString: string;
|
||||
public MethodObj: Operation;
|
||||
}
|
||||
|
||||
export interface ExampleModel {
|
||||
|
@ -115,7 +117,7 @@ export interface ExampleModel {
|
|||
GetSubscriptionKey(): string;
|
||||
GetPreparerEntities(): any[];
|
||||
GatherInternalResource();
|
||||
FindExampleWaitById(id: string, step?: TestStepExampleFileRestCall): string[][];
|
||||
FindExampleWaitById(id: string, step?: TestStepRestCall): string[][];
|
||||
GetExampleItems(example: CommandExample, isTest: boolean, commandParams: any): string[];
|
||||
GetExampleChecks(example: CommandExample): string[];
|
||||
|
||||
|
@ -124,10 +126,9 @@ export interface ExampleModel {
|
|||
FindExampleById(
|
||||
id: string,
|
||||
commandParams: any,
|
||||
examples: any[],
|
||||
minimum: boolean,
|
||||
step?: TestStepExampleFileRestCall,
|
||||
): string[][];
|
||||
step?: TestStepRestCall,
|
||||
): [string[], CommandExample];
|
||||
GenerateTestInit(): void;
|
||||
Example_TestScenario: any;
|
||||
Example_DefaultTestScenario: any;
|
||||
|
@ -231,13 +232,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
}
|
||||
|
||||
public GenerateTestInit(): void {
|
||||
if (this.GetResourcePool().hasTestResourceScenario) {
|
||||
this._testScenario = GroupTestScenario(
|
||||
this.GetResourcePool().generateTestScenario(),
|
||||
this.extensionHandler.Extension_NameUnderscored,
|
||||
);
|
||||
this._configuredScenario = true;
|
||||
} else if (this.baseHandler.codeModel['test-scenario']) {
|
||||
if (this.baseHandler.codeModel['test-scenario']) {
|
||||
this._testScenario = GroupTestScenario(
|
||||
this.baseHandler.codeModel['test-scenario'],
|
||||
this.extensionHandler.Extension_NameUnderscored,
|
||||
|
@ -248,7 +243,18 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
this._configuredScenario = false;
|
||||
}
|
||||
this.GatherInternalResource();
|
||||
this.GetAllExamples();
|
||||
const allExamples = this.GetAllExamples();
|
||||
if (this.GetResourcePool().hasTestResourceScenario) {
|
||||
this._testScenario = GroupTestScenario(
|
||||
this.GetResourcePool().generateTestScenario(
|
||||
allExamples,
|
||||
this.baseHandler.codeModel,
|
||||
),
|
||||
this.extensionHandler.Extension_NameUnderscored,
|
||||
true,
|
||||
);
|
||||
// this._configuredScenario = true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets method parameters dict
|
||||
|
@ -957,6 +963,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
'x-ms-long-running-operation'
|
||||
];
|
||||
example.ExampleObj = exampleObj;
|
||||
example.MethodObj = this.methodHandler.Method;
|
||||
if (this.methodHandler.Method_GetSplitOriginalOperation) {
|
||||
// filter example by name for generic createorupdate
|
||||
if (
|
||||
|
@ -988,7 +995,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
|
||||
public GetExampleChecks(example: CommandExample): string[] {
|
||||
const ret: string[] = [];
|
||||
if (!this.configHandler.GenChecks) return ret;
|
||||
if (!this.configHandler.GenChecks || isNullOrUndefined(example)) return ret;
|
||||
let resourceObjectName = undefined;
|
||||
for (const param of example.Parameters) {
|
||||
if (
|
||||
|
@ -1202,26 +1209,23 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
public FindExampleById(
|
||||
id: string,
|
||||
commandParams: any,
|
||||
examples: CommandExample[],
|
||||
minimum = false,
|
||||
step: TestStepExampleFileRestCall = undefined,
|
||||
): string[][] {
|
||||
const ret: string[][] = [];
|
||||
step: TestStepRestCall = undefined,
|
||||
): [string[], CommandExample] {
|
||||
let commandExample: CommandExample = undefined;
|
||||
let commandString: string[] = [];
|
||||
this.GetAllExamples(
|
||||
id,
|
||||
(example) => {
|
||||
examples.push(example);
|
||||
ret.push(this.GetExampleItems(example, true, commandParams, minimum));
|
||||
commandExample = example;
|
||||
commandString = this.GetExampleItems(example, true, commandParams, minimum);
|
||||
},
|
||||
step?.exampleTemplate,
|
||||
this.resourcePool.genExampleTemplate(step),
|
||||
);
|
||||
return ret;
|
||||
return [commandString, commandExample];
|
||||
}
|
||||
|
||||
public FindExampleWaitById(
|
||||
id: string,
|
||||
step: TestStepExampleFileRestCall = undefined,
|
||||
): string[][] {
|
||||
public FindExampleWaitById(id: string, step: TestStepRestCall = undefined): string[][] {
|
||||
const ret: string[][] = [];
|
||||
this.GetAllExamples(
|
||||
id,
|
||||
|
@ -1229,7 +1233,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
const waitCmd = this.GetExampleWait(example);
|
||||
if (waitCmd.length > 0) ret.push(waitCmd);
|
||||
},
|
||||
step?.exampleTemplate,
|
||||
this.resourcePool.genExampleTemplate(step),
|
||||
);
|
||||
return ret;
|
||||
}
|
||||
|
@ -1351,7 +1355,9 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
this._defaultTestScenario,
|
||||
);
|
||||
this.SortExamplesByDependency();
|
||||
PrintTestScenario(this._defaultTestScenario);
|
||||
if (!this.GetResourcePool().hasTestResourceScenario) {
|
||||
PrintTestScenario(this._defaultTestScenario);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this._configuredScenario && isNullOrUndefined(this._testScenario)) {
|
||||
|
@ -1440,7 +1446,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
const commandExamples = this.GetAllExamples();
|
||||
for (let i = 0; i < this._defaultTestScenario.length; i++) {
|
||||
for (const commandExample of commandExamples) {
|
||||
if (this.matchExample(commandExample, this._defaultTestScenario[i].name)) {
|
||||
if (matchExample(commandExample, this._defaultTestScenario[i].name)) {
|
||||
scenarioExamples.set(this._defaultTestScenario[i].name, commandExample);
|
||||
break;
|
||||
}
|
||||
|
@ -1455,14 +1461,6 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
});
|
||||
}
|
||||
|
||||
private matchExample(example: CommandExample, id: string) {
|
||||
if (!id) return false;
|
||||
return (
|
||||
example.Id.toLowerCase() === id.toLowerCase() ||
|
||||
example.Id.toLowerCase().endsWith(`/${id.toLowerCase()}`)
|
||||
);
|
||||
}
|
||||
|
||||
public GetAllExamples(
|
||||
id?: string,
|
||||
callback?: (example) => void,
|
||||
|
@ -1481,7 +1479,7 @@ export class ExampleModelImpl implements ExampleModel {
|
|||
examples = this.GetExamples(true);
|
||||
}
|
||||
for (const example of examples) {
|
||||
if (id && !this.matchExample(example, id)) continue;
|
||||
if (id && !matchExample(example, id)) continue;
|
||||
if (callback) {
|
||||
callback(example);
|
||||
}
|
||||
|
|
|
@ -92,13 +92,17 @@ export class AzCoreFullGenerator extends GeneratorBase {
|
|||
|
||||
await this.generateFullSingleAndAddtoOutput(new CliTestInit(model));
|
||||
await this.generateFullSingleAndAddtoOutput(new CliTestStep(model), true, true);
|
||||
const hasTestResourceScenario = model.GetHandler().exampleHandler.GetResourcePool()
|
||||
.hasTestResourceScenario;
|
||||
for (const testGroup of exampleHandler.Example_TestScenario
|
||||
? Object.getOwnPropertyNames(exampleHandler.Example_TestScenario)
|
||||
: []) {
|
||||
await this.generateFullSingleAndAddtoOutput(
|
||||
new CliTestScenario(
|
||||
model,
|
||||
PathConstants.fullTestSceanrioFile(testGroup),
|
||||
hasTestResourceScenario
|
||||
? PathConstants.testSwaggerScenarioFile(testGroup)
|
||||
: PathConstants.fullTestSceanrioFile(testGroup),
|
||||
exampleHandler.Example_TestScenario[testGroup],
|
||||
testGroup,
|
||||
),
|
||||
|
|
|
@ -127,13 +127,17 @@ export class AzCoreIncrementalGenerator extends GeneratorBase {
|
|||
|
||||
await this.generateIncrementalSingleAndAddtoOutput(new CliTestInit(this.model));
|
||||
await this.generateIncrementalSingleAndAddtoOutput(new CliTestStep(this.model), true);
|
||||
const hasTestResourceScenario = this.model.GetHandler().exampleHandler.GetResourcePool()
|
||||
.hasTestResourceScenario;
|
||||
for (const testGroup of exampleHandler.Example_TestScenario
|
||||
? Object.getOwnPropertyNames(exampleHandler.Example_TestScenario)
|
||||
: []) {
|
||||
await this.generateIncrementalSingleAndAddtoOutput(
|
||||
new CliTestScenario(
|
||||
this.model,
|
||||
PathConstants.incTestScenarioFile(testGroup),
|
||||
hasTestResourceScenario
|
||||
? PathConstants.testSwaggerScenarioFile(testGroup)
|
||||
: PathConstants.incTestScenarioFile(testGroup),
|
||||
exampleHandler.Example_TestScenario[testGroup],
|
||||
testGroup,
|
||||
),
|
||||
|
|
|
@ -92,13 +92,17 @@ export class AzExtensionFullGenerator extends GeneratorBase {
|
|||
|
||||
await this.generateFullSingleAndAddtoOutput(new CliTestInit(this.model));
|
||||
await this.generateFullSingleAndAddtoOutput(new CliTestStep(this.model), true, true);
|
||||
const hasTestResourceScenario = this.model.GetHandler().exampleHandler.GetResourcePool()
|
||||
.hasTestResourceScenario;
|
||||
for (const testGroup of exampleHandler.Example_TestScenario
|
||||
? Object.getOwnPropertyNames(exampleHandler.Example_TestScenario)
|
||||
: []) {
|
||||
await this.generateFullSingleAndAddtoOutput(
|
||||
new CliTestScenario(
|
||||
this.model,
|
||||
PathConstants.fullTestSceanrioFile(testGroup),
|
||||
hasTestResourceScenario
|
||||
? PathConstants.testSwaggerScenarioFile(testGroup)
|
||||
: PathConstants.fullTestSceanrioFile(testGroup),
|
||||
exampleHandler.Example_TestScenario[testGroup],
|
||||
testGroup,
|
||||
),
|
||||
|
|
|
@ -115,13 +115,17 @@ export class AzExtensionIncrementalGenerator extends GeneratorBase {
|
|||
|
||||
await this.generateIncrementalSingleAndAddtoOutput(new CliTestInit(this.model));
|
||||
await this.generateIncrementalSingleAndAddtoOutput(new CliTestStep(this.model), true);
|
||||
const hasTestResourceScenario = this.model.GetHandler().exampleHandler.GetResourcePool()
|
||||
.hasTestResourceScenario;
|
||||
for (const testGroup of exampleHandler.Example_TestScenario
|
||||
? Object.getOwnPropertyNames(exampleHandler.Example_TestScenario)
|
||||
: []) {
|
||||
await this.generateIncrementalSingleAndAddtoOutput(
|
||||
new CliTestScenario(
|
||||
this.model,
|
||||
PathConstants.incTestScenarioFile(testGroup),
|
||||
hasTestResourceScenario
|
||||
? PathConstants.testSwaggerScenarioFile(testGroup)
|
||||
: PathConstants.incTestScenarioFile(testGroup),
|
||||
exampleHandler.Example_TestScenario[testGroup],
|
||||
testGroup,
|
||||
),
|
||||
|
|
|
@ -5,11 +5,10 @@
|
|||
import * as path from 'path';
|
||||
import { CodeModelAz } from '../../codemodel/CodeModelAz';
|
||||
import { CliTestStep } from './CliTestStep';
|
||||
import { ToMultiLine, Capitalize } from '../../../utils/helper';
|
||||
import { ToMultiLine, Capitalize, isNullOrUndefined } from '../../../utils/helper';
|
||||
import { HeaderGenerator } from '../Header';
|
||||
import { TemplateBase } from '../TemplateBase';
|
||||
import { CodeGenConstants, PathConstants } from '../../../utils/models';
|
||||
import { CommandExample } from '../../codemodel/Example';
|
||||
import { CodeGenConstants, PathConstants, AzConfiguration } from '../../../utils/models';
|
||||
|
||||
export class CliTestScenario extends TemplateBase {
|
||||
public configValue: any;
|
||||
|
@ -33,12 +32,22 @@ export class CliTestScenario extends TemplateBase {
|
|||
|
||||
public async fullGeneration(): Promise<string[]> {
|
||||
this.StartGenerateAzureCliTestScenario();
|
||||
for (const scenarioName of Object.getOwnPropertyNames(this.configValue)) {
|
||||
this.GenerateAzureCliTestScenario(
|
||||
this.model,
|
||||
this.configValue[scenarioName],
|
||||
scenarioName,
|
||||
);
|
||||
if (this.model.GetHandler().exampleHandler.GetResourcePool().hasTestResourceScenario) {
|
||||
for (const scenarioName of Object.getOwnPropertyNames(this.configValue)) {
|
||||
this.GenerateTestResourceScenario(
|
||||
this.model,
|
||||
this.configValue[scenarioName],
|
||||
scenarioName,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for (const scenarioName of Object.getOwnPropertyNames(this.configValue)) {
|
||||
this.GenerateAzureCliTestScenario(
|
||||
this.model,
|
||||
this.configValue[scenarioName],
|
||||
scenarioName,
|
||||
);
|
||||
}
|
||||
}
|
||||
return this.EndGenerateAzureCliTestScenario();
|
||||
}
|
||||
|
@ -113,57 +122,44 @@ export class CliTestScenario extends TemplateBase {
|
|||
if (exampleId) {
|
||||
const disabled: string = config[ci].disabled ? '# ' : '';
|
||||
// find example by name
|
||||
let found = false;
|
||||
const examples: CommandExample[] = [];
|
||||
let exampleIdx = -1;
|
||||
for (const exampleCmd of exampleHandler.FindExampleById(
|
||||
|
||||
const [exampleCmd, commandExample] = exampleHandler.FindExampleById(
|
||||
exampleId,
|
||||
commandParams,
|
||||
examples,
|
||||
minimum,
|
||||
config[ci].step,
|
||||
)) {
|
||||
exampleIdx += 1;
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
found = true;
|
||||
const checks = exampleHandler.GetExampleChecks(examples[exampleIdx]);
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: examples[exampleIdx].Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: commandExample.Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
const checks = exampleHandler.GetExampleChecks(commandExample);
|
||||
if (minimum) functionName += '_min';
|
||||
if (checks.length > 0) {
|
||||
outputFunc.push(
|
||||
...ToMultiLine(
|
||||
` ${disabled}${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
)}, checks=[`,
|
||||
),
|
||||
);
|
||||
if (minimum) functionName += '_min';
|
||||
if (checks.length > 0) {
|
||||
outputFunc.push(
|
||||
...ToMultiLine(
|
||||
` ${disabled}${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
)}, checks=[`,
|
||||
),
|
||||
);
|
||||
for (const check of checks) {
|
||||
ToMultiLine(' ' + disabled + ' ' + check, outputFunc);
|
||||
if (
|
||||
!jsonAdded &&
|
||||
!disabled &&
|
||||
check.indexOf('json.loads') >= 0
|
||||
) {
|
||||
template.header.addImport('json');
|
||||
jsonAdded = true;
|
||||
}
|
||||
for (const check of checks) {
|
||||
ToMultiLine(' ' + disabled + ' ' + check, outputFunc);
|
||||
if (!jsonAdded && !disabled && check.indexOf('json.loads') >= 0) {
|
||||
template.header.addImport('json');
|
||||
jsonAdded = true;
|
||||
}
|
||||
outputFunc.push(` ${disabled}])`);
|
||||
} else {
|
||||
outputFunc.push(
|
||||
...ToMultiLine(
|
||||
` ${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
)}, checks=[])`,
|
||||
),
|
||||
);
|
||||
}
|
||||
outputFunc.push(` ${disabled}])`);
|
||||
} else {
|
||||
outputFunc.push(
|
||||
...ToMultiLine(
|
||||
` ${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
)}, checks=[])`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
template.header.addFromImport('.example_steps', [functionName]);
|
||||
template.skip = false;
|
||||
} else {
|
||||
|
@ -180,14 +176,7 @@ export class CliTestScenario extends TemplateBase {
|
|||
)}):`,
|
||||
),
|
||||
);
|
||||
if (
|
||||
functionName.startsWith('setup_') &&
|
||||
exampleHandler.GetResourcePool().hasTestResourceScenario
|
||||
) {
|
||||
steps.push(...exampleHandler.GetResourcePool().setupWithArmTemplate());
|
||||
} else {
|
||||
steps.push(' pass');
|
||||
}
|
||||
steps.push(' pass');
|
||||
steps.push('');
|
||||
steps.push('');
|
||||
}
|
||||
|
@ -253,6 +242,156 @@ export class CliTestScenario extends TemplateBase {
|
|||
}
|
||||
}
|
||||
|
||||
private GenerateTestResourceScenario(model: CodeModelAz, config: any, scenarioName: string) {
|
||||
const exampleHandler = model.GetHandler().exampleHandler;
|
||||
const commandParams = exampleHandler.GatherInternalResource();
|
||||
config.unshift({ function: `setup_${scenarioName}` });
|
||||
config.push({ function: `cleanup_${scenarioName}` });
|
||||
|
||||
const classInfo: string[] = [];
|
||||
const initiates: string[] = [];
|
||||
|
||||
classInfo.push(`# Test class for ${scenarioName}`);
|
||||
classInfo.push('@try_manual');
|
||||
const testClassName = Capitalize(this.groupName) + scenarioName + 'Test';
|
||||
classInfo.push('class ' + testClassName + '(ScenarioTest):');
|
||||
|
||||
const decorators: string[] = [];
|
||||
const resourcePool = exampleHandler.GetResourcePool();
|
||||
const testLocation =
|
||||
AzConfiguration.getValue(CodeGenConstants.az)[CodeGenConstants.testLocation] ||
|
||||
'westus';
|
||||
const scenarioVariables = resourcePool.getTestResourceVariables(config);
|
||||
const kwargs = {};
|
||||
for (const v of scenarioVariables) {
|
||||
if (v === 'location') {
|
||||
kwargs[v] = `'${testLocation}'`;
|
||||
}
|
||||
if (v === 'subscriptionId') {
|
||||
kwargs[v] = 'self.get_subscription_id()';
|
||||
}
|
||||
if (v === 'resourceGroupName') {
|
||||
decorators.push(
|
||||
` @ResourceGroupPreparer(name_prefix='clitest', key='resourceGroupName', location='${testLocation}')`,
|
||||
);
|
||||
this.header.addFromImport('azure.cli.testsdk', ['ResourceGroupPreparer']);
|
||||
}
|
||||
}
|
||||
if (Object.keys(kwargs).length > 0) {
|
||||
initiates.push(' self.kwargs.update({');
|
||||
for (const k of Object.keys(kwargs)) {
|
||||
initiates.push(` '${k}': ${kwargs[k]},`);
|
||||
}
|
||||
initiates.push(' })');
|
||||
initiates.push('');
|
||||
}
|
||||
|
||||
let jsonAdded = false;
|
||||
|
||||
const funcScenario: string[] = [];
|
||||
const steps: string[] = [];
|
||||
funcScenario.push(`# Testcase: ${scenarioName}`);
|
||||
funcScenario.push('@try_manual');
|
||||
funcScenario.push(...ToMultiLine(`def call_${scenarioName.toLowerCase()}(test):`));
|
||||
|
||||
function buildSenario(template: CliTestScenario, outputFunc: string[]) {
|
||||
resourcePool.clearExampleParams();
|
||||
|
||||
// go through the examples to generate steps
|
||||
for (let ci = 0; ci < config.length; ci++) {
|
||||
const exampleId: string = config[ci].name;
|
||||
let functionName: string = CliTestStep.ToFunctionName(config[ci]);
|
||||
if (exampleId) {
|
||||
const disabled: string = config[ci].disabled ? '# ' : '';
|
||||
// find example by name
|
||||
|
||||
const [normalCmd, commandExample] = exampleHandler.FindExampleById(
|
||||
exampleId,
|
||||
commandParams,
|
||||
false,
|
||||
config[ci].step,
|
||||
);
|
||||
let exampleCmd = normalCmd;
|
||||
if (
|
||||
exampleCmd.length == 0 &&
|
||||
!isNullOrUndefined(config[ci].step) &&
|
||||
!isNullOrUndefined(config[ci].method)
|
||||
) {
|
||||
// The command for this example is not generated in current autorest running.
|
||||
exampleCmd = resourcePool.genAzRestCall(
|
||||
config[ci].step,
|
||||
config[ci].method,
|
||||
scenarioVariables,
|
||||
);
|
||||
} else {
|
||||
// The command for this example is generated in current autorest running.
|
||||
// regenerate functionName with the az commandName
|
||||
if (exampleCmd.length > 0)
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: commandExample.Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
}
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
const checks = exampleHandler.GetExampleChecks(commandExample);
|
||||
if (checks.length > 0) {
|
||||
outputFunc.push(
|
||||
...ToMultiLine(` ${disabled}${functionName}(test, checks=[`),
|
||||
);
|
||||
for (const check of checks) {
|
||||
ToMultiLine(' ' + disabled + ' ' + check, outputFunc);
|
||||
if (!jsonAdded && !disabled && check.indexOf('json.loads') >= 0) {
|
||||
template.header.addImport('json');
|
||||
jsonAdded = true;
|
||||
}
|
||||
}
|
||||
outputFunc.push(` ${disabled}])`);
|
||||
} else {
|
||||
outputFunc.push(...ToMultiLine(` ${functionName}(test, checks=[])`));
|
||||
}
|
||||
template.header.addFromImport('.swagger_steps', [functionName]);
|
||||
template.skip = false;
|
||||
} else {
|
||||
outputFunc.push(...ToMultiLine(` # STEP NOT FOUND: ${exampleId}`));
|
||||
}
|
||||
} else {
|
||||
steps.push(`# Env ${functionName}`);
|
||||
steps.push('@try_manual');
|
||||
steps.push(...ToMultiLine(`def ${functionName}(test):`));
|
||||
if (functionName.startsWith('setup_')) {
|
||||
steps.push(...resourcePool.setupWithArmTemplate());
|
||||
} else {
|
||||
steps.push(' pass');
|
||||
}
|
||||
steps.push('');
|
||||
steps.push('');
|
||||
outputFunc.push(...ToMultiLine(` ${functionName}(test)`));
|
||||
}
|
||||
}
|
||||
outputFunc.push('');
|
||||
outputFunc.push('');
|
||||
}
|
||||
buildSenario(this, funcScenario);
|
||||
classInfo.push(' def __init__(self, *args, **kwargs):');
|
||||
classInfo.push(` super(${testClassName}, self).__init__(*args, **kwargs)`);
|
||||
classInfo.push(...initiates);
|
||||
classInfo.push('');
|
||||
|
||||
function buildTestcase(testcaseName: string) {
|
||||
const ret = [...decorators];
|
||||
let funcLine = ' def test_' + testcaseName + '(self';
|
||||
funcLine += '):';
|
||||
ToMultiLine(funcLine, ret);
|
||||
ret.push(` call_${scenarioName.toLowerCase()}(self)`);
|
||||
ret.push(' calc_coverage(__file__)');
|
||||
ret.push(' raise_if()');
|
||||
ret.push('');
|
||||
return ret;
|
||||
}
|
||||
const testCaseName = this.groupName + '_' + scenarioName;
|
||||
this.scenarios.push(...steps.concat(funcScenario, classInfo, buildTestcase(testCaseName)));
|
||||
}
|
||||
|
||||
private EndGenerateAzureCliTestScenario(): string[] {
|
||||
this.header.addFromImport('..', ['try_manual', 'raise_if', 'calc_coverage']);
|
||||
this.scenarios.forEach((element) => {
|
||||
|
|
|
@ -9,7 +9,6 @@ import { ToMultiLine, deepCopy, isNullOrUndefined } from '../../../utils/helper'
|
|||
import { HeaderGenerator } from '../Header';
|
||||
import { TemplateBase } from '../TemplateBase';
|
||||
import { CodeGenConstants, PathConstants, AzConfiguration } from '../../../utils/models';
|
||||
import { CommandExample } from '../../codemodel/Example';
|
||||
|
||||
let usePreparers: Set<string>, shortToLongName, funcNames, allSteps, stepBuff: Record<string, any>;
|
||||
|
||||
|
@ -33,11 +32,16 @@ export class CliTestStep extends TemplateBase {
|
|||
configHandler.AzextFolder,
|
||||
PathConstants.testFolder,
|
||||
PathConstants.latestFolder,
|
||||
PathConstants.testStepFile,
|
||||
model.GetHandler().exampleHandler.GetResourcePool().hasTestResourceScenario
|
||||
? PathConstants.testSwaggerStepFile
|
||||
: PathConstants.testStepFile,
|
||||
);
|
||||
}
|
||||
|
||||
public async fullGeneration(): Promise<string[]> {
|
||||
if (this.model.GetHandler().exampleHandler.GetResourcePool().hasTestResourceScenario) {
|
||||
return this.GenerateTestResourceStep(this.model);
|
||||
}
|
||||
return this.GenerateAzureCliTestStep(this.model);
|
||||
}
|
||||
|
||||
|
@ -46,7 +50,7 @@ export class CliTestStep extends TemplateBase {
|
|||
}
|
||||
|
||||
private GenerateAzureCliTestStep(model: CodeModelAz): string[] {
|
||||
const { extensionHandler, configHandler, exampleHandler } = model.GetHandler();
|
||||
const { configHandler, exampleHandler } = model.GetHandler();
|
||||
initVars();
|
||||
const steps: string[] = [];
|
||||
steps.push('');
|
||||
|
@ -56,15 +60,7 @@ export class CliTestStep extends TemplateBase {
|
|||
|
||||
const commandParams = exampleHandler.GatherInternalResource();
|
||||
let config: any = [];
|
||||
if (exampleHandler.GetResourcePool().hasTestResourceScenario) {
|
||||
for (const g in exampleHandler.Example_TestScenario) {
|
||||
for (const s in exampleHandler.Example_TestScenario[g])
|
||||
config.push(...exampleHandler.Example_TestScenario[g][s]);
|
||||
}
|
||||
} else {
|
||||
config = deepCopy(exampleHandler.Example_DefaultTestScenario);
|
||||
}
|
||||
|
||||
config = deepCopy(exampleHandler.Example_DefaultTestScenario);
|
||||
const header: HeaderGenerator = new HeaderGenerator();
|
||||
|
||||
const parameterNames = CliTestStep.InitiateDependencies(
|
||||
|
@ -89,77 +85,20 @@ export class CliTestStep extends TemplateBase {
|
|||
steps.push('@try_manual');
|
||||
|
||||
// find example by name
|
||||
let found = false;
|
||||
const examples: CommandExample[] = [];
|
||||
let exampleIdx = -1;
|
||||
let waitCmds: string[][];
|
||||
for (const exampleCmd of exampleHandler.FindExampleById(
|
||||
|
||||
const [exampleCmd, commandExample] = exampleHandler.FindExampleById(
|
||||
exampleId,
|
||||
commandParams,
|
||||
examples,
|
||||
minimum,
|
||||
config[ci].step,
|
||||
)) {
|
||||
exampleIdx += 1;
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: examples[exampleIdx].Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
if (minimum) functionName += '_min';
|
||||
if (exampleIdx === 0) {
|
||||
steps.push(
|
||||
...ToMultiLine(
|
||||
`def ${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
true,
|
||||
)}):`,
|
||||
),
|
||||
);
|
||||
}
|
||||
found = true;
|
||||
if (isNullOrUndefined(waitCmds)) {
|
||||
waitCmds = exampleHandler.FindExampleWaitById(exampleId);
|
||||
}
|
||||
);
|
||||
|
||||
const cmdString = exampleCmd.join('\n');
|
||||
if (Object.prototype.hasOwnProperty.call(stepBuff, cmdString)) {
|
||||
steps.push(
|
||||
...ToMultiLine(
|
||||
` return ${
|
||||
stepBuff[cmdString]
|
||||
}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
)}, checks)`,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
stepBuff[cmdString] = functionName;
|
||||
if (examples[exampleIdx].Method === 'delete') {
|
||||
exampleCmd[0] += ' -y';
|
||||
}
|
||||
|
||||
steps.push(' if checks is None:');
|
||||
steps.push(' checks = []');
|
||||
|
||||
for (let idx = 0; idx < exampleCmd.length; idx++) {
|
||||
const prefix: string =
|
||||
' ' +
|
||||
disabled +
|
||||
(idx === 0 ? "test.cmd('" : " '");
|
||||
const postfix: string =
|
||||
idx < exampleCmd.length - 1 ? " '" : "',";
|
||||
ToMultiLine(prefix + exampleCmd[idx] + postfix, steps);
|
||||
}
|
||||
if (isNullOrUndefined(waitCmds) || waitCmds.length === 0) {
|
||||
steps.push(' ' + disabled + ' checks=checks)');
|
||||
} else {
|
||||
steps.push(' ' + disabled + ' checks=[])');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: commandExample.Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
if (minimum) functionName += '_min';
|
||||
steps.push(
|
||||
...ToMultiLine(
|
||||
|
@ -169,9 +108,40 @@ export class CliTestStep extends TemplateBase {
|
|||
)}):`,
|
||||
),
|
||||
);
|
||||
steps.push(' # EXAMPLE NOT FOUND!');
|
||||
steps.push(' pass');
|
||||
} else {
|
||||
if (isNullOrUndefined(waitCmds)) {
|
||||
waitCmds = exampleHandler.FindExampleWaitById(exampleId);
|
||||
}
|
||||
|
||||
const cmdString = exampleCmd.join('\n');
|
||||
if (Object.prototype.hasOwnProperty.call(stepBuff, cmdString)) {
|
||||
steps.push(
|
||||
...ToMultiLine(
|
||||
` return ${
|
||||
stepBuff[cmdString]
|
||||
}(test${CliTestStep.parameterLine(parameterNames)}, checks)`,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
stepBuff[cmdString] = functionName;
|
||||
if (commandExample.Method === 'delete') {
|
||||
exampleCmd[0] += ' -y';
|
||||
}
|
||||
|
||||
steps.push(' if checks is None:');
|
||||
steps.push(' checks = []');
|
||||
|
||||
for (let idx = 0; idx < exampleCmd.length; idx++) {
|
||||
const prefix: string =
|
||||
' ' + disabled + (idx === 0 ? "test.cmd('" : " '");
|
||||
const postfix: string = idx < exampleCmd.length - 1 ? " '" : "',";
|
||||
ToMultiLine(prefix + exampleCmd[idx] + postfix, steps);
|
||||
}
|
||||
if (isNullOrUndefined(waitCmds) || waitCmds.length === 0) {
|
||||
steps.push(' ' + disabled + ' checks=checks)');
|
||||
} else {
|
||||
steps.push(' ' + disabled + ' checks=[])');
|
||||
}
|
||||
}
|
||||
for (const exampleCmd of waitCmds) {
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
for (let idx = 0; idx < exampleCmd.length; idx++) {
|
||||
|
@ -186,6 +156,18 @@ export class CliTestStep extends TemplateBase {
|
|||
steps.push(' ' + disabled + ' checks=checks)');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (minimum) functionName += '_min';
|
||||
steps.push(
|
||||
...ToMultiLine(
|
||||
`def ${functionName}(test${CliTestStep.parameterLine(
|
||||
parameterNames,
|
||||
true,
|
||||
)}):`,
|
||||
),
|
||||
);
|
||||
steps.push(' # EXAMPLE NOT FOUND!');
|
||||
steps.push(' pass');
|
||||
}
|
||||
if (disabled) {
|
||||
steps.push(' pass');
|
||||
|
@ -265,6 +247,12 @@ export class CliTestStep extends TemplateBase {
|
|||
entity.info.className,
|
||||
entity.objectName,
|
||||
)}'`;
|
||||
const testLocation = AzConfiguration.getValue(CodeGenConstants.az)[
|
||||
CodeGenConstants.testLocation
|
||||
];
|
||||
if (testLocation) {
|
||||
line += `, location='${testLocation}'`;
|
||||
}
|
||||
for (let i = 0; i < entity.dependParameterValues.length; i++) {
|
||||
line += `, ${entity.info.dependParameters[i]}='${entity.dependParameterValues[i]}'`;
|
||||
}
|
||||
|
@ -363,4 +351,147 @@ export class CliTestStep extends TemplateBase {
|
|||
const output: string[] = [];
|
||||
return output;
|
||||
}
|
||||
|
||||
private GenerateTestResourceStep(model: CodeModelAz): string[] {
|
||||
initVars();
|
||||
const steps: string[] = [];
|
||||
steps.push('');
|
||||
steps.push('');
|
||||
steps.push('from .. import try_manual');
|
||||
steps.push('');
|
||||
|
||||
const { exampleHandler } = model.GetHandler();
|
||||
const commandParams = exampleHandler.GatherInternalResource();
|
||||
const config: any = [];
|
||||
for (const g in exampleHandler.Example_TestScenario) {
|
||||
for (const s in exampleHandler.Example_TestScenario[g])
|
||||
config.push(...exampleHandler.Example_TestScenario[g][s]);
|
||||
}
|
||||
|
||||
const header: HeaderGenerator = new HeaderGenerator();
|
||||
|
||||
exampleHandler.GetResourcePool().clearExampleParams();
|
||||
const scenarioVariables = exampleHandler.GetResourcePool().getTestResourceVariables(config);
|
||||
|
||||
// go through the examples to generate steps
|
||||
for (let ci = 0; ci < config.length; ci++) {
|
||||
const exampleId: string = config[ci].name;
|
||||
let functionName: string = CliTestStep.ToFunctionName(config[ci]);
|
||||
if (allSteps.includes(functionName)) continue;
|
||||
allSteps.push(functionName);
|
||||
if (exampleId) {
|
||||
const disabled: string = config[ci].disabled ? '# ' : '';
|
||||
steps.push('');
|
||||
steps.push('# EXAMPLE: ' + exampleId);
|
||||
const createStep = () => {
|
||||
steps.push('@try_manual');
|
||||
|
||||
// find example by name
|
||||
let waitCmds: string[][];
|
||||
|
||||
const [normalCmd, commandExample] = exampleHandler.FindExampleById(
|
||||
exampleId,
|
||||
commandParams,
|
||||
false,
|
||||
config[ci].step,
|
||||
);
|
||||
let exampleCmd =
|
||||
commandExample?.commandStringItems.map((x, i) =>
|
||||
exampleHandler.GetResourcePool().formatable(x, scenarioVariables),
|
||||
) || [];
|
||||
if (
|
||||
exampleCmd.length == 0 &&
|
||||
!isNullOrUndefined(config[ci].step) &&
|
||||
!isNullOrUndefined(config[ci].method)
|
||||
) {
|
||||
// The command for this example is not generated in current autorest running.
|
||||
exampleCmd = exampleHandler
|
||||
.GetResourcePool()
|
||||
.genAzRestCall(config[ci].step, config[ci].method, scenarioVariables);
|
||||
} else {
|
||||
// The command for this example is generated in current autorest running.
|
||||
// regenerate functionName with the az commandName
|
||||
if (exampleCmd.length > 0)
|
||||
functionName = CliTestStep.ToFunctionName(
|
||||
{ name: commandExample.Id },
|
||||
exampleCmd[0],
|
||||
);
|
||||
}
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
steps.push(...ToMultiLine(`def ${functionName}(test, checks):`));
|
||||
if (isNullOrUndefined(waitCmds)) {
|
||||
waitCmds = exampleHandler.FindExampleWaitById(exampleId);
|
||||
}
|
||||
|
||||
const cmdString = exampleCmd.join('\n');
|
||||
if (Object.prototype.hasOwnProperty.call(stepBuff, cmdString)) {
|
||||
steps.push(
|
||||
...ToMultiLine(` return ${stepBuff[cmdString]}(test, checks)`),
|
||||
);
|
||||
} else {
|
||||
stepBuff[cmdString] = functionName;
|
||||
if (
|
||||
exampleCmd[0] == normalCmd[0] &&
|
||||
commandExample.Method === 'delete'
|
||||
) {
|
||||
exampleCmd[0] += ' -y';
|
||||
}
|
||||
|
||||
steps.push(' if checks is None:');
|
||||
steps.push(' checks = []');
|
||||
|
||||
for (let idx = 0; idx < exampleCmd.length; idx++) {
|
||||
const prefix: string =
|
||||
' ' + disabled + (idx === 0 ? "test.cmd('" : " '");
|
||||
const postfix: string = idx < exampleCmd.length - 1 ? " '" : "',";
|
||||
ToMultiLine(prefix + exampleCmd[idx] + postfix, steps);
|
||||
}
|
||||
if (isNullOrUndefined(waitCmds) || waitCmds.length === 0) {
|
||||
steps.push(' ' + disabled + ' checks=checks)');
|
||||
} else {
|
||||
steps.push(' ' + disabled + ' checks=[])');
|
||||
}
|
||||
}
|
||||
for (const exampleCmd of waitCmds) {
|
||||
if (exampleCmd && exampleCmd.length > 0) {
|
||||
for (let idx = 0; idx < exampleCmd.length; idx++) {
|
||||
const prefix: string =
|
||||
' ' +
|
||||
disabled +
|
||||
(idx === 0 ? "test.cmd('" : " '");
|
||||
const postfix: string =
|
||||
idx < exampleCmd.length - 1 ? " '" : "',";
|
||||
ToMultiLine(prefix + exampleCmd[idx] + postfix, steps);
|
||||
}
|
||||
steps.push(' ' + disabled + ' checks=checks)');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
steps.push(...ToMultiLine(`def ${functionName}(test, checks):`));
|
||||
steps.push(' # EXAMPLE NOT FOUND!');
|
||||
steps.push(' pass');
|
||||
}
|
||||
if (disabled) {
|
||||
steps.push(' pass');
|
||||
}
|
||||
steps.push('');
|
||||
};
|
||||
createStep();
|
||||
} else if (functionName) {
|
||||
steps.push('');
|
||||
steps.push(`# Env ${functionName}`);
|
||||
steps.push('@try_manual');
|
||||
steps.push(...ToMultiLine(`def ${functionName}(test):`));
|
||||
steps.push(' pass');
|
||||
steps.push('');
|
||||
}
|
||||
}
|
||||
|
||||
steps.forEach((element) => {
|
||||
if (element.length > CodeGenConstants.PYLINT_MAX_CODE_LENGTH + 1) {
|
||||
header.disableLineTooLong = true;
|
||||
}
|
||||
});
|
||||
return header.getLines().concat(steps);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
import 'reflect-metadata';
|
||||
import { TestResourceLoader } from 'oav/dist/lib/testScenario/testResourceLoader';
|
||||
import { CommandExample, ExampleParam, KeyValueType } from '../../codemodel/Example';
|
||||
import {
|
||||
deepCopy,
|
||||
|
@ -9,20 +11,23 @@ import {
|
|||
isNullOrUndefined,
|
||||
Capitalize,
|
||||
ToSnakeCase,
|
||||
setPathValue,
|
||||
checkNested,
|
||||
toPythonName,
|
||||
ToJsonString,
|
||||
thoughtAsTrue,
|
||||
} from '../../../utils/helper';
|
||||
import { EnglishPluralizationService } from '@azure-tools/codegen';
|
||||
import { AzConfiguration, CodeGenConstants } from '../../../utils/models';
|
||||
import { TestResourceLoader } from 'oav/dist/lib/testScenario/testResourceLoader';
|
||||
import { CodeModel, codeModelSchema, Operation, Parameter } from '@azure-tools/codemodel';
|
||||
|
||||
import {
|
||||
TestDefinitionFile,
|
||||
TestStepArmTemplateDeployment,
|
||||
TestStepExampleFileRestCall,
|
||||
TestStepRestCall,
|
||||
TestScenario,
|
||||
} from 'oav/dist/lib/testScenario/testResourceTypes';
|
||||
import * as path from 'path';
|
||||
import * as process from 'process';
|
||||
|
||||
import * as fs from 'fs';
|
||||
export const azOptions = {};
|
||||
|
||||
function MethodToOrder(httpMethod: string): number {
|
||||
|
@ -118,13 +123,15 @@ export function PrintTestScenario(testScenario: any[]) {
|
|||
console.warn('--------------------------------------------------------');
|
||||
}
|
||||
|
||||
export function GroupTestScenario(testScenario: any, extensionName: string) {
|
||||
export function GroupTestScenario(testScenario: any, extensionName: string, singleGroup = false) {
|
||||
if (isNullOrUndefined(testScenario)) return testScenario;
|
||||
|
||||
const ret = {};
|
||||
const defaultScenario = 'Scenario';
|
||||
|
||||
function addScenario(groupName: string, scenarioName: string, items: any[]) {
|
||||
groupName = groupName.substr(0, 50);
|
||||
scenarioName = scenarioName.substr(0, 50);
|
||||
if (!Object.prototype.hasOwnProperty.call(ret, groupName)) ret[groupName] = {};
|
||||
if (!Object.prototype.hasOwnProperty.call(ret[groupName], scenarioName))
|
||||
ret[groupName][scenarioName] = [];
|
||||
|
@ -136,10 +143,14 @@ export function GroupTestScenario(testScenario: any, extensionName: string) {
|
|||
for (const key of keys) {
|
||||
const item = testScenario[key];
|
||||
const splitedName = key.split('_');
|
||||
if (splitedName.length > 1) {
|
||||
addScenario(splitedName[0], splitedName.slice(1).join('_'), item);
|
||||
if (singleGroup) {
|
||||
addScenario(extensionName, key, item);
|
||||
} else {
|
||||
addScenario(splitedName[0], defaultScenario, item);
|
||||
if (splitedName.length > 1) {
|
||||
addScenario(splitedName[0], splitedName.slice(1).join('_'), item);
|
||||
} else {
|
||||
addScenario(splitedName[0], defaultScenario, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (Array.isArray(testScenario)) {
|
||||
|
@ -367,8 +378,11 @@ class ResourceObject {
|
|||
return getResourceKey(this.className, this.objectName);
|
||||
}
|
||||
|
||||
public placeholder(isTest: boolean): string {
|
||||
if (isTest) return '{' + this.key + '}';
|
||||
public placeholder(isTest: boolean, hasTestResourceScenario: boolean): string {
|
||||
if (isTest) {
|
||||
if (hasTestResourceScenario) return this.objectName;
|
||||
return '{' + this.key + '}';
|
||||
}
|
||||
return getResourceKey(this.className, this.objectName, true);
|
||||
}
|
||||
|
||||
|
@ -961,7 +975,7 @@ export class ResourcePool {
|
|||
return instanceResource || classResource;
|
||||
}
|
||||
|
||||
private formatable(str: string, placeholders: string[]) {
|
||||
public formatable(str: string, placeholders: string[]) {
|
||||
str = str.split('{').join('{{').split('}').join('}}');
|
||||
for (const placeholder of placeholders) {
|
||||
str = str.split(`{${placeholder}}`).join(placeholder);
|
||||
|
@ -1200,9 +1214,15 @@ export class ResourcePool {
|
|||
const resource = this.isResource(nodes[i], nodes[i + 1], fullType);
|
||||
if (resource) {
|
||||
resourceObject = this.addTreeResource(resource, nodes[i + 1], resourceObject);
|
||||
nodes[i + 1] = resourceObject.placeholder(isTest);
|
||||
if (placeholders.indexOf(resourceObject.placeholder(isTest)) < 0) {
|
||||
placeholders.push(resourceObject.placeholder(isTest));
|
||||
nodes[i + 1] = resourceObject.placeholder(isTest, this.hasTestResourceScenario);
|
||||
if (
|
||||
placeholders.indexOf(
|
||||
resourceObject.placeholder(isTest, this.hasTestResourceScenario),
|
||||
) < 0
|
||||
) {
|
||||
placeholders.push(
|
||||
resourceObject.placeholder(isTest, this.hasTestResourceScenario),
|
||||
);
|
||||
}
|
||||
if (resources.indexOf(resource) < 0) {
|
||||
resources.push(resource);
|
||||
|
@ -1235,7 +1255,7 @@ export class ResourcePool {
|
|||
}
|
||||
const resourceObject = this.addMapResource(resource, paramValue);
|
||||
if (resourceObject) {
|
||||
return resourceObject.placeholder(isTest);
|
||||
return resourceObject.placeholder(isTest, this.hasTestResourceScenario);
|
||||
} else {
|
||||
return this.getPlaceholder(paramValue, isTest);
|
||||
}
|
||||
|
@ -1254,7 +1274,10 @@ export class ResourcePool {
|
|||
!isNullOrUndefined(this.map[className].objects) &&
|
||||
Object.prototype.hasOwnProperty.call(this.map[className].objects, objectName)
|
||||
) {
|
||||
const ret = this.map[className].objects[objectName].placeholder(isTest);
|
||||
const ret = this.map[className].objects[objectName].placeholder(
|
||||
isTest,
|
||||
this.hasTestResourceScenario,
|
||||
);
|
||||
if (!isNullOrUndefined(placeholders)) {
|
||||
if (placeholders.indexOf(ret) < 0) {
|
||||
placeholders.push(ret);
|
||||
|
@ -1267,7 +1290,7 @@ export class ResourcePool {
|
|||
// find in TreeResource
|
||||
const resourceObject = this.findTreeResource(targetClassName, objectName, this.root);
|
||||
if (resourceObject) {
|
||||
const ret = resourceObject.placeholder(isTest);
|
||||
const ret = resourceObject.placeholder(isTest, this.hasTestResourceScenario);
|
||||
if (!isNullOrUndefined(placeholders)) {
|
||||
if (placeholders.indexOf(ret) < 0) {
|
||||
placeholders.push(ret);
|
||||
|
@ -1382,16 +1405,31 @@ export class ResourcePool {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const loader = new TestResourceLoader({
|
||||
useJsonParser: false,
|
||||
checkUnderFileRoot: false,
|
||||
fileRoot: getSwaggerFolder(),
|
||||
swaggerFilePaths: AzConfiguration.getValue(CodeGenConstants.inputFile),
|
||||
});
|
||||
try {
|
||||
const fileRoot = getSwaggerFolder();
|
||||
const loader = TestResourceLoader.create({
|
||||
useJsonParser: false,
|
||||
checkUnderFileRoot: false,
|
||||
fileRoot: fileRoot,
|
||||
swaggerFilePaths: AzConfiguration.getValue(CodeGenConstants.inputFile),
|
||||
});
|
||||
|
||||
for (const testResource of AzConfiguration.getValue(CodeGenConstants.testResources) || []) {
|
||||
const testDef = await loader.load(testResource[CodeGenConstants.test]);
|
||||
this.testDefs.push(testDef);
|
||||
for (const testResource of AzConfiguration.getValue(CodeGenConstants.testResources) ||
|
||||
[]) {
|
||||
if (fs.existsSync(path.join(fileRoot, testResource[CodeGenConstants.test]))) {
|
||||
const testDef = await loader.load(testResource[CodeGenConstants.test]);
|
||||
this.testDefs.push(testDef);
|
||||
} else {
|
||||
console.warn(
|
||||
`Unexisted test resource scenario file: ${
|
||||
testResource[CodeGenConstants.test]
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Exception occured when load test resource scenario!');
|
||||
console.warn(`${__filename} - FAILURE ${JSON.stringify(error)} ${error.stack}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1432,48 +1470,157 @@ export class ResourcePool {
|
|||
return ret;
|
||||
}
|
||||
|
||||
public generateTestScenario() {
|
||||
const cliScenario = {};
|
||||
for (const testDef of this.testDefs) {
|
||||
for (const testScenario of testDef.testScenarios) {
|
||||
cliScenario[testScenario.description] = [];
|
||||
for (let step of testScenario.steps) {
|
||||
if ((step as TestStepExampleFileRestCall).exampleId) {
|
||||
step = step as TestStepExampleFileRestCall;
|
||||
this.applyTestResourceReplace(step);
|
||||
cliScenario[testScenario.description].push({
|
||||
name: step.exampleId,
|
||||
step: step,
|
||||
});
|
||||
}
|
||||
public getExampleMethodMap(codeModel: CodeModel): Record<string, Operation> {
|
||||
const exampleMap: Record<string, Operation> = {};
|
||||
for (const groups of codeModel.operationGroups) {
|
||||
for (const op of groups.operations) {
|
||||
const xMsExamples = op.extensions?.['x-ms-examples'];
|
||||
for (const exampleid in xMsExamples ?? {}) {
|
||||
exampleMap[exampleid] = op;
|
||||
}
|
||||
}
|
||||
}
|
||||
return exampleMap;
|
||||
}
|
||||
|
||||
public generateTestScenario(allExamples: CommandExample[], codeModel: CodeModel) {
|
||||
// filter scenario by 1) checking wheather any example step can be found in current codemodel
|
||||
// 2) no raw call step
|
||||
const testScenarios: TestScenario[] = [];
|
||||
const exampleMap = this.getExampleMethodMap(codeModel);
|
||||
for (const testDef of this.testDefs) {
|
||||
for (const testScenario of testDef.testScenarios) {
|
||||
let hasRawCall = false;
|
||||
let inCurrentModel = false;
|
||||
for (const step of testScenario.steps) {
|
||||
if ('requestParameters' in step && 'exampleId' in step) {
|
||||
for (const example of allExamples) {
|
||||
if (matchExample(example, step.exampleId)) {
|
||||
inCurrentModel = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hasRawCall = true;
|
||||
}
|
||||
}
|
||||
if (!hasRawCall && inCurrentModel) {
|
||||
testScenarios.push(testScenario);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cliScenario = {};
|
||||
for (const testScenario of testScenarios) {
|
||||
const scenarioName = toPythonName(testScenario.description);
|
||||
cliScenario[scenarioName] = [];
|
||||
for (let step of testScenario.steps) {
|
||||
if ((step as TestStepRestCall).exampleId) {
|
||||
step = step as TestStepRestCall;
|
||||
cliScenario[scenarioName].push({
|
||||
name: step.exampleId,
|
||||
step: step,
|
||||
scenario: testScenario,
|
||||
method: exampleMap[step.exampleId],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cliScenario;
|
||||
}
|
||||
|
||||
public get hasTestResourceScenario(): boolean {
|
||||
return this.testDefs.length > 0;
|
||||
return (
|
||||
thoughtAsTrue(
|
||||
AzConfiguration.getValue(CodeGenConstants.az)[
|
||||
CodeGenConstants.useSwaggerTestScenario
|
||||
],
|
||||
) && this.testDefs.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
public applyTestResourceReplace(step: TestStepExampleFileRestCall) {
|
||||
for (const replace of step.replace) {
|
||||
if (replace.pathInBody) {
|
||||
for (const k in step.exampleTemplate.parameters) {
|
||||
if (checkNested(step.exampleTemplate.parameters[k], replace.pathInBody)) {
|
||||
setPathValue(
|
||||
step.exampleTemplate.parameters[k],
|
||||
replace.pathInBody,
|
||||
replace.to,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replace.pathInExample) {
|
||||
if (checkNested(step.exampleTemplate, replace.pathInBody)) {
|
||||
setPathValue(step.exampleTemplate, replace.pathInBody, replace.to);
|
||||
}
|
||||
public genExampleTemplate(step: TestStepRestCall) {
|
||||
if (isNullOrUndefined(step)) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
parameters: step.requestParameters,
|
||||
responses: {
|
||||
[step.statusCode]: {
|
||||
body: step.responseExpected,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public getTestResourceVariables(config: any[]): string[] {
|
||||
if (!this.hasTestResourceScenario) return [];
|
||||
const variables = new Set<string>(['subscriptionId', 'resourceGroupName']);
|
||||
for (const c of config) {
|
||||
for (const v of c.scenario?._testDef?.requiredVariables || []) {
|
||||
variables.add(v);
|
||||
}
|
||||
}
|
||||
return [...variables];
|
||||
}
|
||||
|
||||
public genAzRestCall(step: TestStepRestCall, method: Operation, variables: string[]): string[] {
|
||||
const parameters: string[] = [];
|
||||
parameters.push('az rest --method ' + step.operation._method);
|
||||
|
||||
const queryParams = [];
|
||||
let url = step.operation._path._pathTemplate;
|
||||
let hasBody = false;
|
||||
let body = null;
|
||||
let operationParams = [];
|
||||
if (method.requests && method.requests.length > 0 && method.requests[0].parameters) {
|
||||
operationParams = method.requests[0].parameters;
|
||||
}
|
||||
for (const parameter of (method.parameters ?? []).concat(operationParams)) {
|
||||
const param =
|
||||
parameter.language?.default?.serializedName || parameter.language?.default?.name;
|
||||
if (isNullOrUndefined(param)) continue;
|
||||
const paramValue = step.requestParameters[param];
|
||||
|
||||
switch (parameter.protocol?.http?.in) {
|
||||
case 'path':
|
||||
url = url.split(`{${param}}`).join(paramValue + '');
|
||||
break;
|
||||
case 'query':
|
||||
if (paramValue !== undefined) {
|
||||
queryParams.push(`${param}=${paramValue}`);
|
||||
}
|
||||
break;
|
||||
case 'body':
|
||||
if (paramValue !== undefined) {
|
||||
hasBody = true;
|
||||
body = JSON.stringify(paramValue)
|
||||
.split(/[\r\n]+/)
|
||||
.join('');
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// ignore flattened parameters
|
||||
}
|
||||
}
|
||||
if (queryParams.length > 0) {
|
||||
url += '?';
|
||||
url += queryParams.join('&');
|
||||
}
|
||||
parameters.push(`--url "${this.formatable(url, variables)}"`);
|
||||
if (hasBody) {
|
||||
parameters.push('--headers "Content-Type=application/json"');
|
||||
body = parameters.push(`--body "${this.formatable(ToJsonString(body), variables)}"`);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
}
|
||||
|
||||
export function matchExample(example: CommandExample, id: string): boolean {
|
||||
if (!id) return false;
|
||||
return (
|
||||
example.Id.toLowerCase() === id.toLowerCase() ||
|
||||
example.Id.toLowerCase().endsWith(`/${id.toLowerCase()}`)
|
||||
);
|
||||
}
|
||||
|
|
|
@ -806,3 +806,7 @@ export function isGeneratedExampleId(exampleId: string): boolean {
|
|||
if (isNullOrUndefined(exampleId)) return false;
|
||||
return exampleId.toLowerCase().endsWith('_gen');
|
||||
}
|
||||
|
||||
export function toPythonName(str: string): string {
|
||||
return str.toLowerCase().replace(/[^0-9a-z]/gi, '_');
|
||||
}
|
||||
|
|
|
@ -70,6 +70,7 @@ export class PathConstants {
|
|||
public static readonly reportFile: string = 'report.md';
|
||||
public static readonly preparersFile: string = 'preparers.py';
|
||||
public static readonly testStepFile: string = 'example_steps.py';
|
||||
public static readonly testSwaggerStepFile: string = 'swagger_steps.py';
|
||||
public static readonly metadataFile: string = 'azext_metadata.json';
|
||||
public static readonly setupPyFile: string = 'setup.py';
|
||||
public static readonly setupCfgFile: string = 'setup.cfg';
|
||||
|
@ -97,6 +98,10 @@ export class PathConstants {
|
|||
return 'test_' + rpName + '_scenario_incrementalGenerated.py';
|
||||
}
|
||||
|
||||
public static testSwaggerScenarioFile(rpName: string): string {
|
||||
return 'test_' + rpName + '_swagger_scenario.py';
|
||||
}
|
||||
|
||||
public static readonly njkFileExtension = '.njk';
|
||||
}
|
||||
|
||||
|
@ -132,6 +137,7 @@ export enum CodeGenConstants {
|
|||
preparers = 'preparers',
|
||||
genCmdletTest = 'gen-cmdlet-test',
|
||||
extensionDescription = 'extension-description',
|
||||
testLocation = 'test-location',
|
||||
|
||||
// some configuration keys under az section
|
||||
namespace = 'namespace',
|
||||
|
@ -142,6 +148,7 @@ export enum CodeGenConstants {
|
|||
clientAuthenticationPolicy = 'client-authentication-policy',
|
||||
testUniqueResource = 'test-unique-resource',
|
||||
useTestStepParam = 'use-test-step-param',
|
||||
useSwaggerTestScenario = 'use-swagger-test-scenario',
|
||||
|
||||
// default constant values
|
||||
minCliCoreVersion = '2.15.0',
|
||||
|
|
|
@ -8,6 +8,7 @@ az:
|
|||
package-name: azure-mgmt-attestation
|
||||
namespace: azure.mgmt.attestation
|
||||
use-test-step-param: true
|
||||
test-location: eastus
|
||||
az-output-folder: $(azure-cli-extension-folder)/src/attestation
|
||||
python-sdk-output-folder: "$(az-output-folder)/azext_attestation/vendored_sdks/attestation"
|
||||
gen-cmdlet-test: true
|
||||
|
|
|
@ -7,9 +7,8 @@ testScenarios:
|
|||
- description: FakedTestScenario
|
||||
steps:
|
||||
- exampleFile: ../examples/Create_AttestationProvider.json
|
||||
step: create attestation provider
|
||||
- exampleFile: ../examples/Update_AttestationProvider.json
|
||||
replace:
|
||||
- pathInBody: tags.Property1
|
||||
to: $(storageAccountId)
|
||||
step: create attestation provider
|
||||
|
||||
|
||||
|
|
|
@ -14,22 +14,22 @@ from .. import try_manual
|
|||
|
||||
# EXAMPLE: AttestationProviders_Create
|
||||
@try_manual
|
||||
def step_create_provider(test, rg, rg_2, rg_3, checks=None):
|
||||
def step_create_provider(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az attestation create-provider '
|
||||
'--resource-group "{rg_4}" '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--provider-name "myattestationprovider"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: AttestationProviders_Update
|
||||
@try_manual
|
||||
def step_attestation_provider_update(test, rg, rg_2, rg_3, checks=None):
|
||||
def step_attestation_provider_update(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az attestation attestation-provider update '
|
||||
'--resource-group "{rg_4}" '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--provider-name "myattestationprovider" '
|
||||
'--tags Property1="{storageAccountId}" Property2="Value2" Property3="Value3"',
|
||||
'--tags Property1="Value1" Property2="Value2" Property3="Value3"',
|
||||
checks=checks)
|
|
@ -1,66 +0,0 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
# pylint: disable=line-too-long
|
||||
|
||||
import os
|
||||
from azure.cli.testsdk import ScenarioTest
|
||||
from azure.cli.testsdk import ResourceGroupPreparer
|
||||
from .example_steps import step_create_provider
|
||||
from .example_steps import step_attestation_provider_update
|
||||
from .. import (
|
||||
try_manual,
|
||||
raise_if,
|
||||
calc_coverage
|
||||
)
|
||||
|
||||
|
||||
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
|
||||
|
||||
|
||||
# Env setup_scenario
|
||||
@try_manual
|
||||
def setup_scenario(test, rg, rg_2, rg_3, rg_4):
|
||||
cmd = "az deployment group create --resource-group {{rg}} --template-file \"{}\"".format(os.path.join(TEST_DIR, 'depSto.json'))
|
||||
o = test.cmd(cmd).get_output_in_json()
|
||||
kwargs = {k: v.get("value") for k, v in o.get('properties', {}).get('outputs', {}).items()}
|
||||
test.kwargs.update(kwargs)
|
||||
|
||||
|
||||
# Env cleanup_scenario
|
||||
@try_manual
|
||||
def cleanup_scenario(test, rg, rg_2, rg_3, rg_4):
|
||||
pass
|
||||
|
||||
|
||||
# Testcase: Scenario
|
||||
@try_manual
|
||||
def call_scenario(test, rg, rg_2, rg_3, rg_4):
|
||||
setup_scenario(test, rg, rg_2, rg_3, rg_4)
|
||||
step_create_provider(test, rg, rg_2, rg_3, rg_4, checks=[])
|
||||
step_attestation_provider_update(test, rg, rg_2, rg_3, rg_4, checks=[])
|
||||
cleanup_scenario(test, rg, rg_2, rg_3, rg_4)
|
||||
|
||||
|
||||
# Test class for Scenario
|
||||
@try_manual
|
||||
class FakedTestScenarioScenarioTest(ScenarioTest):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(FakedTestScenarioScenarioTest, self).__init__(*args, **kwargs)
|
||||
|
||||
@ResourceGroupPreparer(name_prefix='clitestattestation_MyResourceGroup'[:7], key='rg', parameter_name='rg')
|
||||
@ResourceGroupPreparer(name_prefix='clitestattestation_testrg1'[:7], key='rg_2', parameter_name='rg_2')
|
||||
@ResourceGroupPreparer(name_prefix='clitestattestation_sample-resource-group'[:7], key='rg_3',
|
||||
parameter_name='rg_3')
|
||||
@ResourceGroupPreparer(name_prefix='clitestattestation_$(resourceGroupName)'[:7], key='rg_4',
|
||||
parameter_name='rg_4')
|
||||
def test_FakedTestScenario_Scenario(self, rg, rg_2, rg_3, rg_4):
|
||||
call_scenario(self, rg, rg_2, rg_3, rg_4)
|
||||
calc_coverage(__file__)
|
||||
raise_if()
|
|
@ -0,0 +1,66 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
# pylint: disable=line-too-long
|
||||
|
||||
import os
|
||||
from azure.cli.testsdk import ScenarioTest
|
||||
from azure.cli.testsdk import ResourceGroupPreparer
|
||||
from .swagger_steps import step_create_provider
|
||||
from .swagger_steps import step_attestation_provider_update
|
||||
from .. import (
|
||||
try_manual,
|
||||
raise_if,
|
||||
calc_coverage
|
||||
)
|
||||
|
||||
|
||||
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
|
||||
|
||||
|
||||
# Env setup_fakedtestscenario
|
||||
@try_manual
|
||||
def setup_fakedtestscenario(test):
|
||||
cmd = "az deployment group create --resource-group {{rg}} --template-file \"{}\"".format(os.path.join(TEST_DIR, 'depSto.json'))
|
||||
o = test.cmd(cmd).get_output_in_json()
|
||||
kwargs = {k: v.get("value") for k, v in o.get('properties', {}).get('outputs', {}).items()}
|
||||
test.kwargs.update(kwargs)
|
||||
|
||||
|
||||
# Env cleanup_fakedtestscenario
|
||||
@try_manual
|
||||
def cleanup_fakedtestscenario(test):
|
||||
pass
|
||||
|
||||
|
||||
# Testcase: fakedtestscenario
|
||||
@try_manual
|
||||
def call_fakedtestscenario(test):
|
||||
setup_fakedtestscenario(test)
|
||||
step_create_provider(test, checks=[])
|
||||
step_attestation_provider_update(test, checks=[])
|
||||
cleanup_fakedtestscenario(test)
|
||||
|
||||
|
||||
# Test class for fakedtestscenario
|
||||
@try_manual
|
||||
class AttestationfakedtestscenarioTest(ScenarioTest):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(AttestationfakedtestscenarioTest, self).__init__(*args, **kwargs)
|
||||
self.kwargs.update({
|
||||
'subscriptionId': self.get_subscription_id(),
|
||||
'location': 'eastus',
|
||||
})
|
||||
|
||||
|
||||
@ResourceGroupPreparer(name_prefix='clitest', key='resourceGroupName', location='eastus')
|
||||
def test_attestation_fakedtestscenario(self):
|
||||
call_fakedtestscenario(self)
|
||||
calc_coverage(__file__)
|
||||
raise_if()
|
|
@ -9,6 +9,7 @@ az:
|
|||
namespace: azure.mgmt.datafactory
|
||||
formalize-names: true
|
||||
disable-checks: true
|
||||
use-swagger-test-scenario: false
|
||||
az-output-folder: $(azure-cli-extension-folder)/src/datafactory-preview
|
||||
python-sdk-output-folder: "$(az-output-folder)/azext_datafactory_preview/vendored_sdks/azure_mgmt_datafactory"
|
||||
gen-cmdlet-test: true
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
|
||||
## Test-Resources
|
||||
|
||||
These settings is for the test prerequisites.
|
||||
|
||||
``` yaml
|
||||
test-resources:
|
||||
- test: ../input/test-scenarios/testDataExport.yaml
|
||||
```
|
|
@ -0,0 +1,11 @@
|
|||
scope: ResourceGroup
|
||||
|
||||
prepareSteps: []
|
||||
|
||||
testScenarios:
|
||||
- description: FakedTestScenario
|
||||
steps:
|
||||
- exampleFile: ../examples/Factories_Get.json
|
||||
step: create factory
|
||||
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
|
||||
## Test-Resources
|
||||
|
||||
These settings is for the test prerequisites.
|
||||
|
||||
``` yaml
|
||||
test-resources:
|
||||
- test: ../input/preview/2020-04-06-preview/test-scenarios/testRemoteRendering.yaml
|
||||
- test: ../input/stable/2020-05-01/test-scenarios/testSpatialAnchors.yaml
|
||||
```
|
|
@ -0,0 +1,24 @@
|
|||
scope: ResourceGroup
|
||||
|
||||
testScenarios:
|
||||
- description: FakedRemoteRenderingScenario
|
||||
steps:
|
||||
- exampleFile: ../examples/remote-rendering/Put.json
|
||||
step: put remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/RegenerateKey.json
|
||||
step: regenerate-key spatial-anchors
|
||||
- exampleFile: ../examples/remote-rendering/Get.json
|
||||
step: get remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/GetByResourceGroup.json
|
||||
step: GetByResourceGroup remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/GetBySubscription.json
|
||||
step: GetBySubscription remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/ListKeys.json
|
||||
step: ListKeys remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/Patch.json
|
||||
step: patch remote-rendering
|
||||
- exampleFile: ../examples/remote-rendering/Delete.json
|
||||
step: delete remote-rendering
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
|
||||
"contentVersion": "1.0.0.0",
|
||||
"parameters": {
|
||||
},
|
||||
"variables": {
|
||||
"storageAccountName": "[uniqueString(resourceGroup().id)]"
|
||||
},
|
||||
"resources": [{
|
||||
"type": "Microsoft.Storage/storageAccounts",
|
||||
"apiVersion": "2019-06-01",
|
||||
"name": "[variables('storageAccountName')]",
|
||||
"kind": "StorageV2",
|
||||
"location": "[resourceGroup().location]",
|
||||
"sku": {
|
||||
"name": "Standard_LRS"
|
||||
}
|
||||
}],
|
||||
"outputs": {
|
||||
"storageAccountId": {
|
||||
"type": "string",
|
||||
"value": "[resourceId('Microsoft.Storage/storageAccounts',variables('storageAccountName'))]"
|
||||
},
|
||||
"workspaceName": {
|
||||
"type": "string",
|
||||
"value": "[uniqueString(resourceGroup().id)]"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
scope: ResourceGroup
|
||||
|
||||
prepareSteps:
|
||||
- armTemplateDeployment: depSto.json
|
||||
|
||||
testScenarios:
|
||||
- description: FakedSpatialAnchorsScenario
|
||||
steps:
|
||||
- exampleFile: ../examples/spatial-anchors/Put.json
|
||||
step: put spatial-anchors
|
||||
- exampleFile: ../examples/spatial-anchors/RegenerateKey.json
|
||||
step: regenerate-key spatial-anchors
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
|
||||
"contentVersion": "1.0.0.0",
|
||||
"parameters": {},
|
||||
"variables": {
|
||||
"storageAccountName": "[uniqueString(resourceGroup().id)]"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"type": "Microsoft.Storage/storageAccounts",
|
||||
"apiVersion": "2019-06-01",
|
||||
"name": "[variables('storageAccountName')]",
|
||||
"kind": "StorageV2",
|
||||
"location": "[resourceGroup().location]",
|
||||
"sku": {
|
||||
"name": "Standard_LRS"
|
||||
}
|
||||
}
|
||||
],
|
||||
"outputs": {
|
||||
"storageAccountId": {
|
||||
"type": "string",
|
||||
"value": "[resourceId('Microsoft.Storage/storageAccounts',variables('storageAccountName'))]"
|
||||
},
|
||||
"workspaceName": {
|
||||
"type": "string",
|
||||
"value": "[uniqueString(resourceGroup().id)]"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,114 +0,0 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
from .. import try_manual
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/put/Create remote rendering account
|
||||
@try_manual
|
||||
def step_create(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account create '
|
||||
'--account-name "MyAccount" '
|
||||
'--location "eastus2euap" '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/get/Get remote rendering account
|
||||
@try_manual
|
||||
def step_show(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account show '
|
||||
'--account-name "MyAccount" '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/get/List remote rendering accounts by resource group
|
||||
@try_manual
|
||||
def step_list(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/get/List remote rendering accounts by subscription
|
||||
@try_manual
|
||||
def step_list2(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list '
|
||||
'-g ""',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/patch/Update remote rendering account
|
||||
@try_manual
|
||||
def step_update(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account update '
|
||||
'--account-name "MyAccount" '
|
||||
'--location "eastus2euap" '
|
||||
'--tags hero="romeo" heroine="juliet" '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/post/List remote rendering account key
|
||||
@try_manual
|
||||
def step_list_key(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list-key '
|
||||
'--account-name "MyAccount" '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/post/Regenerate remote rendering account keys
|
||||
@try_manual
|
||||
def step_regenerate_key(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account regenerate-key '
|
||||
'--account-name "MyAccount" '
|
||||
'--serial 1 '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /RemoteRenderingAccounts/delete/Delete remote rendering account
|
||||
@try_manual
|
||||
def step_delete(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account delete -y '
|
||||
'--account-name "MyAccount" '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: /SpatialAnchorsAccounts/post/Regenerate spatial anchors account keys
|
||||
@try_manual
|
||||
def step_regenerate_key2(test, checks=None):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az spatial-anchors-account regenerate-key '
|
||||
'--account-name "MyAccount" '
|
||||
'--serial 1 '
|
||||
'--resource-group "{rg}"',
|
||||
checks=checks)
|
|
@ -0,0 +1,124 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
from .. import try_manual
|
||||
|
||||
|
||||
# EXAMPLE: Create remote rendering account
|
||||
@try_manual
|
||||
def step_create(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account create '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount" '
|
||||
'--location "eastus2euap"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Regenerate remote rendering account keys
|
||||
@try_manual
|
||||
def step_regenerate_key(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account regenerate-key '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount" '
|
||||
'--serial 1',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Get remote rendering account
|
||||
@try_manual
|
||||
def step_show(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account show '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: List remote rendering accounts by resource group
|
||||
@try_manual
|
||||
def step_list(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list '
|
||||
'--resource-group "{resourceGroupName}"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: List remote rendering accounts by subscription
|
||||
@try_manual
|
||||
def step_list2(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: List remote rendering account key
|
||||
@try_manual
|
||||
def step_list_key(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account list-key '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Update remote rendering account
|
||||
@try_manual
|
||||
def step_update(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account update '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount" '
|
||||
'--location "eastus2euap" '
|
||||
'--tags heroine="juliet" hero="romeo"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Delete remote rendering account
|
||||
@try_manual
|
||||
def step_delete(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az remote-rendering-account delete -y '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Create spatial anchor account
|
||||
@try_manual
|
||||
def step_create_spatial_anchor_account(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az rest --method put '
|
||||
'--url "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MixedRealit'
|
||||
'y/spatialAnchorsAccounts/MyAccount?api-version=2020-05-01"',
|
||||
checks=checks)
|
||||
|
||||
|
||||
# EXAMPLE: Regenerate spatial anchors account keys
|
||||
@try_manual
|
||||
def step_regenerate_key2(test, checks):
|
||||
if checks is None:
|
||||
checks = []
|
||||
test.cmd('az spatial-anchors-account regenerate-key '
|
||||
'--resource-group "{resourceGroupName}" '
|
||||
'--account-name "MyAccount" '
|
||||
'--serial 1',
|
||||
checks=checks)
|
|
@ -1,79 +0,0 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
import os
|
||||
from azure.cli.testsdk import ScenarioTest
|
||||
from azure.cli.testsdk import ResourceGroupPreparer
|
||||
from .example_steps import step_create
|
||||
from .example_steps import step_list
|
||||
from .example_steps import step_show
|
||||
from .example_steps import step_list2
|
||||
from .example_steps import step_regenerate_key
|
||||
from .example_steps import step_regenerate_key2
|
||||
from .example_steps import step_update
|
||||
from .example_steps import step_delete
|
||||
from .. import (
|
||||
try_manual,
|
||||
raise_if,
|
||||
calc_coverage
|
||||
)
|
||||
|
||||
|
||||
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
|
||||
|
||||
|
||||
# Env setup_scenario
|
||||
@try_manual
|
||||
def setup_scenario(test):
|
||||
pass
|
||||
|
||||
|
||||
# Env cleanup_scenario
|
||||
@try_manual
|
||||
def cleanup_scenario(test):
|
||||
pass
|
||||
|
||||
|
||||
# Testcase: Scenario
|
||||
@try_manual
|
||||
def call_scenario(test):
|
||||
setup_scenario(test)
|
||||
# STEP NOT FOUND: Create spatial anchor account
|
||||
step_create(test, checks=[])
|
||||
# STEP NOT FOUND: Get remote rendering account key
|
||||
# STEP NOT FOUND: Get spatial anchor account key
|
||||
# STEP NOT FOUND: List spatial anchor accounts by resource group
|
||||
step_list(test, checks=[])
|
||||
# STEP NOT FOUND: Get spatial anchors account
|
||||
step_show(test, checks=[])
|
||||
step_list2(test, checks=[])
|
||||
# STEP NOT FOUND: List spatial anchors accounts by subscription
|
||||
# STEP NOT FOUND: List available operations
|
||||
step_regenerate_key(test, checks=[])
|
||||
step_regenerate_key2(test, checks=[])
|
||||
step_update(test, checks=[])
|
||||
# STEP NOT FOUND: Update spatial anchors account
|
||||
# STEP NOT FOUND: CheckLocalNameAvailability
|
||||
# STEP NOT FOUND: Delete spatial anchors account
|
||||
step_delete(test, checks=[])
|
||||
cleanup_scenario(test)
|
||||
|
||||
|
||||
# Test class for Scenario
|
||||
@try_manual
|
||||
class Mixed_realityScenarioTest(ScenarioTest):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Mixed_realityScenarioTest, self).__init__(*args, **kwargs)
|
||||
|
||||
@ResourceGroupPreparer(name_prefix='clitestmixed_reality_MyResourceGroup'[:7], key='rg', parameter_name='rg')
|
||||
def test_mixed_reality_Scenario(self, rg):
|
||||
call_scenario(self)
|
||||
calc_coverage(__file__)
|
||||
raise_if()
|
|
@ -0,0 +1,121 @@
|
|||
# --------------------------------------------------------------------------
|
||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
# Licensed under the MIT License. See License.txt in the project root for
|
||||
# license information.
|
||||
#
|
||||
# Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
# Changes may cause incorrect behavior and will be lost if the code is
|
||||
# regenerated.
|
||||
# --------------------------------------------------------------------------
|
||||
# pylint: disable=line-too-long
|
||||
|
||||
import os
|
||||
from azure.cli.testsdk import ScenarioTest
|
||||
from azure.cli.testsdk import ResourceGroupPreparer
|
||||
from .swagger_steps import step_create
|
||||
from .swagger_steps import step_regenerate_key
|
||||
from .swagger_steps import step_show
|
||||
from .swagger_steps import step_list
|
||||
from .swagger_steps import step_list2
|
||||
from .swagger_steps import step_list_key
|
||||
from .swagger_steps import step_update
|
||||
from .swagger_steps import step_delete
|
||||
from .swagger_steps import step_create_spatial_anchor_account
|
||||
from .swagger_steps import step_regenerate_key2
|
||||
from .. import (
|
||||
try_manual,
|
||||
raise_if,
|
||||
calc_coverage
|
||||
)
|
||||
|
||||
|
||||
TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))
|
||||
|
||||
|
||||
# Env setup_fakedremoterenderingscenario
|
||||
@try_manual
|
||||
def setup_fakedremoterenderingscenario(test):
|
||||
cmd = "az deployment group create --resource-group {{rg}} --template-file \"{}\"".format(os.path.join(TEST_DIR, 'depSto.json'))
|
||||
o = test.cmd(cmd).get_output_in_json()
|
||||
kwargs = {k: v.get("value") for k, v in o.get('properties', {}).get('outputs', {}).items()}
|
||||
test.kwargs.update(kwargs)
|
||||
|
||||
|
||||
# Env cleanup_fakedremoterenderingscenario
|
||||
@try_manual
|
||||
def cleanup_fakedremoterenderingscenario(test):
|
||||
pass
|
||||
|
||||
|
||||
# Testcase: fakedremoterenderingscenario
|
||||
@try_manual
|
||||
def call_fakedremoterenderingscenario(test):
|
||||
setup_fakedremoterenderingscenario(test)
|
||||
step_create(test, checks=[])
|
||||
step_regenerate_key(test, checks=[])
|
||||
step_show(test, checks=[])
|
||||
step_list(test, checks=[])
|
||||
step_list2(test, checks=[])
|
||||
step_list_key(test, checks=[])
|
||||
step_update(test, checks=[])
|
||||
step_delete(test, checks=[])
|
||||
cleanup_fakedremoterenderingscenario(test)
|
||||
|
||||
|
||||
# Test class for fakedremoterenderingscenario
|
||||
@try_manual
|
||||
class Mixed_realityfakedremoterenderingscenarioTest(ScenarioTest):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Mixed_realityfakedremoterenderingscenarioTest, self).__init__(*args, **kwargs)
|
||||
self.kwargs.update({
|
||||
'subscriptionId': self.get_subscription_id(),
|
||||
'location': 'westus',
|
||||
})
|
||||
|
||||
|
||||
@ResourceGroupPreparer(name_prefix='clitest', key='resourceGroupName', location='westus')
|
||||
def test_mixed_reality_fakedremoterenderingscenario(self):
|
||||
call_fakedremoterenderingscenario(self)
|
||||
calc_coverage(__file__)
|
||||
raise_if()
|
||||
|
||||
# Env setup_fakedspatialanchorsscenario
|
||||
@try_manual
|
||||
def setup_fakedspatialanchorsscenario(test):
|
||||
cmd = "az deployment group create --resource-group {{rg}} --template-file \"{}\"".format(os.path.join(TEST_DIR, 'depSto.json'))
|
||||
o = test.cmd(cmd).get_output_in_json()
|
||||
kwargs = {k: v.get("value") for k, v in o.get('properties', {}).get('outputs', {}).items()}
|
||||
test.kwargs.update(kwargs)
|
||||
|
||||
|
||||
# Env cleanup_fakedspatialanchorsscenario
|
||||
@try_manual
|
||||
def cleanup_fakedspatialanchorsscenario(test):
|
||||
pass
|
||||
|
||||
|
||||
# Testcase: fakedspatialanchorsscenario
|
||||
@try_manual
|
||||
def call_fakedspatialanchorsscenario(test):
|
||||
setup_fakedspatialanchorsscenario(test)
|
||||
step_create_spatial_anchor_account(test, checks=[])
|
||||
step_regenerate_key2(test, checks=[])
|
||||
cleanup_fakedspatialanchorsscenario(test)
|
||||
|
||||
|
||||
# Test class for fakedspatialanchorsscenario
|
||||
@try_manual
|
||||
class Mixed_realityfakedspatialanchorsscenarioTest(ScenarioTest):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Mixed_realityfakedspatialanchorsscenarioTest, self).__init__(*args, **kwargs)
|
||||
self.kwargs.update({
|
||||
'subscriptionId': self.get_subscription_id(),
|
||||
'location': 'westus',
|
||||
})
|
||||
|
||||
|
||||
@ResourceGroupPreparer(name_prefix='clitest', key='resourceGroupName', location='westus')
|
||||
def test_mixed_reality_fakedspatialanchorsscenario(self):
|
||||
call_fakedspatialanchorsscenario(self)
|
||||
calc_coverage(__file__)
|
||||
raise_if()
|
Загрузка…
Ссылка в новой задаче