Rename projects from swagger-codegen master branch

This commit is contained in:
Jeremie Bresson
2018-04-14 16:36:30 +02:00
parent c91ce17aee
commit db413f4d26
2399 changed files with 2175 additions and 2194 deletions

View File

@@ -0,0 +1,37 @@
package org.openapitools.codegen;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import org.openapitools.codegen.cmd.ConfigHelp;
import org.openapitools.codegen.cmd.Generate;
import org.openapitools.codegen.cmd.Langs;
import org.openapitools.codegen.cmd.Meta;
import org.openapitools.codegen.cmd.Validate;
import org.openapitools.codegen.cmd.Version;
/**
* User: lanwen Date: 24.03.15 Time: 17:56
* <p>
* Command line interface for swagger codegen use `swagger-codegen-cli.jar help` for more info
*
* @since 2.1.3-M1
*/
public class SwaggerCodegen {
public static void main(String[] args) {
String version = Version.readVersionFromResources();
@SuppressWarnings("unchecked")
Cli.CliBuilder<Runnable> builder =
Cli.<Runnable>builder("swagger-codegen-cli")
.withDescription(
String.format(
"Swagger code generator CLI (version %s). More info on swagger.io",
version))
.withDefaultCommand(Langs.class)
.withCommands(Generate.class, Meta.class, Langs.class, Help.class,
ConfigHelp.class, Validate.class, Version.class);
builder.build().parse(args).run();
}
}

View File

@@ -0,0 +1,28 @@
package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConfigLoader;
@Command(name = "config-help", description = "Config help for chosen lang")
public class ConfigHelp implements Runnable {
@Option(name = {"-l", "--lang"}, title = "language", required = true,
description = "language to get config help for")
private String lang;
@Override
public void run() {
System.out.println();
CodegenConfig config = CodegenConfigLoader.forName(lang);
System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t "
+ langCliOption.getOptionHelp().replaceAll("\n", "\n\t "));
System.out.println();
}
}
}

View File

@@ -0,0 +1,287 @@
package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import java.util.ArrayList;
import java.util.List;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
*/
@Command(name = "generate", description = "Generate code with chosen lang")
public class Generate implements Runnable {
public static final Logger LOG = LoggerFactory.getLogger(Generate.class);
@Option(name = {"-v", "--verbose"}, description = "verbose mode")
private Boolean verbose;
@Option(name = {"-l", "--lang"}, title = "language", required = true,
description = "client language to generate (maybe class name in classpath, required)")
private String lang;
@Option(name = {"-o", "--output"}, title = "output directory",
description = "where to write the generated files (current dir by default)")
private String output = "";
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
description = "location of the swagger spec, as URL or file (required)")
private String spec;
@Option(name = {"-t", "--template-dir"}, title = "template directory",
description = "folder containing the template files")
private String templateDir;
@Option(
name = {"-a", "--auth"},
title = "authorization",
description = "adds authorization headers when fetching the swagger definitions remotely. "
+ "Pass in a URL-encoded string of name:header with a comma separating multiple values")
private String auth;
@Option(
name = {"-D"},
title = "system properties",
description = "sets specified system properties in "
+ "the format of name=value,name=value (or multiple options, each with name=value)")
private List<String> systemProperties = new ArrayList<>();
@Option(
name = {"-c", "--config"},
title = "configuration file",
description = "Path to json configuration file. "
+ "File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} "
+ "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
private String configFile;
@Option(name = {"-s", "--skip-overwrite"}, title = "skip overwrite",
description = "specifies if the existing files should be "
+ "overwritten during the generation.")
private Boolean skipOverwrite;
@Option(name = {"--api-package"}, title = "api package",
description = CodegenConstants.API_PACKAGE_DESC)
private String apiPackage;
@Option(name = {"--model-package"}, title = "model package",
description = CodegenConstants.MODEL_PACKAGE_DESC)
private String modelPackage;
@Option(name = {"--model-name-prefix"}, title = "model name prefix",
description = CodegenConstants.MODEL_NAME_PREFIX_DESC)
private String modelNamePrefix;
@Option(name = {"--model-name-suffix"}, title = "model name suffix",
description = CodegenConstants.MODEL_NAME_SUFFIX_DESC)
private String modelNameSuffix;
@Option(
name = {"--instantiation-types"},
title = "instantiation types",
description = "sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType."
+ "For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code."
+ " You can also have multiple occurrences of this option.")
private List<String> instantiationTypes = new ArrayList<>();
@Option(
name = {"--type-mappings"},
title = "type mappings",
description = "sets mappings between swagger spec types and generated code types "
+ "in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String."
+ " You can also have multiple occurrences of this option.")
private List<String> typeMappings = new ArrayList<>();
@Option(
name = {"--additional-properties"},
title = "additional properties",
description = "sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value."
+ " You can also have multiple occurrences of this option.")
private List<String> additionalProperties = new ArrayList<>();
@Option(
name = {"--language-specific-primitives"},
title = "language specific primitives",
description = "specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double."
+ " You can also have multiple occurrences of this option.")
private List<String> languageSpecificPrimitives = new ArrayList<>();
@Option(
name = {"--import-mappings"},
title = "import mappings",
description = "specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import."
+ " You can also have multiple occurrences of this option.")
private List<String> importMappings = new ArrayList<>();
@Option(name = {"--invoker-package"}, title = "invoker package",
description = CodegenConstants.INVOKER_PACKAGE_DESC)
private String invokerPackage;
@Option(name = {"--group-id"}, title = "group id", description = CodegenConstants.GROUP_ID_DESC)
private String groupId;
@Option(name = {"--artifact-id"}, title = "artifact id",
description = CodegenConstants.ARTIFACT_ID_DESC)
private String artifactId;
@Option(name = {"--artifact-version"}, title = "artifact version",
description = CodegenConstants.ARTIFACT_VERSION_DESC)
private String artifactVersion;
@Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC)
private String library;
@Option(name = {"--git-user-id"}, title = "git user id",
description = CodegenConstants.GIT_USER_ID_DESC)
private String gitUserId;
@Option(name = {"--git-repo-id"}, title = "git repo id",
description = CodegenConstants.GIT_REPO_ID_DESC)
private String gitRepoId;
@Option(name = {"--release-note"}, title = "release note",
description = CodegenConstants.RELEASE_NOTE_DESC)
private String releaseNote;
@Option(name = {"--http-user-agent"}, title = "http user agent",
description = CodegenConstants.HTTP_USER_AGENT_DESC)
private String httpUserAgent;
@Option(
name = {"--reserved-words-mappings"},
title = "reserved word mappings",
description = "specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier."
+ " You can also have multiple occurrences of this option.")
private List<String> reservedWordsMappings = new ArrayList<>();
@Option(name = {"--ignore-file-override"}, title = "ignore file override location",
description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC)
private String ignoreFileOverride;
@Option(name = {"--remove-operation-id-prefix"}, title = "remove prefix of the operationId",
description = CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DESC)
private Boolean removeOperationIdPrefix;
@Override
public void run() {
// attempt to read from config file
CodegenConfigurator configurator = CodegenConfigurator.fromFile(configFile);
// if a config file wasn't specified or we were unable to read it
if (configurator == null) {
// createa a fresh configurator
configurator = new CodegenConfigurator();
}
// now override with any specified parameters
if (verbose != null) {
configurator.setVerbose(verbose);
}
if (skipOverwrite != null) {
configurator.setSkipOverwrite(skipOverwrite);
}
if (isNotEmpty(spec)) {
configurator.setInputSpec(spec);
}
if (isNotEmpty(lang)) {
configurator.setLang(lang);
}
if (isNotEmpty(output)) {
configurator.setOutputDir(output);
}
if (isNotEmpty(auth)) {
configurator.setAuth(auth);
}
if (isNotEmpty(templateDir)) {
configurator.setTemplateDir(templateDir);
}
if (isNotEmpty(apiPackage)) {
configurator.setApiPackage(apiPackage);
}
if (isNotEmpty(modelPackage)) {
configurator.setModelPackage(modelPackage);
}
if (isNotEmpty(modelNamePrefix)) {
configurator.setModelNamePrefix(modelNamePrefix);
}
if (isNotEmpty(modelNameSuffix)) {
configurator.setModelNameSuffix(modelNameSuffix);
}
if (isNotEmpty(invokerPackage)) {
configurator.setInvokerPackage(invokerPackage);
}
if (isNotEmpty(groupId)) {
configurator.setGroupId(groupId);
}
if (isNotEmpty(artifactId)) {
configurator.setArtifactId(artifactId);
}
if (isNotEmpty(artifactVersion)) {
configurator.setArtifactVersion(artifactVersion);
}
if (isNotEmpty(library)) {
configurator.setLibrary(library);
}
if (isNotEmpty(gitUserId)) {
configurator.setGitUserId(gitUserId);
}
if (isNotEmpty(gitRepoId)) {
configurator.setGitRepoId(gitRepoId);
}
if (isNotEmpty(releaseNote)) {
configurator.setReleaseNote(releaseNote);
}
if (isNotEmpty(httpUserAgent)) {
configurator.setHttpUserAgent(httpUserAgent);
}
if (isNotEmpty(ignoreFileOverride)) {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
applySystemPropertiesKvpList(systemProperties, configurator);
applyInstantiationTypesKvpList(instantiationTypes, configurator);
applyImportMappingsKvpList(importMappings, configurator);
applyTypeMappingsKvpList(typeMappings, configurator);
applyAdditionalPropertiesKvpList(additionalProperties, configurator);
applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator);
applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator);
final ClientOptInput clientOptInput = configurator.toClientOptInput();
new DefaultGenerator().opts(clientOptInput).generate();
}
}

View File

@@ -0,0 +1,22 @@
package org.openapitools.codegen.cmd;
import ch.lambdaj.collection.LambdaIterable;
import io.airlift.airline.Command;
import org.openapitools.codegen.CodegenConfig;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.collection.LambdaCollections.with;
import static java.util.ServiceLoader.load;
/**
* User: lanwen Date: 24.03.15 Time: 20:25
*/
@Command(name = "langs", description = "Shows available langs")
public class Langs implements Runnable {
@Override
public void run() {
LambdaIterable<String> langs =
with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName());
System.out.printf("Available languages: %s%n", langs);
}
}

View File

@@ -0,0 +1,153 @@
package org.openapitools.codegen.cmd;
import ch.lambdaj.function.convert.Converter;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.SupportingFile;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import static ch.lambdaj.collection.LambdaCollections.with;
import static com.google.common.base.Joiner.on;
/**
* User: lanwen Date: 24.03.15 Time: 20:22
*/
@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set "
+ "and configuration for Codegen. The output will be based on the language you "
+ "specify, and includes default templates to include.")
public class Meta implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
private static final String TEMPLATE_DIR_CLASSPATH = "codegen";
private static final String MUSTACHE_EXTENSION = ".mustache";
@Option(name = {"-o", "--output"}, title = "output directory",
description = "where to write the generated files (current dir by default)")
private String outputFolder = "";
@Option(name = {"-n", "--name"}, title = "name",
description = "the human-readable name of the generator")
private String name = "default";
@Option(name = {"-p", "--package"}, title = "package",
description = "the package to put the main class into (defaults to org.openapitools.codegen)")
private String targetPackage = "org.openapitools.codegen";
@Override
public void run() {
final File targetDir = new File(outputFolder);
LOGGER.info("writing to folder [{}]", targetDir.getAbsolutePath());
String mainClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name) + "Generator";
List<SupportingFile> supportingFiles =
ImmutableList
.of(new SupportingFile("pom.mustache", "", "pom.xml"),
new SupportingFile("generatorClass.mustache", on(File.separator)
.join("src/main/java", asPath(targetPackage)), mainClass
.concat(".java")), new SupportingFile("README.mustache",
"", "README.md"), new SupportingFile("api.template",
"src/main/resources" + File.separator + name,
"api.mustache"), new SupportingFile("model.template",
"src/main/resources" + File.separator + name,
"model.mustache"), new SupportingFile("services.mustache",
"src/main/resources/META-INF/services",
"org.openapitools.codegen.CodegenConfig"));
String swaggerVersion = Version.readVersionFromResources();
Map<String, Object> data =
new ImmutableMap.Builder<String, Object>().put("generatorPackage", targetPackage)
.put("generatorClass", mainClass).put("name", name)
.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass)
.put("swaggerCodegenVersion", swaggerVersion).build();
with(supportingFiles).convert(processFiles(targetDir, data));
}
/**
* Converter method to process supporting files: execute with mustache, or simply copy to
* destination directory
*
* @param targetDir - destination directory
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
*/
private static Converter<SupportingFile, File> processFiles(final File targetDir,
final Map<String, Object> data) {
return new Converter<SupportingFile, File>() {
private DefaultGenerator generator = new DefaultGenerator();
@Override
public File convert(SupportingFile support) {
try {
File destinationFolder =
new File(new File(targetDir.getAbsolutePath()), support.folder);
File outputFile = new File(destinationFolder, support.destinationFilename);
String template =
generator.readTemplate(new File(TEMPLATE_DIR_CLASSPATH,
support.templateFile).getPath());
String formatted = template;
if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) {
LOGGER.info("writing file to {}", outputFile.getAbsolutePath());
formatted =
Mustache.compiler().withLoader(loader(generator)).defaultValue("")
.compile(template).execute(data);
} else {
LOGGER.info("copying file to {}", outputFile.getAbsolutePath());
}
FileUtils.writeStringToFile(outputFile, formatted);
return outputFile;
} catch (IOException e) {
throw new RuntimeException("Can't generate project", e);
}
}
};
}
/**
* Creates mustache loader for template using classpath loader
*
* @param generator - class with reader getter
* @return loader for template
*/
private static Mustache.TemplateLoader loader(final DefaultGenerator generator) {
return new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + File.separator
+ name.concat(MUSTACHE_EXTENSION));
}
};
}
/**
* Converts package name to path on file system
*
* @param packageName - package name to convert
* @return relative path
*/
private static String asPath(String packageName) {
return packageName.replace(".", File.separator);
}
}

View File

@@ -0,0 +1,37 @@
package org.openapitools.codegen.cmd;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.SwaggerParser;
import io.swagger.parser.util.SwaggerDeserializationResult;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Command(name = "validate", description = "Validate specification")
public class Validate implements Runnable {
@Option(name = {"-i", "--input-spec"}, title = "spec file", required = true,
description = "location of the swagger spec, as URL or file (required)")
private String spec;
@Override
public void run() {
System.out.println("Validating spec file (" + spec + ")");
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult result = parser.readWithInfo(spec, null, true);
List<String> messageList = result.getMessages();
Set<String> messages = new HashSet<String>(messageList);
for (String message : messages) {
System.out.println(message);
}
if (messages.size() > 0) {
throw new ValidateException();
}
}
}

View File

@@ -0,0 +1,7 @@
package org.openapitools.codegen.cmd;
/**
* Created by takuro on 2017/05/02.
*/
public class ValidateException extends RuntimeException {
}

View File

@@ -0,0 +1,45 @@
package org.openapitools.codegen.cmd;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import io.airlift.airline.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command(name = "version", description = "Show version information")
public class Version implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class);
private static final String VERSION_PLACEHOLDER = "${project.version}";
private static final String UNREADABLE_VERSION = "unreadable";
private static final String UNSET_VERSION = "unset";
private static final String UNKNOWN_VERSION = "unknown";
public static String readVersionFromResources() {
Properties versionProperties = new Properties();
try (InputStream is = Version.class.getResourceAsStream("/version.properties")) {
versionProperties.load(is);
} catch (IOException ex) {
LOGGER.error("Error loading version properties", ex);
return UNREADABLE_VERSION;
}
String version = versionProperties.getProperty("version", UNKNOWN_VERSION).trim();
if (VERSION_PLACEHOLDER.equals(version)) {
return UNSET_VERSION;
} else {
return version;
}
}
@Override
public void run() {
String version = readVersionFromResources();
System.out.println(version);
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>
<logger name="io.swagger" level="debug"/>
<root level="error">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@@ -0,0 +1,559 @@
package org.openapitools.codegen.cmd;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.SwaggerCodegen;
import org.openapitools.codegen.config.CodegenConfigurator;
import mockit.Expectations;
import mockit.FullVerifications;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Verifications;
import org.apache.commons.lang3.ArrayUtils;
import org.testng.annotations.Test;
@SuppressWarnings("unused")
public class GenerateTest {
@Mocked
CodegenConfigurator configurator;
@Injectable
ClientOptInput clientOptInput;
@Mocked
DefaultGenerator generator;
@Test
public void testVerbose() throws Exception {
setupAndRunGenericTest("-v");
new FullVerifications() {
{
configurator.setVerbose(true);
times = 1;
}
};
setupAndRunGenericTest("--verbose");
new FullVerifications() {
{
configurator.setVerbose(true);
times = 1;
}
};
}
@Test
public void testRequiredArgs_ShortArgs() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null);
new FullVerifications() {
{
}
};
}
@Test
public void testRequiredArgs_LongArgs() throws Exception {
setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output",
"src/main/java", false, null);
new FullVerifications() {
{
}
};
}
@Test
public void testTemplateDir() throws Exception {
final String templateDir = "src/main/resources/customTemplates";
setupAndRunGenericTest("--template-dir", templateDir);
new FullVerifications() {
{
configurator.setTemplateDir(templateDir);
times = 1;
}
};
setupAndRunGenericTest("-t", templateDir);
new FullVerifications() {
{
configurator.setTemplateDir(templateDir);
times = 1;
}
};
}
@Test
public void testAuth() throws Exception {
final String auth = "hello:world";
setupAndRunGenericTest("--auth", auth);
new FullVerifications() {
{
configurator.setAuth(auth);
times = 1;
}
};
setupAndRunGenericTest("-a", auth);
new FullVerifications() {
{
configurator.setAuth(auth);
times = 1;
}
};
setupAndRunGenericTest();
new FullVerifications() {
{
configurator.setAuth(anyString);
times = 0;
}
};
}
@Test
public void testSystemProperties() throws Exception {
setupAndRunGenericTest("-D", "hello=world,foo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
}
};
setupAndRunGenericTest("-Dhello=world,foo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
}
};
setupAndRunGenericTest("-D", "hello=world,key=,foo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
configurator.addSystemProperty("key", "");
times = 1;
}
};
setupAndRunGenericTest("-D", "hello=world,key,foo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
configurator.addSystemProperty("key", "");
times = 1;
}
};
setupAndRunGenericTest("-D", "hello=world", "-D", "key", "-D", "foo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
configurator.addSystemProperty("key", "");
times = 1;
}
};
setupAndRunGenericTest("-Dhello=world", "-Dkey", "-Dfoo=bar");
new FullVerifications() {
{
configurator.addSystemProperty("hello", "world");
times = 1;
configurator.addSystemProperty("foo", "bar");
times = 1;
configurator.addSystemProperty("key", "");
times = 1;
}
};
}
@Test
public void testConfig() throws Exception {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true,
"config.json", "-c", "config.json");
new FullVerifications() {
{
}
};
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true,
"config.json", "--config", "config.json");
new FullVerifications() {
{
}
};
}
@Test
public void testSkipOverwrite() throws Exception {
setupAndRunGenericTest("-s");
new FullVerifications() {
{
configurator.setSkipOverwrite(true);
times = 1;
}
};
setupAndRunGenericTest("--skip-overwrite");
new FullVerifications() {
{
configurator.setSkipOverwrite(true);
times = 1;
}
};
}
@Test
public void testApiPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--api-package", value);
new FullVerifications() {
{
configurator.setApiPackage(value);
times = 1;
}
};
}
@Test
public void testModelPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--model-package", value);
new FullVerifications() {
{
configurator.setModelPackage(value);
times = 1;
}
};
}
@Test
public void testInstantiationTypes() throws Exception {
setupAndRunGenericTest("--instantiation-types", "hello=world,key=,foo=bar,key2");
new FullVerifications() {
{
configurator.addInstantiationType("hello", "world");
times = 1;
configurator.addInstantiationType("foo", "bar");
times = 1;
configurator.addInstantiationType("key", "");
times = 1;
configurator.addInstantiationType("key2", "");
times = 1;
}
};
setupAndRunGenericTest("--instantiation-types", "hello=world", "--instantiation-types",
"key=", "--instantiation-types", "foo=bar", "--instantiation-types", "key2");
new FullVerifications() {
{
configurator.addInstantiationType("hello", "world");
times = 1;
configurator.addInstantiationType("foo", "bar");
times = 1;
configurator.addInstantiationType("key", "");
times = 1;
configurator.addInstantiationType("key2", "");
times = 1;
}
};
}
@Test
public void testTypeMappings() throws Exception {
setupAndRunGenericTest("--type-mappings", "hello=world,key=,foo=bar,key2");
new FullVerifications() {
{
configurator.addTypeMapping("hello", "world");
times = 1;
configurator.addTypeMapping("foo", "bar");
times = 1;
configurator.addTypeMapping("key", "");
times = 1;
configurator.addTypeMapping("key2", "");
times = 1;
}
};
setupAndRunGenericTest("--type-mappings", "hello=world", "--type-mappings", "key=",
"--type-mappings", "foo=bar", "--type-mappings", "key2");
new FullVerifications() {
{
configurator.addTypeMapping("hello", "world");
times = 1;
configurator.addTypeMapping("foo", "bar");
times = 1;
configurator.addTypeMapping("key", "");
times = 1;
configurator.addTypeMapping("key2", "");
times = 1;
}
};
}
@Test
public void testAdditionalProperties() throws Exception {
setupAndRunGenericTest("--additional-properties", "hello=world,key=,foo=bar,key2");
new FullVerifications() {
{
configurator.addAdditionalProperty("hello", "world");
times = 1;
configurator.addAdditionalProperty("foo", "bar");
times = 1;
configurator.addAdditionalProperty("key", "");
times = 1;
configurator.addAdditionalProperty("key2", "");
times = 1;
}
};
setupAndRunGenericTest("--additional-properties", "hello=world", "--additional-properties",
"key=", "--additional-properties", "foo=bar", "--additional-properties", "key2");
new FullVerifications() {
{
configurator.addAdditionalProperty("hello", "world");
times = 1;
configurator.addAdditionalProperty("foo", "bar");
times = 1;
configurator.addAdditionalProperty("key", "");
times = 1;
configurator.addAdditionalProperty("key2", "");
times = 1;
}
};
}
@Test
public void testLanguageSpecificPrimitives() throws Exception {
setupAndRunGenericTest("--language-specific-primitives", "foo,,bar",
"--language-specific-primitives", "hello,world");
new FullVerifications() {
{
configurator.addLanguageSpecificPrimitive("foo");
times = 1;
configurator.addLanguageSpecificPrimitive("bar");
times = 1;
configurator.addLanguageSpecificPrimitive("hello");
times = 1;
configurator.addLanguageSpecificPrimitive("world");
times = 1;
}
};
}
@Test
public void testImportMappings() throws Exception {
setupAndRunGenericTest("--import-mappings", "hello=world,key=,foo=bar,key2");
new FullVerifications() {
{
configurator.addImportMapping("hello", "world");
times = 1;
configurator.addImportMapping("foo", "bar");
times = 1;
configurator.addImportMapping("key", "");
times = 1;
configurator.addImportMapping("key2", "");
times = 1;
}
};
setupAndRunGenericTest("--import-mappings", "hello=world", "--import-mappings", "key=",
"--import-mappings", "foo=bar", "--import-mappings", "key2");
new FullVerifications() {
{
configurator.addImportMapping("hello", "world");
times = 1;
configurator.addImportMapping("foo", "bar");
times = 1;
configurator.addImportMapping("key", "");
times = 1;
configurator.addImportMapping("key2", "");
times = 1;
}
};
}
@Test
public void testInvokerPackage() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--invoker-package", value);
new FullVerifications() {
{
configurator.setInvokerPackage(value);
times = 1;
}
};
}
@Test
public void testGroupId() throws Exception {
final String value = "io.foo.bar.api";
setupAndRunGenericTest("--group-id", value);
new FullVerifications() {
{
configurator.setGroupId(value);
times = 1;
}
};
}
@Test
public void testArtifactId() throws Exception {
final String value = "awesome-api";
setupAndRunGenericTest("--artifact-id", value);
new FullVerifications() {
{
configurator.setArtifactId(value);
times = 1;
}
};
}
@Test
public void testArtifactVersion() throws Exception {
final String value = "1.2.3";
setupAndRunGenericTest("--artifact-version", value);
new FullVerifications() {
{
configurator.setArtifactVersion(value);
times = 1;
}
};
}
@Test
public void testLibrary() throws Exception {
final String value = "library1";
setupAndRunGenericTest("--library", value);
new FullVerifications() {
{
configurator.setLibrary(value);
times = 1;
}
};
}
private void setupAndRunTest(String specFlag, final String spec, String langFlag,
final String lang, String outputDirFlag, final String outputDir,
boolean configuratorFromFile, final String configFile, String... additionalParameters) {
final String[] commonArgs =
{"generate", langFlag, lang, outputDirFlag, outputDir, specFlag, spec};
String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters);
if (configuratorFromFile) {
new Expectations() {
{
CodegenConfigurator.fromFile(configFile);
times = 1;
result = configurator;
}
};
} else {
new Expectations() {
{
CodegenConfigurator.fromFile(anyString);
result = null;
new CodegenConfigurator();
times = 1;
result = configurator;
}
};
}
new Expectations() {
{
configurator.toClientOptInput();
times = 1;
result = clientOptInput;
new DefaultGenerator();
times = 1;
result = generator;
generator.opts(clientOptInput);
times = 1;
result = generator;
generator.generate();
times = 1;
}
};
SwaggerCodegen.main(argsToUse);
new Verifications() {
{
configurator.setLang(lang);
times = 1;
configurator.setInputSpec(spec);
times = 1;
configurator.setOutputDir(outputDir);
}
};
}
private void setupAndRunGenericTest(String... additionalParameters) {
setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null,
additionalParameters);
}
}

View File

@@ -0,0 +1,59 @@
package org.openapitools.codegen.cmd.utils;
import org.openapitools.codegen.utils.OptionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@SuppressWarnings("static-method")
public class OptionUtilsTest {
@Test
public void splitCommaSeparatedList() throws Exception {
doCommaSeparatedListTest("a,b,c", asList("a", "b", "c"));
doCommaSeparatedListTest("a,,c", asList("a", "c"));
doCommaSeparatedListTest("", emptyList());
doCommaSeparatedListTest(null, emptyList());
}
@Test
public void testParseCommaSeparatedTuples() throws Exception {
doTupleListTest("a=1,b=2,c=3",
asList(Pair.of("a", "1"), Pair.of("b", "2"), Pair.of("c", "3")));
doTupleListTest("xyz", asList(Pair.of("xyz", "")));
doTupleListTest("a=1,,c=3", asList(Pair.of("a", "1"), Pair.of("c", "3")));
doTupleListTest("a=1,xyz=,c=3",
asList(Pair.of("a", "1"), Pair.of("xyz", ""), Pair.of("c", "3")));
doTupleListTest("a=1,xyz,c=3",
asList(Pair.of("a", "1"), Pair.of("xyz", ""), Pair.of("c", "3")));
doTupleListTest("a=1,=,c=3", asList(Pair.of("a", "1"), Pair.of("c", "3")));
doTupleListTest("", emptyPairList());
doTupleListTest(null, emptyPairList());
}
private static void doTupleListTest(String input, List<Pair<String, String>> expectedResults) {
final List<Pair<String, String>> result = OptionUtils.parseCommaSeparatedTuples(input);
assertNotNull(result);
assertEquals(result, expectedResults);
}
private static void doCommaSeparatedListTest(String csvStr, List<String> expectedResults) {
final List<String> result = OptionUtils.splitCommaSeparatedList(csvStr);
assertNotNull(result);
assertEquals(result, expectedResults);
}
private static List<Pair<String, String>> emptyPairList() {
return Collections.emptyList();
}
private static List<String> emptyList() {
return Collections.emptyList();
}
}