Skip to content

Commit

Permalink
test(annotations): fixed failing test
Browse files Browse the repository at this point in the history
  • Loading branch information
gibahjoe committed Dec 14, 2024
1 parent 4152aab commit ee93955
Show file tree
Hide file tree
Showing 15 changed files with 246 additions and 60 deletions.
5 changes: 4 additions & 1 deletion melos_openapi_generator_dart.iml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
<excludeFolder url="file://$MODULE_DIR$/example/api/petstore_api/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/api/petstore_api/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/api/petstore_api/build" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
</component>
</module>
</module>
21 changes: 1 addition & 20 deletions openapi-generator-cli/bin/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,12 @@ import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:openapi_generator_cli/src/models.dart';
import 'package:path/path.dart' as p;

const baseDownloadUrl =
'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli';

/// Default configuration values
class ConfigDefaults {
static const openapiGeneratorVersion = '7.9.0';
static const additionalCommands = '';
static const downloadUrlOverride = null;
static const jarCacheDir = '.dart_tool/openapi_generator_cache';
static const customGeneratorUrls = <String>[
'https://repo1.maven.org/maven2/com/bluetrainsoftware/maven/openapi-dart-generator/7.2/openapi-dart-generator-7.2.jar'
];
}

/// Configuration keys as static constants
class ConfigKeys {
static const openapiGeneratorVersion = 'openapiGeneratorVersion';
static const additionalCommands = 'additionalCommands';
static const downloadUrlOverride = 'downloadUrlOverride';
static const jarCachePath = 'jarCacheDir';
static const customGeneratorUrls = 'customGeneratorUrls';
}

/// Resolves a given path to an absolute path, handling both relative and absolute inputs
String resolvePath(String path) {
return p.isAbsolute(path) ? path : p.absolute(Directory.current.path, path);
Expand Down
41 changes: 41 additions & 0 deletions openapi-generator-cli/lib/src/generate_command.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:args/command_runner.dart';
import 'package:openapi_generator_cli/src/models.dart';

class GenerateCommand extends Command {
// The [name] and [description] properties must be defined by every
// subclass.
final name = "generate";
final description = "Record changes to the repository.";

CommitCommand() {
// Add options based on ConfigDefaults and ConfigKeys
argParser.addOption(ConfigKeys.openapiGeneratorVersion,
help: 'The version of the OpenAPI generator to use.',
defaultsTo: ConfigDefaults.openapiGeneratorVersion);

argParser.addOption(ConfigKeys.additionalCommands,
help:
'Additional commands to pass to the generator. This command will be appended at the end of the commands pas',
defaultsTo: ConfigDefaults.additionalCommands);

argParser.addOption(ConfigKeys.downloadUrlOverride,
help: 'A custom URL to override the default download location.',
defaultsTo: ConfigDefaults.downloadUrlOverride);

argParser.addOption(ConfigKeys.jarCachePath,
help: 'The directory where the JAR cache will be stored.',
defaultsTo: ConfigDefaults.jarCacheDir);

argParser.addMultiOption(ConfigKeys.customGeneratorUrls,
help:
'Urls for the jars of additional OpenAPI generators to combine with the official one.',
defaultsTo: ConfigDefaults.customGeneratorUrls);
}

// [run] may also return a Future.
void run() {
// [argResults] is set before [run()] is called and contains the flags/options
// passed to this command.
print(argResults?.option('all'));
}
}
19 changes: 19 additions & 0 deletions openapi-generator-cli/lib/src/models.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/// Default configuration values
class ConfigDefaults {
static const openapiGeneratorVersion = '7.9.0';
static const additionalCommands = '';
static const downloadUrlOverride = null;
static const jarCacheDir = '.dart_tool/openapi_generator_cache';
static const customGeneratorUrls = <String>[
'https://repo1.maven.org/maven2/com/bluetrainsoftware/maven/openapi-dart-generator/7.2/openapi-dart-generator-7.2.jar'
];
}

/// Configuration keys as static constants
class ConfigKeys {
static const openapiGeneratorVersion = 'openapiGeneratorVersion';
static const additionalCommands = 'additionalCommands';
static const downloadUrlOverride = 'downloadUrlOverride';
static const jarCachePath = 'jarCacheDir';
static const customGeneratorUrls = 'customGeneratorUrls';
}
2 changes: 2 additions & 0 deletions openapi-generator-cli/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ environment:
dependencies:
http: '>=1.2.2 <=2.0.0'
path: '>=1.9.0 <=2.0.0'
args: '>=2.6.0 <3.0.0'
cli_launcher: ^0.3.1

dev_dependencies:
pedantic:
Expand Down
1 change: 1 addition & 0 deletions openapi-generator-cli/test/openapi_generator_cli_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:openapi_generator_cli/src/models.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

Expand Down
17 changes: 16 additions & 1 deletion openapi-generator/lib/src/openapi_generator_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:openapi_generator/src/process_runner.dart';
import 'package:openapi_generator/src/utils.dart';
import 'package:openapi_generator_annotations/openapi_generator_annotations.dart'
as annots;
import 'package:path/path.dart' as path;
import 'package:source_gen/source_gen.dart';

import 'models/command.dart';
Expand Down Expand Up @@ -131,7 +132,21 @@ class OpenapiGenerator extends GeneratorForAnnotation<annots.Openapi> {
workingDirectory: Directory.current.path,
runInShell: Platform.isWindows,
);

var outputDir = path.isRelative(arguments.outputDirectory!)
? path.normalize(
path.join(Directory.current.path, arguments.outputDirectory!))
: path.normalize(arguments.outputDirectory!);
var outputFolderExists = Directory(outputDir).existsSync();
if (!outputFolderExists) {
logOutputMessage(
log: log,
communication: OutputMessage(
message: [
'\n::::::::::::::::::::::::\n:: Seems the code may not have been generated. If you do not find more info in the logs, set debugLogging to true on your annotation and try again.\n::::::::::::::::::::::::',
].join('\n'),
),
);
}
if (result.exitCode != 0) {
return Future.error(
OutputMessage(
Expand Down
3 changes: 3 additions & 0 deletions openapi-generator/melos_openapi_generator.iml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/115/output/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/115/output/.pub" />
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/115/output/build" />
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/167/output/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/167/output/.pub" />
<excludeFolder url="file://$MODULE_DIR$/test/specs/issue/167/output/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
Expand Down
141 changes: 103 additions & 38 deletions openapi-generator/test/github_issues_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import 'utils.dart';

/// We test the build runner by mocking the specs and then checking the output
/// content for the expected generate command.
///
/// we do not use mock process runner for github issues because we want to test
/// that generated code compiles.
/// If you do not want to generate the actual code, then you can initialise [MockProcessRunner] in the test
void main() {
// we do not use mock process runner for github issues because we want to test
// that generated code compiles
var processRunner = ProcessRunner();
group('Github Issues', () {
// setUpAll(() {
Expand Down Expand Up @@ -58,11 +60,8 @@ void main() {
process: processRunner,
);

expect(generatedOutput,
contains('Skipping source gen because generator does not need it.'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenSkipped(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var analyzeResult = await Process.run(
'dart',
['analyze'],
Expand Down Expand Up @@ -101,11 +100,9 @@ void main() {
annotatedFileContent.replaceAll('{{issueNumber}}', issueNumber),
);

expect(generatedOutput,
contains('Skipping source gen because generator does not need it.'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenSkipped(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);

var analyzeResult = await Process.run(
'dart',
['analyze', '--no-fatal-warnings'],
Expand Down Expand Up @@ -133,13 +130,8 @@ void main() {
annotatedFileContent.replaceAll('{{issueNumber}}', issueNumber),
);

expect(
generatedOutput,
contains(
'pub run build_runner build --delete-conflicting-outputs'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenRun(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var workingDirectory = path.join(parentFolder, 'output');
var analyzeResult = await Process.run(
'dart',
Expand Down Expand Up @@ -180,11 +172,8 @@ void main() {
annotatedFileContent.replaceAll('{{issueNumber}}', issueNumber),
);

expect(generatedOutput,
contains('Skipping source gen because generator does not need it.'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenSkipped(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var analyzeResult = await Process.run(
'dart',
['analyze', '--fatal-warnings'],
Expand Down Expand Up @@ -212,13 +201,8 @@ void main() {
annotatedFileContent.replaceAll('{{issueNumber}}', issueNumber),
);

expect(
generatedOutput,
contains(
'pub run build_runner build --delete-conflicting-outputs'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenRun(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var workingDirectory = path.join(parentFolder, 'output');
await Process.run(
'dart',
Expand Down Expand Up @@ -257,11 +241,8 @@ void main() {
var generatedOutput = await generateFromPath(annotatedFile.path,
process: processRunner, openapiSpecFilePath: inputSpecFile.path);

expect(generatedOutput,
contains('Skipping source gen because generator does not need it.'),
reason: generatedOutput);
expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectSourceGenSkipped(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var analyzeResult = await Process.run(
'dart',
['analyze', '--no-fatal-warnings'],
Expand All @@ -282,8 +263,7 @@ void main() {
var generatedOutput = await generateFromPath(annotatedFile.path,
process: processRunner, openapiSpecFilePath: inputSpecFile.path);

expect(generatedOutput, contains('Successfully formatted code.'),
reason: generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var workingDirectory = path.join(parentFolder, 'output');
var analyzeResult = await Process.run(
'dart',
Expand Down Expand Up @@ -333,5 +313,90 @@ void main() {
cleanup(workingDirectory);
}, skip: true);
});

group('#164', () {
var issueNumber = '164';
var parentFolder = path.join(testSpecPath, 'issue', issueNumber);
var workingDirectory = path.join(parentFolder, 'output');
setUpAll(
() {
var workingDirectory = path.join(parentFolder, 'output');
cleanup(workingDirectory);
},
);
test('[dio] Test that generation does not fail', () async {
var generatedOutput = await generateFromAnnotation(
Openapi(
additionalProperties: DioProperties(
pubName: 'petstore_api', pubAuthor: 'Johnny_dep'),
inputSpec: RemoteSpec(
path: 'https://petstore3.swagger.io/api/v3/openapi.json'),
typeMappings: {'Pet': 'ExamplePet'},
generatorName: Generator.dio,
runSourceGenOnOutput: true,
skipIfSpecIsUnchanged: false,
cleanSubOutputDirectory: [
'./test/specs/issue/$issueNumber/output'
],
outputDirectory: './test/specs/issue/$issueNumber/output'),
process: processRunner,
);

expectSourceGenRun(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var analyzeResult = await Process.run(
'dart',
['analyze', '--no-fatal-warnings'],
workingDirectory: workingDirectory,
);
expect(analyzeResult.exitCode, 0,
reason: '${analyzeResult.stdout}\n\n${analyzeResult.stderr}');
cleanup(workingDirectory);
});
});

group('#167', () {
var issueNumber = '167';
var parentFolder = path.join(testSpecPath, 'issue', issueNumber);
var workingDirectory = path.join(parentFolder, 'output');
setUpAll(
() {
var workingDirectory = path.join(parentFolder, 'output');
cleanup(workingDirectory);
},
);
test('[dio] Test that generation does not fail', () async {
var generatedOutput = await generateFromAnnotation(
Openapi(
additionalProperties: DioAltProperties(
pubName: 'issue_api',
),
inputSpec: InputSpec(
path:
'./test/specs/issue/$issueNumber/github_issue_#167.yaml'),
generatorName: Generator.dio,
runSourceGenOnOutput: true,
typeMappings: {'Pet': 'ExamplePet', 'Test': 'ExampleTest'},
skipIfSpecIsUnchanged: false,
cleanSubOutputDirectory: [
'./test/specs/issue/$issueNumber/output'
],
outputDirectory: './test/specs/issue/$issueNumber/output'),
process: processRunner,
);

expectSourceGenRun(generatedOutput);
expectCodeFormattedSuccessfully(generatedOutput);
var analyzeResult = await Process.run(
'dart',
['analyze', '--no-fatal-warnings'],
workingDirectory: workingDirectory,
);
expect(analyzeResult.exitCode, 0,
reason: '${analyzeResult.stdout}\n\n${analyzeResult.stderr}');

cleanup(workingDirectory);
});
});
});
}
4 changes: 4 additions & 0 deletions openapi-generator/test/specs/issue/167/a.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type: object
properties:
optionA1:
type: string
4 changes: 4 additions & 0 deletions openapi-generator/test/specs/issue/167/b.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type: object
properties:
optionB1:
type: string
15 changes: 15 additions & 0 deletions openapi-generator/test/specs/issue/167/github_issue_#167.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
openapi: 3.0.3
info:
version: '1.0'
title: Test
paths:
/test:
get:
operationId: test
responses:
'200':
description: response
content:
application/json:
schema:
$ref: "./test.yml"
Loading

0 comments on commit ee93955

Please sign in to comment.