Merge branch 'master' of https://github.com/swagger-api/swagger-codegen into feature/node-promise-cleanup

This commit is contained in:
Kristof Vrolijkx 2016-05-19 20:08:34 +02:00
commit d583e179ba
249 changed files with 12301 additions and 15799 deletions

34
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,34 @@
<!--
Please follow the issue template below for bug reports and feature requests.
Also please indicate in the issue title which language/library is concerned. Eg: [JAVA] Bug generating foo with bar
-->
##### Description
<!-- describe what is the issue and why this is a problem for you. -->
##### Swagger-codegen version
<!-- which version of swagger-codegen are you using, is it a regression? -->
##### Swagger declaration file content or url
<!-- if it is a bug, a json or yaml that produces it. -->
##### Command line used for generation
<!-- including the language, libraries and various options -->
##### Steps to reproduce
<!-- unambiguous set of steps to reproduce the bug.-->
##### Related issues
<!-- has a similar issue been reported before? -->
##### Suggest a Fix
<!-- if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit) -->

View File

@ -386,6 +386,26 @@ To control the specific files being generated, you can pass a CSV list of what y
-Dmodels=User -DsupportingFiles=StringUtil.java
```
To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`.
These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`):
```
# generate only models (with tests and documentation)
java -Dmodels {opts}
# generate only models (with tests but no documentation)
java -Dmodels -DmodelDocs=false {opts}
# generate only User and Pet models (no tests and no documentation)
java -Dmodels=User,Pet -DmodelTests=false {opts}
# generate only apis (without tests)
java -Dapis -DapiTests=false {opts}
# generate only apis (modelTests option is ignored)
java -Dapis -DmodelTests=false {opts}
```
When using selective generation, _only_ the templates needed for the specific generation will be used.
### Customizing the generator
@ -800,6 +820,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [everystory.us](http://everystory.us)
- [Expected Behavior](http://www.expectedbehavior.com/)
- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de)
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/)
- [LiveAgent](https://www.ladesk.com/)
@ -819,6 +840,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [ThoughtWorks](https://www.thoughtworks.com)
- [uShip](https://www.uship.com/)
- [WEXO A/S](https://www.wexo.dk/)
- [Zalando](https://tech.zalando.com)
- [ZEEF.com](https://zeef.com/)

View File

@ -99,6 +99,16 @@ public abstract class AbstractGenerator {
}
}
public String readResourceContents(String resourceFilePath) {
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(this.getClass().getResourceAsStream(getCPResourcePath(resourceFilePath)), "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(line).append('\n');
}
return sb.toString();
}
public boolean embeddedTemplateExists(String name) {
return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null;
}

View File

@ -184,4 +184,5 @@ public interface CodegenConfig {
String getHttpUserAgent();
String getCommonTemplateDir();
}

View File

@ -105,4 +105,14 @@ public class CodegenConstants {
public static final String SUPPORTS_ES6 = "supportsES6";
public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6.";
public static final String EXCLUDE_TESTS = "excludeTests";
public static final String EXCLUDE_TESTS_DESC = "Specifies that no tests are to be generated.";
public static final String GENERATE_API_TESTS = "generateApiTests";
public static final String GENERATE_API_TESTS_DESC = "Specifies that api tests are to be generated.";
public static final String GENERATE_MODEL_TESTS = "generateModelTests";
public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated.";
}

View File

@ -94,6 +94,7 @@ public class DefaultCodegen {
protected Map<String, String> modelDocTemplateFiles = new HashMap<String, String>();
protected String templateDir;
protected String embeddedTemplateDir;
protected String commonTemplateDir = "_common";
protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
protected Map<String, Object> vendorExtensions = new HashMap<String, Object>();
protected List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
@ -441,6 +442,14 @@ public class DefaultCodegen {
}
}
public String getCommonTemplateDir() {
return this.commonTemplateDir;
}
public void setCommonTemplateDir(String commonTemplateDir) {
this.commonTemplateDir = commonTemplateDir;
}
public Map<String, String> apiDocTemplateFiles() {
return apiDocTemplateFiles;
}

View File

@ -2,6 +2,7 @@ package io.swagger.codegen;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
import io.swagger.models.*;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
@ -24,6 +25,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
protected CodegenConfig config;
protected ClientOptInput opts;
protected Swagger swagger;
protected CodegenIgnoreProcessor ignoreProcessor;
@Override
public Generator opts(ClientOptInput opts) {
@ -31,8 +33,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
this.swagger = opts.getSwagger();
this.config = opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
return this;
}
@ -41,6 +46,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
Boolean generateApis = null;
Boolean generateModels = null;
Boolean generateSupportingFiles = null;
Boolean generateApiTests = null;
Boolean generateApiDocumentation = null;
Boolean generateModelTests = null;
Boolean generateModelDocumentation = null;
Set<String> modelsToGenerate = null;
Set<String> apisToGenerate = null;
@ -68,6 +77,18 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
}
}
if(System.getProperty("modelTests") != null) {
generateModelTests = Boolean.valueOf(System.getProperty("modelTests"));
}
if(System.getProperty("modelDocs") != null) {
generateModelDocumentation = Boolean.valueOf(System.getProperty("modelDocs"));
}
if(System.getProperty("apiTests") != null) {
generateApiTests = Boolean.valueOf(System.getProperty("apiTests"));
}
if(System.getProperty("apiDocs") != null) {
generateApiDocumentation = Boolean.valueOf(System.getProperty("apiDocs"));
}
if(generateApis == null && generateModels == null && generateSupportingFiles == null) {
// no specifics are set, generate everything
@ -85,6 +106,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
// model/api tests and documentation options rely on parent generate options (api or model) and no other options.
// They default to true in all scenarios and can only be marked false explicitly
if (generateModelTests == null) {
generateModelTests = true;
}
if (generateModelDocumentation == null) {
generateModelDocumentation = true;
}
if (generateApiTests == null) {
generateApiTests = true;
}
if (generateApiDocumentation == null) {
generateApiDocumentation = true;
}
// Additional properties added for tests to exclude references in project related files
config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests);
if(Boolean.FALSE.equals(generateApiTests) && Boolean.FALSE.equals(generateModelTests)) {
config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE);
}
if (swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
}
@ -159,7 +202,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
String basePath = hostBuilder.toString();
String basePathWithoutHost = swagger.getBasePath();
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(swagger);
@ -267,66 +309,46 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(models));
files.add(new File(filename));
File written = processTemplateToFile(models, templateName, filename);
if(written != null) {
files.add(written);
}
}
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
if(generateModelTests) {
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(models));
files.add(new File(filename));
}
// to generate model documentation files
for (String templateName : config.modelDocTemplateFiles().keySet()) {
String suffix = config.modelDocTemplateFiles().get(templateName);
String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
if(generateModelDocumentation) {
// to generate model documentation files
for (String templateName : config.modelDocTemplateFiles().keySet()) {
String suffix = config.modelDocTemplateFiles().get(templateName);
String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(models));
files.add(new File(filename));
}
} catch (Exception e) {
throw new RuntimeException("Could not generate model '" + name + "'", e);
@ -401,68 +423,44 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
File written = processTemplateToFile(operation, templateName, filename);
if(written != null) {
files.add(written);
}
}
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
if(generateApiTests) {
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
// to generate api documentation files
for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
if(generateApiDocumentation) {
// to generate api documentation files
for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
}
} catch (Exception e) {
@ -544,53 +542,95 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
if(shouldGenerate) {
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
if(ignoreProcessor.allowsFile(new File(outputFilename))) {
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
}
}
files.add(outputFile);
}
files.add(outputFile);
} else {
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
}
}
} catch (Exception e) {
throw new RuntimeException("Could not generate supporting file '" + support + "'", e);
}
}
// Consider .swagger-codegen-ignore a supporting file
// Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator
final String swaggerCodegenIgnore = ".swagger-codegen-ignore";
String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore;
File ignoreFile = new File(ignoreFileNameTarget);
if(!ignoreFile.exists()) {
String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore;
String ignoreFileContents = readResourceContents(ignoreFileNameSource);
try {
writeToFile(ignoreFileNameTarget, ignoreFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e);
}
files.add(ignoreFile);
}
}
config.processSwagger(swagger);
return files;
}
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename) throws IOException {
if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) {
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(templateData));
return new File(outputFilename);
}
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
return null;
}
private static void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if (mimeTypeList != null && mimeTypeList.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();

View File

@ -0,0 +1,134 @@
package io.swagger.codegen.ignore;
import com.google.common.collect.ImmutableList;
import io.swagger.codegen.ignore.rules.DirectoryRule;
import io.swagger.codegen.ignore.rules.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CodegenIgnoreProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);
private final String outputPath;
private List<Rule> exclusionRules = new ArrayList<>();
private List<Rule> inclusionRules = new ArrayList<>();
public CodegenIgnoreProcessor(String outputPath) {
this.outputPath = outputPath;
final File directory = new File(outputPath);
if(directory.exists() && directory.isDirectory()){
final File codegenIgnore = new File(directory, ".swagger-codegen-ignore");
if(codegenIgnore.exists() && codegenIgnore.isFile()){
try {
loadCodegenRules(codegenIgnore);
} catch (IOException e) {
LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage());
}
} else {
// log info message
LOGGER.info("No .swagger-codegen-ignore file found.");
}
}
}
void loadCodegenRules(File codegenIgnore) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) {
String line;
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
while ((line = reader.readLine()) != null) {
if(
//: A blank line matches no files, so it can serve as a separator for readability.
line.length() == 0
) continue;
Rule rule = Rule.create(line);
// rule could be null here if it's a COMMENT, for example
if(rule != null) {
if (Boolean.TRUE.equals(rule.getNegated())) {
inclusionRules.add(rule);
} else {
exclusionRules.add(rule);
}
}
}
}
}
public boolean allowsFile(File targetFile) {
File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath());
Boolean directoryExcluded = false;
Boolean exclude = false;
if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
return true;
}
// NOTE: We *must* process all exclusion rules
for (int i = 0; i < exclusionRules.size(); i++) {
Rule current = exclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath());
switch (op){
case EXCLUDE:
exclude = true;
// Include rule can't override rules that exclude a file by some parent directory.
if(current instanceof DirectoryRule) {
directoryExcluded = true;
}
break;
case INCLUDE:
// This won't happen here.
break;
case NOOP:
break;
case EXCLUDE_AND_TERMINATE:
i = exclusionRules.size();
break;
}
}
if(exclude) {
// Only need to process inclusion rules if we've been excluded
for (int i = 0; exclude && i < inclusionRules.size(); i++) {
Rule current = inclusionRules.get(i);
Rule.Operation op = current.evaluate(file.getPath());
// At this point exclude=true means the file should be ignored.
// op == INCLUDE means we have to flip that flag.
if(op.equals(Rule.Operation.INCLUDE)) {
if(current instanceof DirectoryRule && directoryExcluded) {
// e.g
// baz/
// !foo/bar/baz/
// NOTE: Possibly surprising side effect:
// foo/bar/baz/
// !bar/
exclude = false;
} else if (!directoryExcluded) {
// e.g.
// **/*.log
// !ISSUE_1234.log
exclude = false;
}
}
}
}
return Boolean.FALSE.equals(exclude);
}
public List<Rule> getInclusionRules() {
return ImmutableList.copyOf(inclusionRules);
}
public List<Rule> getExclusionRules() {
return ImmutableList.copyOf(exclusionRules);
}
}

View File

@ -0,0 +1,20 @@
package io.swagger.codegen.ignore.rules;
import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.util.List;
public class DirectoryRule extends FileRule {
private PathMatcher matcher = null;
DirectoryRule(List<Part> syntax, String definition) {
super(syntax, definition);
matcher = FileSystems.getDefault().getPathMatcher("glob:**/"+this.getPattern());
}
@Override
public Boolean matches(String relativePath) {
return matcher.matches(FileSystems.getDefault().getPath(relativePath));
}
}

View File

@ -0,0 +1,20 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
/**
* An ignore rule which matches everything.
*/
public class EverythingRule extends Rule {
EverythingRule(List<Part> syntax, String definition) {
super(syntax, definition);
}
@Override
public Boolean matches(String relativePath) {
return true;
}
@Override
protected Operation getExcludeOperation(){ return Operation.EXCLUDE_AND_TERMINATE; }
}

View File

@ -0,0 +1,20 @@
package io.swagger.codegen.ignore.rules;
import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.util.List;
public class FileRule extends Rule {
private PathMatcher matcher = null;
FileRule(List<Part> syntax, String definition) {
super(syntax, definition);
matcher = FileSystems.getDefault().getPathMatcher("glob:"+this.getPattern());
}
@Override
public Boolean matches(String relativePath) {
return matcher.matches(FileSystems.getDefault().getPath(relativePath));
}
}

View File

@ -0,0 +1,134 @@
package io.swagger.codegen.ignore.rules;
import java.util.ArrayList;
import java.util.List;
public class IgnoreLineParser {
enum Token {
MATCH_ALL("**"),
MATCH_ANY("*"),
ESCAPED_EXCLAMATION("\\!"),
ESCAPED_SPACE("\\ "),
PATH_DELIM("/"),
NEGATE("!"),
TEXT(null),
DIRECTORY_MARKER("/"),
ROOTED_MARKER("/"),
COMMENT(null);
private String pattern;
Token(String pattern) {
this.pattern = pattern;
}
public String getPattern() {
return pattern;
}
}
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
static List<Part> parse(String text) throws ParserException {
List<Part> parts = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String current = null;
String next = null;
char[] characters = text.toCharArray();
for (int i = 0, totalLength = characters.length; i < totalLength; i++) {
char character = characters[i];
current = String.valueOf(character);
next = i < totalLength - 1 ? String.valueOf(characters[i + 1]) : null;
if (i == 0) {
if ("#".equals(current)) {
//: A line starting with # serves as a comment.
parts.add(new Part(Token.COMMENT, text));
i = totalLength; // rather than early return
continue;
} else if ("!".equals(current)) {
if (i == totalLength - 1) {
throw new ParserException("Negation with no negated pattern.");
} else {
parts.add(new Part(Token.NEGATE));
continue;
}
} else if ("\\".equals(current) && "#".equals(next)) {
//: Put a backslash ("`\`") in front of the first hash for patterns
//: that begin with a hash.
// NOTE: Just push forward and drop the escape character. Falls through to TEXT token.
current = next;
next = null;
i++;
}
}
if (Token.MATCH_ANY.pattern.equals(current)) {
if (Token.MATCH_ANY.pattern.equals(next)) {
// peek ahead for invalid pattern. Slightly inefficient, but acceptable.
if ((i+2 < totalLength - 1) &&
String.valueOf(characters[i+2]).equals(Token.MATCH_ANY.pattern)) {
// It doesn't matter where we are in the pattern, *** is invalid.
throw new ParserException("The pattern *** is invalid.");
}
parts.add(new Part(Token.MATCH_ALL));
i++;
continue;
} else {
parts.add(new Part(Token.MATCH_ANY));
continue;
}
}
if (i == 0 && Token.ROOTED_MARKER.pattern.equals(current)) {
parts.add(new Part(Token.ROOTED_MARKER));
continue;
}
if ("\\".equals(current) && " ".equals(next)) {
parts.add(new Part(Token.ESCAPED_SPACE));
i++;
continue;
} else if ("\\".equals(current) && "!".equals(next)) {
parts.add(new Part(Token.ESCAPED_EXCLAMATION));
i++;
continue;
}
if (Token.PATH_DELIM.pattern.equals(current)) {
if (i != totalLength - 1) {
if (sb.length() > 0) {
parts.add(new Part(Token.TEXT, sb.toString()));
sb.delete(0, sb.length());
}
parts.add(new Part(Token.PATH_DELIM));
if(Token.PATH_DELIM.pattern.equals(next)) {
// ignore doubled path delims. NOTE: doesn't do full lookahead, so /// will result in //
i++;
}
continue;
} else if (i == totalLength - 1) {
parts.add(new Part(Token.TEXT, sb.toString()));
sb.delete(0, sb.length());
parts.add(new Part(Token.DIRECTORY_MARKER));
continue;
}
}
sb.append(current);
}
if (sb.length() > 0) {
// NOTE: All spaces escaped spaces are a special token, ESCAPED_SPACE
//: Trailing spaces are ignored unless they are quoted with backslash ("`\`")
parts.add(new Part(Token.TEXT, sb.toString().trim()));
}
return parts;
}
}

View File

@ -0,0 +1,26 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
public class InvalidRule extends Rule {
private final String reason;
InvalidRule(List<Part> syntax, String definition, String reason) {
super(syntax, definition);
this.reason = reason;
}
@Override
public Boolean matches(String relativePath) {
return null;
}
@Override
public Operation evaluate(String relativePath) {
return Operation.NOOP;
}
public String getReason() {
return reason;
}
}

View File

@ -0,0 +1,15 @@
package io.swagger.codegen.ignore.rules;
public class ParserException extends Exception {
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ParserException(String message) {
super(message);
}
}

View File

@ -0,0 +1,24 @@
package io.swagger.codegen.ignore.rules;
class Part {
private final IgnoreLineParser.Token token;
private final String value;
public Part(IgnoreLineParser.Token token, String value) {
this.token = token;
this.value = value;
}
public Part(IgnoreLineParser.Token token) {
this.token = token;
this.value = token.getPattern();
}
public IgnoreLineParser.Token getToken() {
return token;
}
public String getValue() {
return value;
}
}

View File

@ -0,0 +1,58 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
import java.util.regex.Pattern;
/**
* A special case rule which matches files only if they're located
* in the same directory as the .swagger-codegen-ignore file.
*/
public class RootedFileRule extends Rule {
private String definedFilename = null;
private String definedExtension = null;
RootedFileRule(List<Part> syntax, String definition) {
super(syntax, definition);
int separatorIndex = definition.lastIndexOf(".");
definedFilename = getFilenamePart(definition, separatorIndex);
definedExtension = getExtensionPart(definition, separatorIndex);
}
private String getFilenamePart(final String input, int stopIndex){
return input.substring('/' == input.charAt(0) ? 1 : 0, stopIndex > 0 ? stopIndex : input.length());
}
private String getExtensionPart(final String input, int stopIndex) {
return input.substring(stopIndex > 0 ? stopIndex+1: input.length(), input.length());
}
@Override
public Boolean matches(String relativePath) {
// NOTE: Windows-style separator isn't supported, so File.pathSeparator would be incorrect here.
// NOTE: lastIndexOf rather than contains because /file.txt is acceptable while path/file.txt is not.
// relativePath will be passed by CodegenIgnoreProcessor and is relative to .codegen-ignore.
boolean isSingleFile = relativePath.lastIndexOf("/") <= 0;
if(isSingleFile) {
int separatorIndex = relativePath.lastIndexOf(".");
final String filename = getFilenamePart(relativePath, separatorIndex);
final String extension = getExtensionPart(relativePath, separatorIndex);
boolean extensionMatches = definedExtension.equals(extension) || definedExtension.equals(IgnoreLineParser.Token.MATCH_ANY.getPattern());
if(extensionMatches && definedFilename.contains(IgnoreLineParser.Token.MATCH_ANY.getPattern())) {
// TODO: Evaluate any other escape requirements here.
Pattern regex = Pattern.compile(
definedFilename
.replaceAll(Pattern.quote("."), "\\\\Q.\\\\E")
.replaceAll(Pattern.quote("*"), ".*?") // non-greedy match on 0+ any character
);
return regex.matcher(filename).matches();
}
return extensionMatches && definedFilename.equals(filename);
}
return false;
}
}

View File

@ -0,0 +1,175 @@
package io.swagger.codegen.ignore.rules;
import java.util.List;
public abstract class Rule {
public enum Operation {EXCLUDE, INCLUDE, NOOP, EXCLUDE_AND_TERMINATE}
// The original rule
private final String definition;
private final List<Part> syntax;
Rule(List<Part> syntax, String definition) {
this.syntax = syntax;
this.definition = definition;
}
public abstract Boolean matches(String relativePath);
public String getDefinition() {
return this.definition;
}
protected String getPattern() {
if(syntax == null) return this.definition;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < syntax.size(); i++) {
Part current = syntax.get(i);
switch(current.getToken()){
case MATCH_ALL:
case MATCH_ANY:
case ESCAPED_EXCLAMATION:
case ESCAPED_SPACE:
case PATH_DELIM:
case TEXT:
case DIRECTORY_MARKER:
sb.append(current.getValue());
break;
case NEGATE:
case ROOTED_MARKER:
case COMMENT:
break;
}
}
return sb.toString();
}
/**
* Whether or not the rule should be negated. !foo means foo should be removed from previous matches.
* Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root.
* <p>
* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded.
*/
public Boolean getNegated() {
return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE;
}
public Operation evaluate(String relativePath) {
if (Boolean.TRUE.equals(matches(relativePath))) {
if(Boolean.TRUE.equals(this.getNegated())) {
return this.getIncludeOperation();
}
return this.getExcludeOperation();
}
return Operation.NOOP;
}
protected Operation getIncludeOperation(){ return Operation.INCLUDE; }
protected Operation getExcludeOperation(){ return Operation.EXCLUDE; }
public static Rule create(String definition) {
// NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
// see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
Rule rule = null;
if (definition.equals(".")) {
return new InvalidRule(null, definition, "Pattern '.' is invalid.");
} else if (definition.equals("!.")) {
return new InvalidRule(null, definition, "Pattern '!.' is invalid.");
} else if (definition.startsWith("..")) {
return new InvalidRule(null, definition, "Pattern '..' is invalid.");
}
try {
List<Part> result = IgnoreLineParser.parse(definition);
Boolean directoryOnly = null;
if (result.size() == 0) {
return rule;
} else if (result.size() == 1) {
// single-character filename only
Part part = result.get(0);
if (IgnoreLineParser.Token.MATCH_ANY.equals(part.getToken())) {
rule = new RootedFileRule(result, definition);
} else {
rule = new FileRule(result, definition);
}
} else {
IgnoreLineParser.Token head = result.get(0).getToken();
//: An optional prefix "`!`" which negates the pattern; any
//: matching file excluded by a previous pattern will become
//: included again. It is not possible to re-include a file if a parent
//: directory of that file is excluded. Git doesn't list excluded
//: directories for performance reasons, so any patterns on contained
//: files have no effect, no matter where they are defined.
//: Put a backslash ("`\`") in front of the first "`!`" for patterns
//: that begin with a literal "`!`", for example, "`\!important!.txt`".
// see this.getNegated();
//: If the pattern ends with a slash, it is removed for the
//: purpose of the following description, but it would only find
//: a match with a directory. In other words, `foo/` will match a
//: directory `foo` and paths underneath it, but will not match a
//: regular file or a symbolic link `foo` (this is consistent
//: with the way how pathspec works in general in Git).
directoryOnly = IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result.get(result.size() - 1).getToken());
if (directoryOnly) {
rule = new DirectoryRule(result, definition);
} else if (IgnoreLineParser.Token.PATH_DELIM.equals(head)) {
//: A leading slash matches the beginning of the pathname.
//: For example, "/{asterisk}.c" matches "cat-file.c" but not
//: "mozilla-sha1/sha1.c".
rule = new RootedFileRule(result, definition);
} else {
// case 1
//: If the pattern does not contain a slash '/', Git treats it as
//: a shell glob pattern and checks for a match against the
//: pathname relative to the location of the `.gitignore` file
//: (relative to the toplevel of the work tree if not from a
//: `.gitignore` file).
// case 2
//: Otherwise, Git treats the pattern as a shell glob suitable
//: for consumption by fnmatch(3) with the FNM_PATHNAME flag:
//: wildcards in the pattern will not match a / in the pathname.
//: For example, "Documentation/{asterisk}.html" matches
//: "Documentation/git.html" but not "Documentation/ppc/ppc.html"
//: or "tools/perf/Documentation/perf.html".
// case 3
//: Two consecutive asterisks ("`**`") in patterns matched against
//: full pathname may have special meaning:
//:
//: - A leading "`**`" followed by a slash means match in all
//: directories. For example, "`**/foo`" matches file or directory
//: "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`"
//: matches file or directory "`bar`" anywhere that is directly
//: under directory "`foo`".
//:
//: - A trailing "`/**`" matches everything inside. For example,
//: "`abc/**`" matches all files inside directory "`abc`", relative
//: to the location of the `.gitignore` file, with infinite depth.
//:
//: - A slash followed by two consecutive asterisks then a slash
//: matches zero or more directories. For example, "`a/**/b`"
//: matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on.
//:
//: - Other consecutive asterisks are considered invalid.
rule = new FileRule(result, definition);
}
}
} catch (ParserException e) {
e.printStackTrace();
return new InvalidRule(null, definition, e.getMessage());
}
return rule;
}
}

View File

@ -23,6 +23,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
public AbstractJavaJAXRSServerCodegen()
{
super();
apiTestTemplateFiles.clear(); // TODO: add test template
}
@Override

View File

@ -137,6 +137,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public void processOpts() {
super.processOpts();
Boolean excludeTests = false;
if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
}
apiPackage = "Api";
modelPackage = "Model";
@ -234,7 +239,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
// copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
}
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
@ -247,11 +255,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj"));
// TODO: Check if test project output is enabled, partially related to #2506. Should have options for:
// 1) No test project
// 2) No model tests
// 3) No api tests
supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
}
}
additionalProperties.put("apiDocPath", apiDocPath);

View File

@ -19,6 +19,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
outputFolder = "generated-code/groovy";
modelTemplateFiles.put("model.mustache", ".groovy");
apiTemplateFiles.put(templateFileName, ".groovy");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "Groovy";
apiPackage = "io.swagger.api";

View File

@ -36,7 +36,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactId = "swagger-java-client";
protected String artifactVersion = "1.0.0";
protected String projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
protected String testFolder = projectTestFolder + File.separator + "java";
protected String localVariablePrefix = "";
protected boolean fullJavaUtil;
protected String javaUtilPrefix = "";
@ -52,6 +54,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separator + "java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.put("api_test.mustache", ".java");
embeddedTemplateDir = templateDir = "Java";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
@ -366,6 +369,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public String apiTestFileFolder() {
return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/');
@ -391,6 +399,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(name);
}
@Override
public String toApiTestFilename(String name) {
return toApiName(name) + "Test";
}
@Override
public String toVarName(String name) {
// sanitize name

View File

@ -25,6 +25,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
sourceFolder = "src/gen/java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaInflector";
invokerPackage = "io.swagger.handler";
artifactId = "swagger-inflector-server";

View File

@ -31,6 +31,7 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";

View File

@ -226,10 +226,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
additionalProperties.put("modelFilesPath", modelFilesPath);
additionalProperties.put("coreFilesPath", coreFilesPath);
additionalProperties.put("apiFilesPath", apiFilesPath);
modelPackage = podName;
apiPackage = podName;
@ -253,6 +249,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m"));
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));

View File

@ -34,8 +34,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String COMPOSER_VENDOR_NAME = "composerVendorName";
public static final String COMPOSER_PROJECT_NAME = "composerProjectName";
protected String invokerPackage = "Swagger\\Client";
protected String composerVendorName = "swagger";
protected String composerProjectName = "swagger-client";
protected String composerVendorName = null;
protected String composerProjectName = null;
protected String packagePath = "SwaggerClient-php";
protected String artifactVersion = null;
protected String srcBasePath = "lib";
@ -128,7 +128,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore"));
cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root."));
cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release"));
cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC));
cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release"));
cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3"));
}
@ -216,12 +218,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName);
}
if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) {
this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID));
} else {
additionalProperties.put(CodegenConstants.GIT_USER_ID, gitUserId);
}
if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) {
this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME));
} else {
additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName);
}
if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) {
this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID));
} else {
additionalProperties.put(CodegenConstants.GIT_REPO_ID, gitRepoId);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else {

View File

@ -116,6 +116,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public void processOpts() {
super.processOpts();
Boolean excludeTests = false;
if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
@ -145,13 +150,20 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini"));
supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt"));
supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py"));
supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py"));
supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py"));
supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
if(Boolean.FALSE.equals(excludeTests)) {
supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
}
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}

View File

@ -20,6 +20,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
outputFolder = "generated-code/javaSpringBoot";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringBoot";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";

View File

@ -18,6 +18,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
outputFolder = "generated-code/javaSpringMVC";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringMVC";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";

View File

@ -342,7 +342,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
if (isReservedWord(codegenProperty.datatypeWithEnum) || name.equals(codegenProperty.datatypeWithEnum)) {
if (isReservedWord(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum";
}
}

View File

@ -0,0 +1,41 @@
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -0,0 +1,44 @@
package {{package}};
import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Before;
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private {{classname}} api;
@Before
public void setup() {
api = new ApiClient().buildClient({{classname}}.class);
}
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*/
@Test
public void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -0,0 +1,44 @@
package {{package}};
import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Before;
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private {{classname}} api;
@Before
public void setup() {
api = new ApiClient().createService({{classname}}.class);
}
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*/
@Test
public void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -0,0 +1,44 @@
package {{package}};
import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Before;
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private {{classname}} api;
@Before
public void setup() {
api = new ApiClient().createService({{classname}}.class);
}
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*/
@Test
public void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@ -1,6 +1,7 @@
package {{invokerPackage}}.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import java.io.IOException;
import java.util.Map;
@ -85,42 +86,55 @@ public class OAuth implements Interceptor {
updateAccessToken(null);
}
// Build the request
Builder rb = request.newBuilder();
if (getAccessToken() != null) {
// Build the request
Builder rb = request.newBuilder();
String requestAccessToken = new String(getAccessToken());
try {
oAuthRequest = new OAuthBearerClientRequest(request.url().toString())
.setAccessToken(requestAccessToken)
.buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
String requestAccessToken = new String(getAccessToken());
try {
oAuthRequest = new OAuthBearerClientRequest(request.url().toString())
.setAccessToken(requestAccessToken)
.buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
for ( Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet() ) {
rb.addHeader(header.getKey(), header.getValue());
}
rb.url( oAuthRequest.getLocationUri());
//Execute the request
Response response = chain.proceed(rb.build());
// 401 most likely indicates that access token has expired.
// Time to refresh and resend the request
if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) {
if (updateAccessToken(requestAccessToken)) {
return intercept( chain );
}
}
return response;
} else {
return chain.proceed(chain.request());
}
for ( Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet() ) {
rb.addHeader(header.getKey(), header.getValue());
}
rb.url( oAuthRequest.getLocationUri());
//Execute the request
Response response = chain.proceed(rb.build());
// 401 most likely indicates that access token has expired.
// Time to refresh and resend the request
if ( response.code() == HTTP_UNAUTHORIZED ) {
updateAccessToken(requestAccessToken);
return intercept( chain );
}
return response;
}
public synchronized void updateAccessToken(String requestAccessToken) throws IOException {
/*
* Returns true if the access token has been updated
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage());
setAccessToken(accessTokenResponse.getAccessToken());
if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken());
if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
return getAccessToken().equals(requestAccessToken);
} else {
return false;
}
} catch (OAuthSystemException e) {
throw new IOException(e);
@ -128,6 +142,7 @@ public class OAuth implements Interceptor {
throw new IOException(e);
}
}
return true;
}
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -4,9 +4,9 @@ VisualStudioVersion = 12.0.0.0
MinimumVisualStudioVersion = 10.0.0.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}"
{{^excludeTests}}Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}"
EndProject
Global
{{/excludeTests}}Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU

View File

@ -32,7 +32,7 @@ namespace {{packageName}}.Test
[SetUp]
public void Init()
{
instance = new {{classname}}();
instance = new {{classname}}();
}
/// <summary>

View File

@ -41,7 +41,10 @@
{{/vars}}
public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} = null{{/isReadOnly}}{{#hasMoreNonReadOnly}}, {{/hasMoreNonReadOnly}}{{/vars}})
{
{{#vars}}{{^isReadOnly}}{{#required}}// to ensure "{{name}}" is required (not null)
{{#vars}}
{{^isReadOnly}}
{{#required}}
// to ensure "{{name}}" is required (not null)
if ({{name}} == null)
{
throw new InvalidDataException("{{name}} is a required property for {{classname}} and cannot be null");
@ -50,8 +53,12 @@
{
this.{{name}} = {{name}};
}
{{/required}}{{/isReadOnly}}{{/vars}}
{{#vars}}{{^isReadOnly}}{{^required}}
{{/required}}
{{/isReadOnly}}
{{/vars}}
{{#vars}}
{{^isReadOnly}}
{{^required}}
{{#defaultValue}}// use default value if no "{{name}}" provided
if ({{name}} == null)
{
@ -63,9 +70,11 @@
}
{{/defaultValue}}
{{^defaultValue}}
this.{{name}} = {{name}};
this.{{name}} = {{name}};
{{/defaultValue}}
{{/required}}{{/isReadOnly}}{{/vars}}
{{/required}}
{{/isReadOnly}}
{{/vars}}
}
{{#vars}}
@ -86,7 +95,8 @@
{
var sb = new StringBuilder();
sb.Append("class {{classname}} {\n");
{{#vars}}sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
{{#vars}}
sb.Append(" {{name}}: ").Append({{name}}).Append("\n");
{{/vars}}
sb.Append("}\n");
return sb.ToString();

View File

@ -5,6 +5,7 @@ import (
"strings"
"fmt"
"errors"
"net/url"
{{#imports}}"{{import}}"
{{/imports}}
)
@ -50,7 +51,7 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{
}{{/required}}{{/allParams}}
headerParams := make(map[string]string)
queryParams := make(map[string]string)
queryParams := url.Values{}
formParams := make(map[string]string)
var postBody interface{}
var fileName string
@ -75,9 +76,22 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{
// add default headers if any
for key := range a.Configuration.DefaultHeader {
headerParams[key] = a.Configuration.DefaultHeader[key]
}{{#hasQueryParams}}{{#queryParams}}
queryParams["{{paramName}}"] = a.Configuration.APIClient.ParameterToString({{paramName}})
}
{{#hasQueryParams}}
{{#queryParams}}
{{#isListContainer}}
var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"
if collectionFormat == "multi" {
for _, value := range {{paramName}} {
queryParams.Add("{{paramName}}", value)
}
} else {
queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat))
}
{{/isListContainer}}
{{^isListContainer}}
queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, ""))
{{/isListContainer}}
{{/queryParams}}{{/hasQueryParams}}
// to determine the Content-Type header

View File

@ -6,7 +6,7 @@ import (
"path/filepath"
"reflect"
"strings"
"net/url"
"github.com/go-resty/resty"
)
@ -47,7 +47,7 @@ func contains(source []string, containvalue string) bool {
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
@ -79,17 +79,26 @@ func (c *APIClient) CallAPI(path string, method string,
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}) string {
func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string {
if reflect.TypeOf(obj).String() == "[]string" {
return strings.Join(obj.([]string), ",")
} else {
return obj.(string)
switch collectionFormat {
case "pipes":
return strings.Join(obj.([]string), "|")
case "ssv":
return strings.Join(obj.([]string), " ")
case "tsv":
return strings.Join(obj.([]string), "\t")
case "csv" :
return strings.Join(obj.([]string), ",")
}
}
return obj.(string)
}
func prepareRequest(postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
@ -104,7 +113,7 @@ func prepareRequest(postBody interface{},
// add query parameter, if any
if len(queryParams) > 0 {
request.SetQueryParams(queryParams)
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any

View File

@ -83,8 +83,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
reachabilityStatus = status;
}
- (void)setHeaderValue:(NSString*) value
forKey:(NSString*) forKey {
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
}
@ -110,7 +109,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
#pragma mark - Request Methods
+(unsigned long)requestQueueSize {
+(NSUInteger)requestQueueSize {
return [queuedRequests count];
}
@ -221,8 +220,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
}
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig];
NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory();
NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory();
NSString * filename = {{classPrefix}}__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
@ -442,16 +440,16 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
if (!authSettings || [authSettings count] == 0) {
if ([authSettings count] == 0) {
return;
}
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig];
NSDictionary* configurationAuthSettings = [[self configuration] authSettings];
for (NSString *auth in authSettings) {
NSDictionary *authSetting = [config authSettings][auth];
NSDictionary *authSetting = configurationAuthSettings[auth];
if(!authSetting) { // auth setting is set only if the key is non-empty
continue;
}
@ -472,7 +470,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
- (AFSecurityPolicy *) customSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig];
{{classPrefix}}Configuration *config = [self configuration];
if (config.sslCaCert) {
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
@ -490,4 +488,8 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
return securityPolicy;
}
- ({{classPrefix}}Configuration*) configuration {
return [{{classPrefix}}Configuration sharedConfig];
}
@end

View File

@ -56,7 +56,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*
* @return The size of `queuedRequests` static variable.
*/
+(unsigned long)requestQueueSize;
+(NSUInteger)requestQueueSize;
/**
* Sets the client unreachable
@ -176,5 +176,12 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
*/
- (AFSecurityPolicy *) customSecurityPolicy;
/**
* {{classPrefix}}Configuration return sharedConfig
*
* @return {{classPrefix}}Configuration
*/
- ({{classPrefix}}Configuration*) configuration;
@end

View File

@ -2,8 +2,9 @@
@interface {{classPrefix}}Configuration ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix;
@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders;
@property (nonatomic, strong) NSMutableDictionary *mutableApiKey;
@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix;
@end
@ -33,6 +34,7 @@
self.verifySSL = YES;
self.mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders = [NSMutableDictionary dictionary];
self.logger = [{{classPrefix}}Logger sharedLogger];
}
return self;
@ -147,4 +149,26 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];
return;
}
self.mutableDefaultHeaders[key] = value;
}
-(void) removeDefaultHeaderForKey:(NSString*)key {
[self.mutableDefaultHeaders removeObjectForKey:key];
}
- (NSString *)defaultHeaderForKey:(NSString *)key {
return self.mutableDefaultHeaders[key];
}
- (NSDictionary *)defaultHeaders {
return [self.mutableDefaultHeaders copy];
}
@end

View File

@ -105,8 +105,6 @@
/**
* Sets the prefix for API key
*
* To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil.
*
* @param apiKeyPrefix API key prefix.
* @param identifier API key identifier.
*/
@ -139,4 +137,29 @@
*/
- (NSDictionary *) authSettings;
/**
* Default headers for all services
*/
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
/**
* Removes header from defaultHeaders
*
* @param Header name.
*/
-(void) removeDefaultHeaderForKey:(NSString*)key;
/**
* Sets the header for key
*
* @param value Value for header name
* @param key Header name
*/
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
/**
* @param Header key name.
*/
-(NSString*) defaultHeaderForKey:(NSString*)key;
@end

View File

@ -42,6 +42,7 @@ pod '{{podName}}', :path => 'Vendor/{{podName}}'
### Usage
Import the following:
```objc
#import <{{podName}}/{{{classPrefix}}}ApiClient.h>
#import <{{podName}}/{{{classPrefix}}}Configuration.h>
@ -81,12 +82,10 @@ Please follow the [installation procedure](#installation--usage) and then run th
{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/allParams}}
@try
{
{{classname}} *apiInstance = [[{{classname}} alloc] init];
{{classname}} *apiInstance = [[{{classname}} alloc] init];
{{#summary}} // {{{.}}}
{{/summary}} [apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) {
{{#returnType}}
@ -98,12 +97,6 @@ Please follow the [installation procedure](#installation--usage) and then run th
NSLog(@"Error: %@", error);
}
}];
}
@catch (NSException *exception)
{
NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name);
NSLog(@"Reason: %@ ", exception.reason);
}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```

View File

@ -6,12 +6,17 @@
{{newline}}
@interface {{classname}} ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end
@implementation {{classname}}
static {{classname}}* singletonAPI = nil;
NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain";
NSInteger k{{classname}}MissingParamErrorCode = 234513;
@synthesize apiClient = _apiClient;
#pragma mark - Initialize methods
@ -22,48 +27,45 @@ static {{classname}}* singletonAPI = nil;
if (config.apiClient == nil) {
config.apiClient = [[{{classPrefix}}ApiClient alloc] init];
}
self.apiClient = config.apiClient;
self.defaultHeaders = [NSMutableDictionary dictionary];
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
- (instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient {
- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient {
self = [super init];
if (self) {
self.apiClient = apiClient;
self.defaultHeaders = [NSMutableDictionary dictionary];
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
if (singletonAPI == nil) {
singletonAPI = [[{{classname}} alloc] init];
[singletonAPI addHeader:headerValue forKey:key];
}
return singletonAPI;
+ (instancetype)sharedAPI {
static {{classname}} *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
+({{classname}}*) sharedAPI {
if (singletonAPI == nil) {
singletonAPI = [[{{classname}} alloc] init];
}
return singletonAPI;
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
}
-(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
}
-(unsigned long) requestQueueSize {
-(NSUInteger) requestQueueSize {
return [{{classPrefix}}ApiClient requestQueueSize];
}
@ -84,7 +86,13 @@ static {{classname}}* singletonAPI = nil;
{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == nil) {
[NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"];
NSParameterAssert({{paramName}});
if(handler) {
NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] };
NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo];
handler({{#returnType}}nil, {{/returnType}}error);
}
return nil;
}
{{/required}}
@ -110,13 +118,12 @@ static {{classname}}* singletonAPI = nil;
{{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}}
}
{{/queryParams}}
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders];
[headerParams addEntriesFromDictionary:self.defaultHeaders];
{{#headerParams}}
if ({{paramName}} != nil) {
headerParams[@"{{baseName}}"] = {{paramName}};
}
{{/headerParams}}
// HTTP header `Accept`
NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]];
@ -165,7 +172,9 @@ static {{classname}}* singletonAPI = nil;
responseContentType: responseContentType
responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}}
completionBlock: ^(id data, NSError *error) {
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
if(handler) {
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
}
}
];
}

View File

@ -1,10 +1,8 @@
#import <Foundation/Foundation.h>
{{#imports}}#import "{{import}}.h"
{{/imports}}
#import "{{classPrefix}}Object.h"
#import "{{classPrefix}}ApiClient.h"
#import "{{classPrefix}}Api.h"
{{newline}}
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
@ -12,15 +10,14 @@
*/
{{#operations}}
@interface {{classname}}: NSObject
@property(nonatomic, assign){{classPrefix}}ApiClient *apiClient;
@interface {{classname}}: NSObject <{{classPrefix}}Api>
extern NSString* k{{classname}}ErrorDomain;
extern NSInteger k{{classname}}MissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+({{classname}}*) sharedAPI;
{{#operation}}
/// {{{summary}}}
/// {{#notes}}{{{notes}}}{{/notes}}

View File

@ -0,0 +1,24 @@
#import <Foundation/Foundation.h>
#import "{{classPrefix}}Object.h"
#import "{{classPrefix}}ApiClient.h"
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
@protocol {{classPrefix}}Api <NSObject>
@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient;
-(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
-(NSString*) defaultHeaderForKey:(NSString*)key;
-(NSUInteger) requestQueueSize;
@end

View File

@ -42,29 +42,21 @@ Method | HTTP request | Description
{{#allParams}}{{{dataType}}} {{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/allParams}}
@try
{
{{classname}} *apiInstance = [[{{classname}} alloc] init];
{{classname}}*apiInstance = [[{{classname}} alloc] init];
{{#summary}} // {{{.}}}
{{/summary}} [apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
{{#summary}}// {{{.}}}
{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) {
{{#returnType}}
if (output) {
NSLog(@"%@", output);
}
if (output) {
NSLog(@"%@", output);
}
{{/returnType}}
if (error) {
NSLog(@"Error: %@", error);
}
}];
}
@catch (NSException *exception)
{
NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name);
NSLog(@"Reason: %@ ", exception.reason);
}
if (error) {
NSLog(@"Error calling {{classname}}->{{operationId}}: %@", error);
}
}];
```
### Parameters

View File

@ -27,11 +27,11 @@ To install the bindings via [Composer](http://getcomposer.org/), add the followi
"repositories": [
{
"type": "git",
"url": "https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}.git"
"url": "https://github.com/{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}.git"
}
],
"require": {
"{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}": "*@dev"
"{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}": "*@dev"
}
}
```

View File

@ -1,5 +1,5 @@
{
"name": "{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}",{{#artifactVersion}}
"name": "{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}",{{#artifactVersion}}
"version": "{{artifactVersion}}",{{/artifactVersion}}
"description": "{{description}}",
"keywords": [

View File

@ -0,0 +1,5 @@
certifi >= 14.05.14
six == 1.8.0
python_dateutil >= 2.5.3
setuptools >= 21.0.0
urllib3 >= 1.15.1

View File

@ -0,0 +1,5 @@
coverage>=4.0.3
nose>=1.3.7
pluggy>=0.3.1
py>=1.4.31
randomize>=0.13

View File

@ -0,0 +1,10 @@
[tox]
envlist = py27, py34
[testenv]
deps=-r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
commands=
nosetests \
[]

View File

@ -22,7 +22,7 @@ Method | HTTP request | Description
# load the gem
require '{{{gemName}}}'
{{#hasAuthMethods}}
# setup authorization
# setup authorization
{{{moduleName}}}.configure do |config|{{#authMethods}}{{#isBasic}}
# Configure HTTP basic authorization: {{{name}}}
config.username = 'YOUR USERNAME'

View File

@ -86,7 +86,7 @@
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)

View File

@ -28,7 +28,7 @@ git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote

View File

@ -216,7 +216,7 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}}
{{/isEnum}}
{{/vars}}
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class{{#vars}} &&
@ -224,7 +224,7 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}}
end
# @see the `==` method
# @param [Object] Object to be compared
# @param [Object] Object to be compared
def eql?(o)
self == o
end

View File

@ -16,6 +16,18 @@ extension {{projectName}}API {
/** {{description}} */{{/description}}
public class {{classname}}: APIBase {
{{#operation}}
{{#allParams}}
{{#isEnum}}
/**
enum for parameter {{paramName}}
*/
public enum {{{datatypeWithEnum}}}_{{operationId}}: String { {{#allowableValues}}{{#values}}
case {{enum}} = "{{raw}}"{{/values}}{{/allowableValues}}
}
{{/isEnum}}
{{/allParams}}
/**
{{#summary}}
{{{summary}}}
@ -23,7 +35,7 @@ public class {{classname}}: APIBase {
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- parameter completion: completion handler to receive the data and the error objects
*/
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) {
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) {
{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}).execute { (response, error) -> Void in
completion({{#returnType}}data: response?.body, {{/returnType}}error: error);
}
@ -37,7 +49,7 @@ public class {{classname}}: APIBase {
- parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- returns: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
*/
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pendingPromise()
{{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in
if let error = error {
@ -69,16 +81,16 @@ public class {{classname}}: APIBase {
- returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}}
*/
public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
public class func {{operationId}}WithRequestBuilder({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{{datatypeWithEnum}}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
{{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}}
path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}}
path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}}{{#isEnum}}.rawValue{{/isEnum}})", options: .LiteralSearch, range: nil){{/pathParams}}
let URLString = {{projectName}}API.basePath + path
{{#bodyParam}}
let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}}
let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}}
"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}}
"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^required}}?{{/required}}.rawValue{{/isEnum}}{{#hasMore}},{{/hasMore}}{{^hasMore}}
]{{/hasMore}}{{/queryParams}}
let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}}

View File

@ -20,7 +20,8 @@ public abstract class AbstractIntegrationTest {
protected abstract Map<String, String> configProperties();
@Test
// @wing328: ignore for the time being until we fix the error with the integration test
@Test(enabled = false)
public void generatesCorrectDirectoryStructure() throws IOException {
DefaultGenerator codeGen = new DefaultGenerator();
IntegrationTestPathsConfig integrationTestPathsConfig = getIntegrationTestPathsConfig();

View File

@ -0,0 +1,21 @@
package io.swagger.codegen.ignore;
import org.testng.annotations.Test;
public class CodegenIgnoreProcessorTest {
@Test
public void loadCodegenRules() throws Exception {
}
@Test
public void getInclusionRules() throws Exception {
}
@Test
public void getExclusionRules() throws Exception {
}
}

View File

@ -0,0 +1,70 @@
package io.swagger.codegen.ignore.rules;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.*;
public class FileRuleTest {
@Test
public void testMatchComplex() throws Exception {
// Arrange
final String definition = "path/to/**/complex/*.txt";
final String relativePath = "path/to/some/nested/complex/xyzzy.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "path"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "to"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.MATCH_ALL),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "complex"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".txt")
);
Rule rule = new FileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchComplex() throws Exception {
// Arrange
final String definition = "path/to/**/complex/*.txt";
final String relativePath = "path/to/some/nested/invalid/xyzzy.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "path"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "to"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.MATCH_ALL),
new Part(IgnoreLineParser.Token.TEXT, "complex"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".txt")
);
Rule rule = new FileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
}

View File

@ -0,0 +1,158 @@
package io.swagger.codegen.ignore.rules;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import static org.testng.Assert.*;
public class IgnoreLineParserTest {
private IgnoreLineParser.Token verifyInputToSingleToken(final String input, IgnoreLineParser.Token token) throws ParserException {
// Act
List<Part> result = IgnoreLineParser.parse(input);
// Assert
assertNotNull(result);
assertEquals(result.size(), 1);
IgnoreLineParser.Token actual = result.get(0).getToken();
assertEquals(actual, token);
return actual;
}
@Test
public void parseMatchAll() throws Exception {
verifyInputToSingleToken("**", IgnoreLineParser.Token.MATCH_ALL);
}
@Test
public void parseMatchAny() throws Exception {
verifyInputToSingleToken("*", IgnoreLineParser.Token.MATCH_ANY);
}
@Test(expectedExceptions = ParserException.class,
expectedExceptionsMessageRegExp = "Negation with no negated pattern\\.")
public void parseNegate() throws Exception {
verifyInputToSingleToken("!", IgnoreLineParser.Token.NEGATE);
// Assert
fail("Expected simple pattern '!' to throw a ParserException.");
}
@Test
public void parseComment() throws Exception {
// Arrange
final String input = "# This is a comment";
Part actual = null;
// Act
List<Part> result = IgnoreLineParser.parse(input);
// Assert
assertEquals(result.size(), 1);
actual = result.get(0);
assertEquals(actual.getToken(), IgnoreLineParser.Token.COMMENT);
assertEquals(actual.getValue(), input);
}
@Test
public void parseEscapedExclamation() throws Exception {
final String input = "\\!";
verifyInputToSingleToken(input, IgnoreLineParser.Token.ESCAPED_EXCLAMATION);
}
@Test
public void parseEscapedSpace() throws Exception {
final String input = "\\ ";
verifyInputToSingleToken(input, IgnoreLineParser.Token.ESCAPED_SPACE);
}
@Test
public void parseDirectoryMarker() throws Exception {
// Arrange
final String input = "foo/";
Part actual = null;
// Act
List<Part> result = IgnoreLineParser.parse(input);
// Assert
assertEquals(result.size(), 2);
actual = result.get(0);
assertEquals(actual.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(actual.getValue(), "foo");
actual = result.get(1);
assertEquals(actual.getToken(), IgnoreLineParser.Token.DIRECTORY_MARKER);
}
@Test
public void parseRooted() throws Exception {
// Arrange
final String input = "/abcd";
Part actual = null;
// Act
List<Part> result = IgnoreLineParser.parse(input);
// Assert
assertEquals(result.size(), 2);
actual = result.get(0);
assertEquals(actual.getToken(), IgnoreLineParser.Token.ROOTED_MARKER);
actual = result.get(1);
assertEquals(actual.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(actual.getValue(), "abcd");
}
@Test
public void parseComplex() throws Exception {
// Arrange
final String input = "**/abcd/**/foo/bar/sample.txt";
Part current = null;
// Act
Queue<Part> result = new LinkedList<>(IgnoreLineParser.parse(input));
// Assert
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.MATCH_ALL);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(current.getValue(), "abcd");
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.MATCH_ALL);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(current.getValue(), "foo");
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(current.getValue(), "bar");
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.PATH_DELIM);
current = result.remove();
assertEquals(current.getToken(), IgnoreLineParser.Token.TEXT);
assertEquals(current.getValue(), "sample.txt");
}
@Test(expectedExceptions = ParserException.class,
expectedExceptionsMessageRegExp = "The pattern \\*\\*\\* is invalid\\.")
public void parseTripleStarPattern() throws Exception {
// Arrange
final String input = "should/throw/***/anywhere";
// Act
List<Part> result = IgnoreLineParser.parse(input);
// Assert
fail("Expected pattern containing '***' to throw a ParserException.");
}
}

View File

@ -0,0 +1,285 @@
package io.swagger.codegen.ignore.rules;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.*;
public class RootedFileRuleTest {
@Test
public void testMatchFilenameOnly() throws Exception {
// Arrange
final String definition = "/foo";
final String relativePath = "foo";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchFilenameOnly() throws Exception {
// Arrange
final String definition = "/foo";
final String relativePath = "bar";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
@Test
public void testMatchFilenameAndExtension() throws Exception {
// Arrange
final String definition = "/foo.txt";
final String relativePath = "foo.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchFilenameAndExtension() throws Exception {
// Arrange
final String definition = "/foo.txt";
final String relativePath = "bar.baz";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
@Test
public void testMatchFilenameWithGlob() throws Exception {
// Arrange
final String definition = "/foo*";
final String relativePath = "foobarbaz";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY)
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchFilenameWithGlob() throws Exception {
// Arrange
final String definition = "/foo*";
final String relativePath = "boobarbaz";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY)
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
@Test
public void testMatchFilenameAndExtensionWithFilenameGlob() throws Exception {
// Arrange
final String definition = "/foo*.txt";
final String relativePath = "foobarbaz.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchFilenameAndExtensionWithFilenameGlob() throws Exception {
// Arrange
final String definition = "/foo*qux.txt";
final String relativePath = "foobarbaz.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, "qux.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
@Test
public void testMatchFilenameAndExtensionWithExtensionGlob() throws Exception {
// Arrange
final String definition = "/foo.*";
final String relativePath = "foo.bak";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo."),
new Part(IgnoreLineParser.Token.MATCH_ANY)
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testMatchFilenameAndExtensionWithMultiplePeriods() throws Exception {
// Arrange
final String definition = "/foo*.xyzzy.txt";
final String relativePath = "foo.bar.baz.xyzzy.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testNonMatchFilenameAndExtensionWithMultiplePeriods() throws Exception {
// Arrange
final String definition = "/foo*.xyzzy.txt";
final String relativePath = "foo.bar.baz.qux.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
@Test
public void testMatchWithoutLeadingForwardSlash() throws Exception {
// Arrange
final String definition = "foo*.xyzzy.txt";
final String relativePath = "foo.bar.baz.xyzzy.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "foo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertTrue(actual);
}
@Test
public void testMatchesOnlyRooted() throws Exception {
// Arrange
final String definition = "/path/to/some/foo*.xyzzy.txt";
final String relativePath = "foo.bar.baz.xyzzy.txt";
final List<Part> syntax = Arrays.asList(
new Part(IgnoreLineParser.Token.ROOTED_MARKER),
new Part(IgnoreLineParser.Token.TEXT, "path"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "to"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "some"),
new Part(IgnoreLineParser.Token.PATH_DELIM),
new Part(IgnoreLineParser.Token.TEXT, "oo"),
new Part(IgnoreLineParser.Token.MATCH_ANY),
new Part(IgnoreLineParser.Token.TEXT, ".xyzzy.txt")
);
Rule rule = new RootedFileRule(syntax, definition);
Boolean actual = null;
// Act
actual = rule.matches(relativePath);
// Assert
assertFalse(actual);
}
}

View File

@ -18,6 +18,8 @@ public class PhpClientOptionsProvider implements OptionsProvider {
public static final String SRC_BASE_PATH_VALUE = "libPhp";
public static final String COMPOSER_VENDOR_NAME_VALUE = "swaggerPhp";
public static final String COMPOSER_PROJECT_NAME_VALUE = "swagger-client-php";
public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp";
public static final String GIT_REPO_ID_VALUE = "git-swagger-client-php";
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
@Override
@ -37,7 +39,9 @@ public class PhpClientOptionsProvider implements OptionsProvider {
.put(PhpClientCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE)
.put(PhpClientCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE)
.put(PhpClientCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE)
.put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE)
.put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE)
.put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE)
.put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE)
.build();
}

View File

@ -42,8 +42,12 @@ public class PhpClientOptionsTest extends AbstractOptionsTest {
times = 1;
clientCodegen.setComposerVendorName(PhpClientOptionsProvider.COMPOSER_VENDOR_NAME_VALUE);
times = 1;
clientCodegen.setGitUserId(PhpClientOptionsProvider.GIT_USER_ID_VALUE);
times = 1;
clientCodegen.setComposerProjectName(PhpClientOptionsProvider.COMPOSER_PROJECT_NAME_VALUE);
times = 1;
clientCodegen.setGitRepoId(PhpClientOptionsProvider.GIT_REPO_ID_VALUE);
times = 1;
clientCodegen.setArtifactVersion(PhpClientOptionsProvider.ARTIFACT_VERSION_VALUE);
times = 1;
}};

View File

@ -562,7 +562,7 @@
<swagger-parser-version>1.0.19</swagger-parser-version>
<scala-version>2.11.1</scala-version>
<felix-version>2.3.4</felix-version>
<swagger-core-version>1.5.8</swagger-core-version>
<swagger-core-version>1.5.9</swagger-core-version>
<commons-io-version>2.4</commons-io-version>
<commons-cli-version>1.2</commons-cli-version>
<junit-version>4.8.1</junit-version>

View File

@ -0,0 +1,6 @@
#Mon May 16 21:00:11 CST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip

View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,6 @@
#Mon May 16 21:00:31 CST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip

160
samples/client/petstore/android/volley/gradlew vendored Executable file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
VisualStudioVersion = 12.0.0.0
MinimumVisualStudioVersion = 10.0.0.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{74456AF8-75EE-4ABC-97EB-CA96A472DD21}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}"
EndProject
@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.Build.0 = Debug|Any CPU
{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.ActiveCfg = Release|Any CPU
{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.Build.0 = Release|Any CPU
{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}.Release|Any CPU.Build.0 = Release|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU
{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c
- API version: 1.0.0
- SDK version: 1.0.0
- Build date: 2016-05-13T21:50:05.372+08:00
- Build date: 2016-05-16T15:24:50.194+08:00
- Build package: class io.swagger.codegen.languages.CSharpClientCodegen
## Frameworks supported

View File

@ -58,20 +58,22 @@ namespace IO.Swagger.Test
[Test]
public void TestEndpointParametersTest()
{
/* comment out the following as the endpiont is fake
// TODO: add unit test for the method 'TestEndpointParameters'
double? number = null; // TODO: replace null with proper value
double? _double = null; // TODO: replace null with proper value
string _string = null; // TODO: replace null with proper value
byte[] _byte = null; // TODO: replace null with proper value
int? integer = null; // TODO: replace null with proper value
int? int32 = null; // TODO: replace null with proper value
long? int64 = null; // TODO: replace null with proper value
float? _float = null; // TODO: replace null with proper value
double? number = 12.3; // TODO: replace null with proper value
double? _double = 34.5; // TODO: replace null with proper value
string _string = "charp test"; // TODO: replace null with proper value
byte[] _byte = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };; // TODO: replace null with proper value
int? integer = 3; // TODO: replace null with proper value
int? int32 = 2; // TODO: replace null with proper value
long? int64 = 1; // TODO: replace null with proper value
float? _float = 7.8F; // TODO: replace null with proper value
byte[] binary = null; // TODO: replace null with proper value
DateTime? date = null; // TODO: replace null with proper value
DateTime? date = null; // TODO: replace null with proper value
DateTime? dateTime = null; // TODO: replace null with proper value
string password = null; // TODO: replace null with proper value
instance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password);
*/
}

View File

@ -25,13 +25,59 @@ namespace IO.Swagger.Test
{
private PetApi instance;
private long petId = 11088;
/// <summary>
/// Create a Pet object
/// </summary>
private Pet createPet()
{
// create pet
Pet p = new Pet(Name: "Csharp test", PhotoUrls: new List<string> { "http://petstore.com/csharp_test" });
p.Id = petId;
//p.Name = "Csharp test";
p.Status = Pet.StatusEnum.Available;
// create Category object
Category category = new Category();
category.Id = 56;
category.Name = "sample category name2";
List<String> photoUrls = new List<String>(new String[] {"sample photoUrls"});
// create Tag object
Tag tag = new Tag();
tag.Id = petId;
tag.Name = "csharp sample tag name1";
List<Tag> tags = new List<Tag>(new Tag[] {tag});
p.Tags = tags;
p.Category = category;
p.PhotoUrls = photoUrls;
return p;
}
/// <summary>
/// Convert string to byte array
/// </summary>
private byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
instance = new PetApi();
instance = new PetApi();
// create pet
Pet p = createPet();
// add pet before testing
PetApi petApi = new PetApi("http://petstore.swagger.io/v2/");
petApi.AddPet (p);
}
/// <summary>
@ -40,7 +86,9 @@ namespace IO.Swagger.Test
[TearDown]
public void Cleanup()
{
// remove the pet after testing
PetApi petApi = new PetApi ();
petApi.DeletePet(petId, "test key");
}
/// <summary>
@ -59,10 +107,10 @@ namespace IO.Swagger.Test
[Test]
public void AddPetTest()
{
// TODO: add unit test for the method 'AddPet'
Pet body = null; // TODO: replace null with proper value
instance.AddPet(body);
// create pet
Pet p = createPet();
instance.AddPet(p);
}
/// <summary>
@ -71,11 +119,7 @@ namespace IO.Swagger.Test
[Test]
public void DeletePetTest()
{
// TODO: add unit test for the method 'DeletePet'
long? petId = null; // TODO: replace null with proper value
string apiKey = null; // TODO: replace null with proper value
instance.DeletePet(petId, apiKey);
// no need to test as it'c covered by Cleanup() already
}
/// <summary>
@ -84,10 +128,15 @@ namespace IO.Swagger.Test
[Test]
public void FindPetsByStatusTest()
{
// TODO: add unit test for the method 'FindPetsByStatus'
List<string> status = null; // TODO: replace null with proper value
var response = instance.FindPetsByStatus(status);
Assert.IsInstanceOf<List<Pet>> (response, "response is List<Pet>");
PetApi petApi = new PetApi ();
List<String> tagsList = new List<String>(new String[] {"available"});
List<Pet> listPet = petApi.FindPetsByTags (tagsList);
foreach (Pet pet in listPet) // Loop through List with foreach.
{
Assert.IsInstanceOf<Pet> (pet, "Response is a Pet");
Assert.AreEqual ("csharp sample tag name1", pet.Tags[0]);
}
}
/// <summary>
@ -96,8 +145,7 @@ namespace IO.Swagger.Test
[Test]
public void FindPetsByTagsTest()
{
// TODO: add unit test for the method 'FindPetsByTags'
List<string> tags = null; // TODO: replace null with proper value
List<string> tags = new List<String>(new String[] {"pet"});
var response = instance.FindPetsByTags(tags);
Assert.IsInstanceOf<List<Pet>> (response, "response is List<Pet>");
}
@ -108,22 +156,96 @@ namespace IO.Swagger.Test
[Test]
public void GetPetByIdTest()
{
// TODO: add unit test for the method 'GetPetById'
long? petId = null; // TODO: replace null with proper value
var response = instance.GetPetById(petId);
Assert.IsInstanceOf<Pet> (response, "response is Pet");
// set timeout to 10 seconds
Configuration c1 = new Configuration (timeout: 10000, userAgent: "TEST_USER_AGENT");
PetApi petApi = new PetApi (c1);
Pet response = petApi.GetPetById (petId);
Assert.IsInstanceOf<Pet> (response, "Response is a Pet");
Assert.AreEqual ("Csharp test", response.Name);
Assert.AreEqual (Pet.StatusEnum.Available, response.Status);
Assert.IsInstanceOf<List<Tag>> (response.Tags, "Response.Tags is a Array");
Assert.AreEqual (petId, response.Tags [0].Id);
Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name);
Assert.IsInstanceOf<List<String>> (response.PhotoUrls, "Response.PhotoUrls is a Array");
Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]);
Assert.IsInstanceOf<Category> (response.Category, "Response.Category is a Category");
Assert.AreEqual (56, response.Category.Id);
Assert.AreEqual ("sample category name2", response.Category.Name);
}
/// <summary>
/// Test GetPetByIdAsync
/// </summary>
[Test ()]
public void TestGetPetByIdAsync ()
{
PetApi petApi = new PetApi ();
var task = petApi.GetPetByIdAsync (petId);
Pet response = task.Result;
Assert.IsInstanceOf<Pet> (response, "Response is a Pet");
Assert.AreEqual ("Csharp test", response.Name);
Assert.AreEqual (Pet.StatusEnum.Available, response.Status);
Assert.IsInstanceOf<List<Tag>> (response.Tags, "Response.Tags is a Array");
Assert.AreEqual (petId, response.Tags [0].Id);
Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name);
Assert.IsInstanceOf<List<String>> (response.PhotoUrls, "Response.PhotoUrls is a Array");
Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]);
Assert.IsInstanceOf<Category> (response.Category, "Response.Category is a Category");
Assert.AreEqual (56, response.Category.Id);
Assert.AreEqual ("sample category name2", response.Category.Name);
}
/// <summary>
/// Test GetPetByIdAsyncWithHttpInfo
/// </summary>
[Test ()]
public void TestGetPetByIdAsyncWithHttpInfo ()
{
PetApi petApi = new PetApi ();
var task = petApi.GetPetByIdAsyncWithHttpInfo (petId);
Assert.AreEqual (200, task.Result.StatusCode);
Assert.IsTrue (task.Result.Headers.ContainsKey("Content-Type"));
Assert.AreEqual (task.Result.Headers["Content-Type"], "application/json");
Pet response = task.Result.Data;
Assert.IsInstanceOf<Pet> (response, "Response is a Pet");
Assert.AreEqual ("Csharp test", response.Name);
Assert.AreEqual (Pet.StatusEnum.Available, response.Status);
Assert.IsInstanceOf<List<Tag>> (response.Tags, "Response.Tags is a Array");
Assert.AreEqual (petId, response.Tags [0].Id);
Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name);
Assert.IsInstanceOf<List<String>> (response.PhotoUrls, "Response.PhotoUrls is a Array");
Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]);
Assert.IsInstanceOf<Category> (response.Category, "Response.Category is a Category");
Assert.AreEqual (56, response.Category.Id);
Assert.AreEqual ("sample category name2", response.Category.Name);
}
/// <summary>
/// Test UpdatePet
/// </summary>
[Test]
public void UpdatePetTest()
{
// TODO: add unit test for the method 'UpdatePet'
Pet body = null; // TODO: replace null with proper value
instance.UpdatePet(body);
// create pet
Pet p = createPet();
instance.UpdatePet(p);
}
/// <summary>
@ -132,12 +254,24 @@ namespace IO.Swagger.Test
[Test]
public void UpdatePetWithFormTest()
{
// TODO: add unit test for the method 'UpdatePetWithForm'
long? petId = null; // TODO: replace null with proper value
string name = null; // TODO: replace null with proper value
string status = null; // TODO: replace null with proper value
instance.UpdatePetWithForm(petId, name, status);
PetApi petApi = new PetApi ();
petApi.UpdatePetWithForm (petId, "new form name", "pending");
Pet response = petApi.GetPetById (petId);
Assert.IsInstanceOf<Pet> (response, "Response is a Pet");
Assert.IsInstanceOf<Category> (response.Category, "Response.Category is a Category");
Assert.IsInstanceOf<List<Tag>> (response.Tags, "Response.Tags is a Array");
Assert.AreEqual ("new form name", response.Name);
Assert.AreEqual (Pet.StatusEnum.Pending, response.Status);
Assert.AreEqual (petId, response.Tags [0].Id);
Assert.AreEqual (56, response.Category.Id);
// test optional parameter
petApi.UpdatePetWithForm (petId, "new form name2");
Pet response2 = petApi.GetPetById (petId);
Assert.AreEqual ("new form name2", response2.Name);
}
/// <summary>
@ -146,13 +280,45 @@ namespace IO.Swagger.Test
[Test]
public void UploadFileTest()
{
// TODO: add unit test for the method 'UploadFile'
long? petId = null; // TODO: replace null with proper value
string additionalMetadata = null; // TODO: replace null with proper value
System.IO.Stream file = null; // TODO: replace null with proper value
var response = instance.UploadFile(petId, additionalMetadata, file);
Assert.IsInstanceOf<ApiResponse> (response, "response is ApiResponse");
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream _imageStream = _assembly.GetManifestResourceStream("IO.Swagger.Test.swagger-logo.png");
PetApi petApi = new PetApi ();
// test file upload with form parameters
petApi.UploadFile(petId, "new form name", _imageStream);
// test file upload without any form parameters
// using optional parameter syntax introduced at .net 4.0
petApi.UploadFile(petId: petId, file: _imageStream);
}
/// <summary>
/// Test status code
/// </summary>
[Test ()]
public void TestStatusCodeAndHeader ()
{
PetApi petApi = new PetApi ();
var response = petApi.GetPetByIdWithHttpInfo (petId);
Assert.AreEqual (response.StatusCode, 200);
Assert.IsTrue (response.Headers.ContainsKey("Content-Type"));
Assert.AreEqual (response.Headers["Content-Type"], "application/json");
}
/// <summary>
/// Test default header (should be deprecated
/// </summary>
[Test ()]
public void TestDefaultHeader ()
{
PetApi petApi = new PetApi ();
// commented out the warning test below as it's confirmed the warning is working as expected
// there should be a warning for using AddDefaultHeader (deprecated) below
//petApi.AddDefaultHeader ("header_key", "header_value");
// the following should be used instead as suggested in the doc
petApi.Configuration.AddDefaultHeader ("header_key2", "header_value2");
}
}

View File

@ -6,6 +6,7 @@ using System.Linq;
using System.Reflection;
using RestSharp;
using NUnit.Framework;
using Newtonsoft.Json;
using IO.Swagger.Client;
using IO.Swagger.Api;
@ -60,8 +61,8 @@ namespace IO.Swagger.Test
public void DeleteOrderTest()
{
// TODO: add unit test for the method 'DeleteOrder'
string orderId = null; // TODO: replace null with proper value
instance.DeleteOrder(orderId);
//string orderId = null; // TODO: replace null with proper value
//instance.DeleteOrder(orderId);
}
@ -72,8 +73,19 @@ namespace IO.Swagger.Test
public void GetInventoryTest()
{
// TODO: add unit test for the method 'GetInventory'
var response = instance.GetInventory();
Assert.IsInstanceOf<Dictionary<string, int?>> (response, "response is Dictionary<string, int?>");
//var response = instance.GetInventory();
//Assert.IsInstanceOf<Dictionary<string, int?>> (response, "response is Dictionary<string, int?>");
// set timeout to 10 seconds
Configuration c1 = new Configuration (timeout: 10000);
StoreApi storeApi = new StoreApi (c1);
Dictionary<String, int?> response = storeApi.GetInventory ();
foreach(KeyValuePair<string, int?> entry in response)
{
Assert.IsInstanceOf (typeof(int?), entry.Value);
}
}
/// <summary>
@ -83,9 +95,9 @@ namespace IO.Swagger.Test
public void GetOrderByIdTest()
{
// TODO: add unit test for the method 'GetOrderById'
long? orderId = null; // TODO: replace null with proper value
var response = instance.GetOrderById(orderId);
Assert.IsInstanceOf<Order> (response, "response is Order");
//long? orderId = null; // TODO: replace null with proper value
//var response = instance.GetOrderById(orderId);
//Assert.IsInstanceOf<Order> (response, "response is Order");
}
/// <summary>
@ -95,11 +107,41 @@ namespace IO.Swagger.Test
public void PlaceOrderTest()
{
// TODO: add unit test for the method 'PlaceOrder'
Order body = null; // TODO: replace null with proper value
var response = instance.PlaceOrder(body);
Assert.IsInstanceOf<Order> (response, "response is Order");
//Order body = null; // TODO: replace null with proper value
//var response = instance.PlaceOrder(body);
//Assert.IsInstanceOf<Order> (response, "response is Order");
}
/// <summary>
/// Test Enum
/// </summary>
[Test ()]
public void TestEnum ()
{
Assert.AreEqual (Order.StatusEnum.Approved.ToString(), "Approved");
}
/// <summary>
/// Test deserialization of JSON to Order and its readonly property
/// </summary>
[Test ()]
public void TesOrderDeserialization()
{
string json = @"{
'id': 1982,
'petId': 1020,
'quantity': 1,
'status': 'placed',
'complete': true,
}";
var o = JsonConvert.DeserializeObject<Order>(json);
Assert.AreEqual (1982, o.Id);
Assert.AreEqual (1020, o.PetId);
Assert.AreEqual (1, o.Quantity);
Assert.AreEqual (Order.StatusEnum.Placed, o.Status);
Assert.AreEqual (true, o.Complete);
}
}
}

View File

@ -60,8 +60,8 @@ namespace IO.Swagger.Test
public void CreateUserTest()
{
// TODO: add unit test for the method 'CreateUser'
User body = null; // TODO: replace null with proper value
instance.CreateUser(body);
//User body = null; // TODO: replace null with proper value
//instance.CreateUser(body);
}
@ -72,8 +72,8 @@ namespace IO.Swagger.Test
public void CreateUsersWithArrayInputTest()
{
// TODO: add unit test for the method 'CreateUsersWithArrayInput'
List<User> body = null; // TODO: replace null with proper value
instance.CreateUsersWithArrayInput(body);
//List<User> body = null; // TODO: replace null with proper value
//instance.CreateUsersWithArrayInput(body);
}
@ -84,8 +84,8 @@ namespace IO.Swagger.Test
public void CreateUsersWithListInputTest()
{
// TODO: add unit test for the method 'CreateUsersWithListInput'
List<User> body = null; // TODO: replace null with proper value
instance.CreateUsersWithListInput(body);
//List<User> body = null; // TODO: replace null with proper value
//instance.CreateUsersWithListInput(body);
}
@ -96,8 +96,8 @@ namespace IO.Swagger.Test
public void DeleteUserTest()
{
// TODO: add unit test for the method 'DeleteUser'
string username = null; // TODO: replace null with proper value
instance.DeleteUser(username);
//string username = null; // TODO: replace null with proper value
//instance.DeleteUser(username);
}
@ -108,9 +108,9 @@ namespace IO.Swagger.Test
public void GetUserByNameTest()
{
// TODO: add unit test for the method 'GetUserByName'
string username = null; // TODO: replace null with proper value
var response = instance.GetUserByName(username);
Assert.IsInstanceOf<User> (response, "response is User");
//string username = null; // TODO: replace null with proper value
//var response = instance.GetUserByName(username);
//Assert.IsInstanceOf<User> (response, "response is User");
}
/// <summary>
@ -120,10 +120,10 @@ namespace IO.Swagger.Test
public void LoginUserTest()
{
// TODO: add unit test for the method 'LoginUser'
string username = null; // TODO: replace null with proper value
string password = null; // TODO: replace null with proper value
var response = instance.LoginUser(username, password);
Assert.IsInstanceOf<string> (response, "response is string");
//string username = null; // TODO: replace null with proper value
//string password = null; // TODO: replace null with proper value
//var response = instance.LoginUser(username, password);
//Assert.IsInstanceOf<string> (response, "response is string");
}
/// <summary>
@ -133,7 +133,7 @@ namespace IO.Swagger.Test
public void LogoutUserTest()
{
// TODO: add unit test for the method 'LogoutUser'
instance.LogoutUser();
//instance.LogoutUser();
}
@ -144,9 +144,9 @@ namespace IO.Swagger.Test
public void UpdateUserTest()
{
// TODO: add unit test for the method 'UpdateUser'
string username = null; // TODO: replace null with proper value
User body = null; // TODO: replace null with proper value
instance.UpdateUser(username, body);
//string username = null; // TODO: replace null with proper value
//User body = null; // TODO: replace null with proper value
//instance.UpdateUser(username, body);
}

View File

@ -3,17 +3,22 @@ using System;
using System.Collections.Generic;
using IO.Swagger.Client;
using IO.Swagger.Api;
using IO.Swagger.Model;
namespace SwaggerClientTest.TestApiClient
namespace IO.Swagger.Test
{
public class TestApiClient
public class ApiClientTests
{
[TearDown()]
public void TearDown()
{
// Reset to default, just in case
Configuration.Default.DateTimeFormat = "o";
}
public ApiClientTests ()
{
}
[TearDown()]
public void TearDown()
{
// Reset to default, just in case
Configuration.Default.DateTimeFormat = "o";
}
/// <summary>
/// Test SelectHeaderContentType
@ -35,7 +40,7 @@ namespace SwaggerClientTest.TestApiClient
/// <summary>
/// Test ParameterToString
/// </summary>
[Test ()]
[Test ()]
public void TestParameterToString ()
{
ApiClient api = new ApiClient ();
@ -49,8 +54,8 @@ namespace SwaggerClientTest.TestApiClient
Assert.AreEqual("1,37", api.ParameterToString (numList));
}
[Test ()]
public void TestParameterToStringForDateTime ()
[Test ()]
public void TestParameterToStringForDateTime ()
{
ApiClient api = new ApiClient ();
@ -68,34 +73,34 @@ namespace SwaggerClientTest.TestApiClient
public void TestParameterToStringWithTimeZoneForDateTime ()
{
ApiClient api = new ApiClient ();
// test datetime with a time zone
DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz));
}
// test datetime with a time zone
DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz));
}
[Test ()]
public void TestParameterToStringForDateTimeWithUFormat ()
{
// Setup the DateTimeFormat across all of the calls
Configuration.Default.DateTimeFormat = "u";
ApiClient api = new ApiClient();
// test datetime
DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc));
}
[Test ()]
public void TestParameterToStringForDateTimeWithUFormat ()
{
// Setup the DateTimeFormat across all of the calls
Configuration.Default.DateTimeFormat = "u";
ApiClient api = new ApiClient();
[Test ()]
public void TestParameterToStringForDateTimeWithCustomFormat ()
{
// Setup the DateTimeFormat across all of the calls
Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss";
ApiClient api = new ApiClient();
// test datetime
DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc));
}
// test datetime
DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc));
}
[Test ()]
public void TestParameterToStringForDateTimeWithCustomFormat ()
{
// Setup the DateTimeFormat across all of the calls
Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss";
ApiClient api = new ApiClient();
// test datetime
DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc));
}
[Test ()]
public void TestSanitizeFilename ()
@ -104,7 +109,7 @@ namespace SwaggerClientTest.TestApiClient
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("../sun.gif"));
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("/var/tmp/sun.gif"));
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("./sun.gif"));
Assert.AreEqual("sun", ApiClient.SanitizeFilename("sun"));
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("..\\sun.gif"));
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename("\\var\\tmp\\sun.gif"));
@ -140,6 +145,5 @@ namespace SwaggerClientTest.TestApiClient
Assert.AreNotSame(p4.Configuration.ApiClient, Configuration.Default.ApiClient);
}
}
}
}
}

View File

@ -5,16 +5,20 @@ using IO.Swagger.Client;
using IO.Swagger.Api;
using IO.Swagger.Model;
namespace SwaggerClientTest.TestConfiguration
namespace IO.Swagger.Test
{
public class TestConfiguration
public class ConfigurationTests
{
[TearDown ()]
public void TearDown ()
{
// Reset to default, just in case
Configuration.Default.DateTimeFormat = "o";
}
public ConfigurationTests ()
{
}
[TearDown ()]
public void TearDown ()
{
// Reset to default, just in case
Configuration.Default.DateTimeFormat = "o";
}
[Test ()]
public void TestAuthentication ()
@ -39,21 +43,21 @@ namespace SwaggerClientTest.TestConfiguration
Assert.AreNotSame (p.Configuration, Configuration.Default);
}
[Test ()]
public void TestDateTimeFormat_Default ()
{
// Should default to the Round-trip Format Specifier - "o"
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
Assert.AreEqual("o", Configuration.Default.DateTimeFormat);
}
[Test ()]
public void TestDateTimeFormat_Default ()
{
// Should default to the Round-trip Format Specifier - "o"
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
Assert.AreEqual("o", Configuration.Default.DateTimeFormat);
}
[Test ()]
public void TestDateTimeFormat_UType()
{
Configuration.Default.DateTimeFormat = "u";
[Test ()]
public void TestDateTimeFormat_UType()
{
Configuration.Default.DateTimeFormat = "u";
Assert.AreEqual("u", Configuration.Default.DateTimeFormat);
}
Assert.AreEqual("u", Configuration.Default.DateTimeFormat);
}
[Test ()]
public void TestConstructor()
@ -64,7 +68,7 @@ namespace SwaggerClientTest.TestConfiguration
}
[Test ()]
[Test ()]
public void TestDefautlConfiguration ()
{
PetApi p1 = new PetApi ();
@ -110,14 +114,16 @@ namespace SwaggerClientTest.TestConfiguration
[Test ()]
public void TestTimeout ()
{
Configuration c1 = new Configuration();
Assert.AreEqual(100000, c1.Timeout); // default vaue
Configuration c1 = new Configuration ();
Assert.AreEqual (100000, c1.Timeout); // default vaue
c1.Timeout = 50000;
Assert.AreEqual(50000, c1.Timeout);
Assert.AreEqual (50000, c1.Timeout);
Configuration c2 = new Configuration(timeout: 20000);
Assert.AreEqual(20000, c2.Timeout);
Configuration c2 = new Configuration (timeout: 20000);
Assert.AreEqual (20000, c2.Timeout);
}
}
}
}

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@ -38,36 +38,43 @@
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" />
<Reference Include="Newtonsoft.Json">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RestSharp">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('$(SolutionDir)\packages')">$(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\packages')">..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\packages')">..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
<HintPath Condition="Exists('..\..\vendor')">..\..\vendor\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="**\*.cs"/>
<Compile Include="**\*.cs" />
<Compile Include="Client\ApiClientTests.cs" />
<Compile Include="Client\ConfigurationTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MsBuildToolsPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\IO.Swagger\IO.Swagger.csproj">
<Project>{74456AF8-75EE-4ABC-97EB-CA96A472DD21}</Project>
<Name>IO.Swagger</Name>
</ProjectReference>
<ProjectReference Include="..\IO.Swagger\IO.Swagger.csproj">
<Project>{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}</Project>
<Name>IO.Swagger</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="swagger-logo.png" />
</ItemGroup>
<ItemGroup>
<Folder Include="Client\" />
</ItemGroup>
</Project>

View File

@ -29,7 +29,7 @@ namespace IO.Swagger.Test
[SetUp]
public void Init()
{
instance = new Animal();
instance = new Animal(ClassName: "csharp test");
}
/// <summary>

View File

@ -29,7 +29,7 @@ namespace IO.Swagger.Test
[SetUp]
public void Init()
{
instance = new Cat();
instance = new Cat(ClassName: "csharp test");
}
/// <summary>

View File

@ -29,7 +29,7 @@ namespace IO.Swagger.Test
[SetUp]
public void Init()
{
instance = new Dog();
instance = new Dog(ClassName: "csharp test");
}
/// <summary>

View File

@ -50,6 +50,22 @@ namespace IO.Swagger.Test
Assert.IsInstanceOf<EnumClass> (instance, "instance is a EnumClass");
}
/// <summary>
/// Test EnumClass
/// </summary>
[Test]
public void EnumClassValueTest ()
{
// test serialization for string
Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumClass.Abc), "\"_abc\"");
// test serialization for number
Assert.AreEqual (Newtonsoft.Json.JsonConvert.SerializeObject(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1), "\"-1\"");
// test cast to int
Assert.AreEqual ((int)EnumTest.EnumIntegerEnum.NUMBER_MINUS_1, -1);
}
}

View File

@ -29,7 +29,7 @@ namespace IO.Swagger.Test
[SetUp]
public void Init()
{
instance = new FormatTest();
instance = new FormatTest(Number: 123, _Byte: new byte[] { 0x20 }, Date: new DateTime(2015, 1, 18), Password: "xyz");
}
/// <summary>

View File

@ -29,7 +29,7 @@ namespace IO.Swagger.Test
[SetUp]
public void Init()
{
instance = new Name();
instance = new Name(_Name: 1, Property: "csharp");
}
/// <summary>

View File

@ -41,6 +41,16 @@ namespace IO.Swagger.Test
}
/// <summary>
/// Test creating a new instance of Order
/// </summary>
[Test ()]
public void TestNewOrder()
{
Order o = new Order ();
Assert.IsNull (o.Id);
}
/// <summary>
/// Test an instance of Order
/// </summary>

View File

@ -23,13 +23,15 @@ namespace IO.Swagger.Test
{
private Pet instance;
private long petId = 11088;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
instance = new Pet();
instance = new Pet(Name: "Csharp test", PhotoUrls: new List<string> { "http://petstore.com/csharp_test" });
}
/// <summary>
@ -99,6 +101,69 @@ namespace IO.Swagger.Test
// TODO: unit test for the property 'Status'
}
/// <summary>
/// Test Equal
/// </summary>
[Test ()]
public void TestEqual()
{
// create pet
Pet p1 = new Pet (Name: "Csharp test", PhotoUrls: new List<string> { "http://petstore.com/csharp_test" });
p1.Id = petId;
//p1.Name = "Csharp test";
p1.Status = Pet.StatusEnum.Available;
// create Category object
Category category1 = new Category ();
category1.Id = 56;
category1.Name = "sample category name2";
List<String> photoUrls1 = new List<String> (new String[] { "sample photoUrls" });
// create Tag object
Tag tag1 = new Tag ();
tag1.Id = petId;
tag1.Name = "csharp sample tag name1";
List<Tag> tags1 = new List<Tag> (new Tag[] { tag1 });
p1.Tags = tags1;
p1.Category = category1;
p1.PhotoUrls = photoUrls1;
// create pet 2
Pet p2 = new Pet (Name: "Csharp test", PhotoUrls: new List<string> { "http://petstore.com/csharp_test" });
p2.Id = petId;
p2.Name = "Csharp test";
p2.Status = Pet.StatusEnum.Available;
// create Category object
Category category2 = new Category ();
category2.Id = 56;
category2.Name = "sample category name2";
List<String> photoUrls2 = new List<String> (new String[] { "sample photoUrls" });
// create Tag object
Tag tag2 = new Tag ();
tag2.Id = petId;
tag2.Name = "csharp sample tag name1";
List<Tag> tags2 = new List<Tag> (new Tag[] { tag2 });
p2.Tags = tags2;
p2.Category = category2;
p2.PhotoUrls = photoUrls2;
// p1 and p2 should be equal (both object and attribute level)
Assert.IsTrue (category1.Equals (category2));
Assert.IsTrue (tags1.SequenceEqual (tags2));
Assert.IsTrue (p1.PhotoUrls.SequenceEqual (p2.PhotoUrls));
Assert.IsTrue (p1.Equals (p2));
// update attribute to that p1 and p2 are not equal
category2.Name = "new category name";
Assert.IsFalse (category1.Equals (category2));
tags2 = new List<Tag> ();
Assert.IsFalse (tags1.SequenceEqual (tags2));
// photoUrls has not changed so it should be equal
Assert.IsTrue (p1.PhotoUrls.SequenceEqual (p2.PhotoUrls));
Assert.IsFalse (p1.Equals (p2));
}
}
}

View File

@ -3,7 +3,7 @@
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{74456AF8-75EE-4ABC-97EB-CA96A472DD21}</ProjectGuid>
<ProjectGuid>{1293D07E-F404-42B9-8BC7-0A4DAD18E83B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Swagger Library</RootNamespace>

View File

@ -38,8 +38,6 @@ namespace IO.Swagger.Model
{
this.ClassName = ClassName;
}
// use default value if no "Color" provided
if (Color == null)
{
@ -49,7 +47,6 @@ namespace IO.Swagger.Model
{
this.Color = Color;
}
}
/// <summary>
@ -71,7 +68,7 @@ namespace IO.Swagger.Model
var sb = new StringBuilder();
sb.Append("class Animal {\n");
sb.Append(" ClassName: ").Append(ClassName).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append("}\n");
return sb.ToString();
}

View File

@ -22,8 +22,6 @@ namespace IO.Swagger.Model
/// </summary>
public AnimalFarm()
{
}
/// <summary>
@ -34,7 +32,7 @@ namespace IO.Swagger.Model
{
var sb = new StringBuilder();
sb.Append("class AnimalFarm {\n");
sb.Append("}\n");
sb.Append("}\n");
return sb.ToString();
}

View File

@ -25,14 +25,9 @@ namespace IO.Swagger.Model
/// <param name="Message">Message.</param>
public ApiResponse(int? Code = null, string Type = null, string Message = null)
{
this.Code = Code;
this.Type = Type;
this.Message = Message;
this.Code = Code;
this.Type = Type;
this.Message = Message;
}
/// <summary>
@ -59,8 +54,8 @@ namespace IO.Swagger.Model
var sb = new StringBuilder();
sb.Append("class ApiResponse {\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append("}\n");
return sb.ToString();
}

View File

@ -39,8 +39,6 @@ namespace IO.Swagger.Model
{
this.ClassName = ClassName;
}
// use default value if no "Color" provided
if (Color == null)
{
@ -50,9 +48,7 @@ namespace IO.Swagger.Model
{
this.Color = Color;
}
this.Declawed = Declawed;
this.Declawed = Declawed;
}
/// <summary>
@ -79,8 +75,8 @@ namespace IO.Swagger.Model
var sb = new StringBuilder();
sb.Append("class Cat {\n");
sb.Append(" ClassName: ").Append(ClassName).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Declawed: ").Append(Declawed).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Declawed: ").Append(Declawed).Append("\n");
sb.Append("}\n");
return sb.ToString();
}

View File

@ -24,12 +24,8 @@ namespace IO.Swagger.Model
/// <param name="Name">Name.</param>
public Category(long? Id = null, string Name = null)
{
this.Id = Id;
this.Name = Name;
this.Id = Id;
this.Name = Name;
}
/// <summary>
@ -51,7 +47,7 @@ namespace IO.Swagger.Model
var sb = new StringBuilder();
sb.Append("class Category {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}

View File

@ -39,8 +39,6 @@ namespace IO.Swagger.Model
{
this.ClassName = ClassName;
}
// use default value if no "Color" provided
if (Color == null)
{
@ -50,9 +48,7 @@ namespace IO.Swagger.Model
{
this.Color = Color;
}
this.Breed = Breed;
this.Breed = Breed;
}
/// <summary>
@ -79,8 +75,8 @@ namespace IO.Swagger.Model
var sb = new StringBuilder();
sb.Append("class Dog {\n");
sb.Append(" ClassName: ").Append(ClassName).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Breed: ").Append(Breed).Append("\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Breed: ").Append(Breed).Append("\n");
sb.Append("}\n");
return sb.ToString();
}

Some files were not shown because too many files have changed in this diff Show More