Merge remote-tracking branch 'origin/master' into 2.3.0

This commit is contained in:
wing328
2017-05-21 01:35:13 +08:00
122 changed files with 9124 additions and 162 deletions

View File

@@ -867,6 +867,7 @@ Swagger Codegen core team members are contributors who have been making signific
Here is a list of template creators:
* API Clients:
* Akka-Scala: @cchafer
* Apex: @asnelling
* Bash: @bkryza
* C++ REST: @Danielku15
* C# (.NET 2.0): @who

31
bin/apex-petstore.sh Executable file
View File

@@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/apex -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l apex -o samples/client/petstore/apex"
java $JAVA_OPTS -jar $executable $ags

10
bin/windows/apex-petstore.bat Executable file
View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l apex -o samples\client\petstore\apex
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -125,6 +125,9 @@ public class Generate implements Runnable {
@Option(name = {"--ignore-file-override"}, title = "ignore file override location", description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC)
private String ignoreFileOverride;
@Option(name = {"--remove-operation-id-prefix"}, title = "remove prefix of the operationId", description = CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DESC)
private Boolean removeOperationIdPrefix;
@Override
public void run() {
@@ -222,6 +225,10 @@ public class Generate implements Runnable {
configurator.setIgnoreFileOverride(ignoreFileOverride);
}
if (removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
applySystemPropertiesKvp(systemProperties, configurator);
applyInstantiationTypesKvp(instantiationTypes, configurator);
applyImportMappingsKvp(importMappings, configurator);

View File

@@ -108,6 +108,12 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(name="skipOverwrite", required=false)
private Boolean skipOverwrite;
/**
* Specifies if the existing files should be overwritten during the generation.
*/
@Parameter(name="removeOperationIdPrefix", required=false)
private Boolean removeOperationIdPrefix;
/**
* The package to use for generated api objects/classes
*/
@@ -283,6 +289,10 @@ public class CodeGenMojo extends AbstractMojo {
configurator.setSkipOverwrite(skipOverwrite);
}
if(removeOperationIdPrefix != null) {
configurator.setRemoveOperationIdPrefix(removeOperationIdPrefix);
}
if(isNotEmpty(inputSpec)) {
configurator.setInputSpec(inputSpec);
}

View File

@@ -171,6 +171,10 @@ public interface CodegenConfig {
void setSkipOverwrite(boolean skipOverwrite);
boolean isRemoveOperationIdPrefix();
void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix);
Map<String, String> supportedLibraries();
void setLibrary(String library);

View File

@@ -191,4 +191,6 @@ public class CodegenConstants {
public static final String IGNORE_FILE_OVERRIDE = "ignoreFileOverride";
public static final String IGNORE_FILE_OVERRIDE_DESC = "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation.";
public static final String REMOVE_OPERATION_ID_PREFIX = "removeOperationIdPrefix";
public static final String REMOVE_OPERATION_ID_PREFIX_DESC = "Remove prefix of operationId, e.g. config_getId => getId";
}

View File

@@ -102,6 +102,7 @@ public class DefaultCodegen {
protected List<SupportingFile> supportingFiles = new ArrayList<SupportingFile>();
protected List<CliOption> cliOptions = new ArrayList<CliOption>();
protected boolean skipOverwrite;
protected boolean removeOperationIdPrefix;
protected boolean supportsInheritance;
protected boolean supportsMixins;
protected Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
@@ -160,6 +161,11 @@ public class DefaultCodegen {
if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){
this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX));
}
if (additionalProperties.containsKey(CodegenConstants.REMOVE_OPERATION_ID_PREFIX)) {
this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties
.get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX).toString()));
}
}
// override with any special post-processing for all models
@@ -849,7 +855,7 @@ public class DefaultCodegen {
cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants
.ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString()));
//name formatting options
// name formatting options
cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, CodegenConstants
.ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue(Boolean.FALSE.toString()));
@@ -1982,6 +1988,13 @@ public class DefaultCodegen {
op.vendorExtensions = operation.getVendorExtensions();
String operationId = getOrGenerateOperationId(operation, path, httpMethod);
// remove prefix in operationId
if (removeOperationIdPrefix) {
int offset = operationId.indexOf('_');
if (offset > -1) {
operationId = operationId.substring(offset+1);
}
}
operationId = removeNonNameElementToCamelCase(operationId);
op.path = path;
op.operationId = toOperationId(operationId);
@@ -3194,6 +3207,14 @@ public class DefaultCodegen {
this.skipOverwrite = skipOverwrite;
}
public boolean isRemoveOperationIdPrefix() {
return removeOperationIdPrefix;
}
public void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix;
}
/**
* All library templates supported.
* (key: library name, value: library description)

View File

@@ -44,6 +44,7 @@ public class CodegenConfigurator implements Serializable {
private String outputDir;
private boolean verbose;
private boolean skipOverwrite;
private boolean removeOperationIdPrefix;
private String templateDir;
private String auth;
private String apiPackage;
@@ -116,6 +117,15 @@ public class CodegenConfigurator implements Serializable {
return this;
}
public boolean getRemoveOperationIdPrefix() {
return removeOperationIdPrefix;
}
public CodegenConfigurator setRemoveOperationIdPrefix(boolean removeOperationIdPrefix) {
this.removeOperationIdPrefix = removeOperationIdPrefix;
return this;
}
public String getModelNameSuffix() {
return modelNameSuffix;
}
@@ -383,6 +393,7 @@ public class CodegenConfigurator implements Serializable {
config.setOutputDir(outputDir);
config.setSkipOverwrite(skipOverwrite);
config.setIgnoreFilePathOverride(ignoreFileOverride);
config.setRemoveOperationIdPrefix(removeOperationIdPrefix);
config.instantiationTypes().putAll(instantiationTypes);
config.typeMapping().putAll(typeMappings);

View File

@@ -0,0 +1,454 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
public class ApexClientCodegen extends AbstractJavaCodegen {
private static final String CLASS_PREFIX = "classPrefix";
private static final String API_VERSION = "apiVersion";
private static final Logger LOGGER = LoggerFactory.getLogger(ApexClientCodegen.class);
private String classPrefix = "Swag";
private String apiVersion = "36.0";
public ApexClientCodegen() {
super();
importMapping.clear();
embeddedTemplateDir = templateDir = "apex";
outputFolder = "generated-code" + File.separator + "apex";
testFolder = sourceFolder = "deploy";
apiPackage = "classes";
modelPackage = "classes";
testPackage = "deploy.classes";
modelNamePrefix = classPrefix;
dateLibrary = "";
apiTemplateFiles.put("api.mustache", ".cls");
apiTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
apiTestTemplateFiles.put("api_test.mustache", ".cls");
apiTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
modelTemplateFiles.put("model.mustache", ".cls");
modelTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
modelTestTemplateFiles.put("model_test.mustache", ".cls");
modelTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
cliOptions.add(CliOption.newString(CLASS_PREFIX, "Prefix for generated classes. Set this to avoid overwriting existing classes in your org."));
cliOptions.add(CliOption.newString(API_VERSION, "The Metadata API version number to use for components in this package."));
supportingFiles.add(new SupportingFile("package.mustache", "deploy", "package.xml"));
supportingFiles.add(new SupportingFile("package.mustache", "undeploy", "destructiveChanges.xml"));
supportingFiles.add(new SupportingFile("build.mustache", "build.xml"));
supportingFiles.add(new SupportingFile("build.properties", "build.properties"));
supportingFiles.add(new SupportingFile("remove.package.mustache", "undeploy", "package.xml"));
supportingFiles.add(new SupportingFile("Swagger.cls", "deploy/classes", "Swagger.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "Swagger.cls-meta.xml"));
supportingFiles.add(new SupportingFile("SwaggerTest.cls", "deploy/classes", "SwaggerTest.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "SwaggerTest.cls-meta.xml"));
supportingFiles.add(new SupportingFile("SwaggerResponseMock.cls", "deploy/classes", "SwaggerResponseMock.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "SwaggerResponseMock.cls-meta.xml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "README.md"));
typeMapping.put("BigDecimal", "Double");
typeMapping.put("binary", "String");
typeMapping.put("ByteArray", "Blob");
typeMapping.put("date", "Date");
typeMapping.put("DateTime", "Datetime");
typeMapping.put("file", "Blob");
typeMapping.put("float", "Double");
typeMapping.put("number", "Double");
typeMapping.put("short", "Integer");
typeMapping.put("UUID", "String");
setReservedWordsLowerCase(
Arrays.asList("abstract", "activate", "and", "any", "array", "as", "asc", "autonomous",
"begin", "bigdecimal", "blob", "break", "bulk", "by", "byte", "case", "cast",
"catch", "char", "class", "collect", "commit", "const", "continue",
"convertcurrency", "date", "decimal", "default", "delete", "desc", "do", "else",
"end", "enum", "exception", "exit", "export", "extends", "false", "final",
"finally", "float", "for", "from", "future", "global", "goto", "group", "having",
"hint", "if", "implements", "import", "inner", "insert", "instanceof", "int",
"interface", "into", "join", "last_90_days", "last_month", "last_n_days",
"last_week", "like", "limit", "list", "long", "loop", "map", "merge", "new",
"next_90_days", "next_month", "next_n_days", "next_week", "not", "null", "nulls",
"number", "object", "of", "on", "or", "outer", "override", "package", "parallel",
"pragma", "private", "protected", "public", "retrieve", "return", "returning",
"rollback", "savepoint", "search", "select", "set", "short", "sort", "stat",
"static", "super", "switch", "synchronized", "system", "testmethod", "then", "this",
"this_month", "this_week", "throw", "today", "tolabel", "tomorrow", "transaction",
"trigger", "true", "try", "type", "undelete", "update", "upsert", "using",
"virtual", "webservice", "when", "where", "while", "yesterday"
));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "ID",
"Integer", "Long", "Object", "String", "Time"
));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CLASS_PREFIX)) {
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
}
additionalProperties.put(CLASS_PREFIX, classPrefix);
if (additionalProperties.containsKey(API_VERSION)) {
setApiVersion(toApiVersion((String) additionalProperties.get(API_VERSION)));
}
additionalProperties.put(API_VERSION, apiVersion);
postProcessOpts();
}
@Override
public String escapeReservedWord(String name) {
// Identifiers must start with a letter
return "r" + super.escapeReservedWord(name);
}
@Override
public String toModelName(String name) {
String modelName = super.toModelName(name);
// Max length is 40; save the last 4 for "Test"
if (modelName.length() > 36) {
modelName = modelName.substring(0, 36);
}
return modelName;
}
@Override
public String toDefaultValue(Property p) {
String out = null;
if (p instanceof ArrayProperty) {
Property inner = ((ArrayProperty) p).getItems();
out = String.format(
"new List<%s>()",
inner == null ? "Object" : getTypeDeclaration(inner)
);
} else if (p instanceof BooleanProperty) {
// true => "true", false => "false", null => "null"
out = String.valueOf(((BooleanProperty) p).getDefault());
} else if (p instanceof LongProperty) {
Long def = ((LongProperty) p).getDefault();
out = def == null ? out : def.toString() + "L";
} else if (p instanceof MapProperty) {
Property inner = ((MapProperty) p).getAdditionalProperties();
String s = inner == null ? "Object" : getTypeDeclaration(inner);
out = String.format("new Map<String, %s>()", s);
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
String def = sp.getDefault();
if (def != null) {
out = sp.getEnum() == null ? String.format("'%s'", escapeText(def)) : def;
}
} else {
out = super.toDefaultValue(p);
}
// we'll skip over null defaults in the model template to avoid redundant initialization
return "null".equals(out) ? null : out;
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isLong)) {
p.example = "2147483648L";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "Blob.valueOf('Sample text file\\nContents')";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "Date.newInstance(1960, 2, 17)";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = "Datetime.newInstanceGmt(2013, 11, 12, 3, 3, 3)";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isString)) {
p.example = "'" + p.example + "'";
} else if ("".equals(p.example) || p.example == null) {
// Get an example object from the generated model
p.example = p.dataType + ".getExample()";
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel cm = super.fromModel(name, model, allDefinitions);
if (cm.interfaces == null) {
cm.interfaces = new ArrayList<String>();
}
Boolean hasDefaultValues = false;
// for (de)serializing properties renamed for Apex (e.g. reserved words)
List<Map<String, String>> propertyMappings = new ArrayList<>();
for (CodegenProperty p : cm.allVars) {
hasDefaultValues |= p.defaultValue != null;
if (!p.baseName.equals(p.name)) {
Map<String, String> mapping = new HashMap<>();
mapping.put("externalName", p.baseName);
mapping.put("internalName", p.name);
propertyMappings.add(mapping);
}
}
cm.vendorExtensions.put("hasPropertyMappings", !propertyMappings.isEmpty());
cm.vendorExtensions.put("hasDefaultValues", hasDefaultValues);
cm.vendorExtensions.put("propertyMappings", propertyMappings);
if (!propertyMappings.isEmpty()) {
cm.interfaces.add("Swagger.MappedProperties");
}
return cm;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
if (parameter.isBodyParam && parameter.isListContainer) {
// items of array bodyParams are being nested an extra level too deep for some reason
parameter.items = parameter.items.items;
setParameterExampleValue(parameter);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
String description = info.getDescription();
String sanitized = sanitizeName(info.getTitle());
additionalProperties.put("sanitizedName", sanitized);
supportingFiles.add(new SupportingFile("remoteSite.mustache", "deploy/remoteSiteSettings",
sanitized + ".remoteSite"
));
// max length for description for a Remote Site setting
if (description != null && description.length() > 255) {
description = description.substring(0, 255);
}
additionalProperties.put("shortDescription", description);
}
@Override
public CodegenOperation fromOperation(String path,
String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
Boolean hasFormParams = false;
for (Parameter p : operation.getParameters()) {
if ("formData".equals(p.getIn())) {
hasFormParams = true;
break;
}
}
// only support serialization into JSON and urlencoded forms for now
operation.setConsumes(
Collections.singletonList(hasFormParams
? "application/x-www-form-urlencoded"
: "application/json"));
// only support deserialization from JSON for now
operation.setProduces(Collections.singletonList("application/json"));
CodegenOperation op = super.fromOperation(
path, httpMethod, operation, definitions, swagger);
if (op.getHasExamples()) {
// prepare examples for Apex test classes
Property responseProperty = findMethodResponse(operation.getResponses()).getSchema();
String deserializedExample = toExampleValue(responseProperty);
for (Map<String, String> example : op.examples) {
example.put("example", escapeText(example.get("example")));
example.put("deserializedExample", deserializedExample);
}
}
return op;
}
@Override
public String escapeQuotationMark(String input) {
return input.replace("'", "\\'");
}
public void setClassPrefix(String classPrefix) {
// the best thing we can do without namespacing in Apex
modelNamePrefix = classPrefix;
this.classPrefix = classPrefix;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
private String toApiVersion(String apiVersion) {
if (apiVersion.matches("^\\d{2}(\\.0)?$")) {
return apiVersion.substring(0, 2) + ".0";
} else {
LOGGER.warn(String.format("specified API version is invalid: %s - defaulting to %s", apiVersion, this.apiVersion));
return this.apiVersion;
}
}
private void postProcessOpts() {
supportingFiles.add(
new SupportingFile("client.mustache", "deploy/classes", classPrefix + "Client.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes",
classPrefix + "Client.cls-meta.xml"
));
}
@Override
public String escapeText(String input) {
if (input == null) {
return input;
}
return input.replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r");
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + "Test";
}
@Override
public String toExampleValue(Property p) {
if (p == null) {
return "";
}
Object obj = p.getExample();
String example = obj == null ? "" : obj.toString();
if (p instanceof ArrayProperty) {
example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
((ArrayProperty) p).getItems()) + "}";
} else if (p instanceof BooleanProperty) {
example = String.valueOf(!"false".equals(example));
} else if (p instanceof ByteArrayProperty) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
}
((ByteArrayProperty) p).setExample(example);
example = "EncodingUtil.base64Decode('" + example + "')";
} else if (p instanceof DateProperty) {
if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p
.getName(), example));
example = "2000, 1, 23";
}
example = "Date.newInstance(" + example + ")";
} else if (p instanceof DateTimeProperty) {
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23, 4, 56, 7";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p
.getName(), example));
example = "2000, 1, 23, 4, 56, 7";
}
example = "Datetime.newInstanceGmt(" + example + ")";
} else if (p instanceof DecimalProperty) {
example = example.replaceAll("[^-0-9.]", "");
example = example.isEmpty() ? "1.3579" : example;
} else if (p instanceof FileProperty) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
((FileProperty) p).setExample(example);
}
example = "EncodingUtil.base64Decode(" + example + ")";
} else if (p instanceof EmailProperty) {
if (example.isEmpty()) {
example = "example@example.com";
((EmailProperty) p).setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof LongProperty) {
example = example.isEmpty() ? "123456789L" : example + "L";
} else if (p instanceof MapProperty) {
example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(
((MapProperty) p).getAdditionalProperties()) + "}";
} else if (p instanceof ObjectProperty) {
example = example.isEmpty() ? "null" : example;
} else if (p instanceof PasswordProperty) {
example = example.isEmpty() ? "password123" : escapeText(example);
((PasswordProperty) p).setExample(example);
example = "'" + example + "'";
} else if (p instanceof RefProperty) {
example = getTypeDeclaration(p) + ".getExample()";
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
List<String> enums = sp.getEnum();
if (enums != null && example.isEmpty()) {
example = enums.get(0);
sp.setExample(example);
} else if (example.isEmpty()) {
example = "aeiou";
} else {
example = escapeText(example);
sp.setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof UUIDProperty) {
example = example.isEmpty()
? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
: "'" + escapeText(example) + "'";
} else if (p instanceof BaseIntegerProperty) {
example = example.matches("^-?\\d+$") ? example : "123";
}
return example;
}
@Override
public String toApiName(String name) {
return camelize(classPrefix + super.toApiName(name));
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
super.updateCodegenPropertyEnum(var);
if (var.isEnum && var.example != null) {
String example = var.example.replace("'", "");
example = toEnumVarName(example, var.datatype);
var.example = toEnumDefaultValue(example, var.datatypeWithEnum);
}
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "apex";
}
@Override
public String getHelp() {
return "Generates an Apex API client library (beta).";
}
}

View File

@@ -56,7 +56,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// at the moment
importMapping.clear();
supportsInheritance = true;
outputFolder = "generated-code" + File.separator + "php";
modelTemplateFiles.put("model.mustache", ".php");

View File

@@ -27,8 +27,8 @@ import swagger.SwaggerUtils.ApiAction;
{{#operations}}
public class {{classname}}Controller extends Controller {
private {{classname}}ControllerImp imp;
private ObjectMapper mapper;
private final {{classname}}ControllerImp imp;
private final ObjectMapper mapper;
@Inject
private {{classname}}Controller({{classname}}ControllerImp imp) {
@@ -42,8 +42,7 @@ public class {{classname}}Controller extends Controller {
public Result {{operationId}}({{#pathParams}}{{>pathParams}}{{#hasMore}},{{/hasMore}}{{/pathParams}}) {{^handleExceptions}}{{#bodyParams}}throws IOException{{/bodyParams}}{{/handleExceptions}}{{#handleExceptions}}throws Exception{{/handleExceptions}} {
{{#bodyParams}}
{{#collectionFormat}}
//TODO: Maybe implement this in the future if we can support collection in the body params: see bug in swagger-play: https://github.com/swagger-api/swagger-play/issues/130
//TODO: Tt seems it is not detected that it's a list based on the collectionFormat field?
//TODO: Support this later
{{/collectionFormat}}
{{^collectionFormat}}
JsonNode node{{paramName}} = request().body().asJson();
@@ -60,9 +59,7 @@ public class {{classname}}Controller extends Controller {
{{/bodyParams}}
{{#queryParams}}
{{#collectionFormat}}
//TODO: Maybe implement this in the future if we can support collection in the body params: see bug in swagger-play: https://github.com/swagger-api/swagger-play/issues/130
//TODO: Tt seems it is not detected that it's a list based on the collectionFormat field?
//WIP when both bugs will be fixed
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", request().getQueryString("{{baseName}}"));
{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {
@@ -92,9 +89,7 @@ public class {{classname}}Controller extends Controller {
{{/notFile}}
{{#notFile}}
{{#collectionFormat}}
//TODO: Maybe implement this in the future if we can support collection in the body params: see bug in swagger-play: https://github.com/swagger-api/swagger-play/issues/130
//TODO: Tt seems it is not detected that it's a list based on the collectionFormat field?
//WIP when both bugs will be fixed
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", ((String[]) request().body().asMultipartFormData().asFormUrlEncoded().get("{{baseName}}"))[0]);
{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {
@@ -117,9 +112,7 @@ public class {{classname}}Controller extends Controller {
{{/formParams}}
{{#headerParams}}
{{#collectionFormat}}
//TODO: Maybe implement this in the future if we can support collection in the body params: see bug in swagger-play: https://github.com/swagger-api/swagger-play/issues/130
//TODO: Tt seems it is not detected that it's a list based on the collectionFormat field?
//WIP when both bugs will be fixed
//TODO: Support this later
//List<Pair> {{paramName}}Pair = SwaggerUtils.parameterToPairs("{{collectionFormat}}", "{{paramName}}", request().getHeader("{{baseName}}"));
//{{{dataType}}} {{paramName}} = new Array{{{dataType}}}();
//for (Pair pair : {{paramName}}Pair) {

View File

@@ -1 +1 @@
{{#isInteger}}0{{/isInteger}}{{#isDouble}}0.0{{/isDouble}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0{{/isFloat}}{{#isString}}""{{/isString}}
{{#isBoolean}}false{{/isBoolean}}{{#isInteger}}0{{/isInteger}}{{#isDouble}}0.0{{/isDouble}}{{#isLong}}0L{{/isLong}}{{#isFloat}}0.0{{/isFloat}}{{#isString}}""{{/isString}}

View File

@@ -1,4 +1,5 @@
io.swagger.codegen.languages.AndroidClientCodegen
io.swagger.codegen.languages.ApexClientCodegen
io.swagger.codegen.languages.AspNetCoreServerCodegen
io.swagger.codegen.languages.AsyncScalaClientCodegen
io.swagger.codegen.languages.BashClientCodegen
@@ -63,4 +64,4 @@ io.swagger.codegen.languages.GoServerCodegen
io.swagger.codegen.languages.ErlangServerCodegen
io.swagger.codegen.languages.UndertowCodegen
io.swagger.codegen.languages.JavaMSF4JServerCodegen
io.swagger.codegen.languages.ZendExpressivePathHandlerServerCodegen
io.swagger.codegen.languages.ZendExpressivePathHandlerServerCodegen

View File

@@ -0,0 +1,182 @@
# {{appName}} API Client
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## Requirements
- [Java 8 JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
- [Apache Ant](http://ant.apache.org/) version 1.6 or later
- [Force.com Migration Tool](https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_install.htm)
- The `ant-salesforce.jar` file included with the Force.com Migration Tool must be placed in the root directory of this project (in the same directory as this README and `build.xml`)
- `ANT_HOME` and `JAVA_HOME` environment variables must be set accordingly
- On Windows, `JAVA_HOME` will probably look something like this:
```
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_121
```
- The `bin` directory from Ant must be on your `PATH`
If everything is set correctly:
- Running `java -version` in a command prompt should output something like:
```bash
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
```
- Running `ant -version` should output something like:
```bash
Apache Ant(TM) version 1.10.1 compiled on February 2 2017
```
For more information, see <https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_prereq.htm>
## Installation
{{#gitRepoId}}{{#gitUserId}}
1. Clone the repo from GitHub
```bash
$ git clone git@github.com:{{gitUserId}}/{{gitRepoId}}.git
```
Or, [download](https://github.com/{{gitUserId}}/{{gitRepoId}}/archive/master.zip) the repo as a ZIP and extract it to `{{gitRepoId}}`
{{/gitUserId}}{{/gitRepoId}}
1. Set the `SF_USERNAME` and `SF_PASSWORD` environment variables to your Salesforce username and password. Alternatively, they may be set in `build.properties`. Environment variables will override the values in `build.properties` if set.
`SF_SESSIONID` may also be set instead of `SF_USERNAME` and `SF_PASSWORD` (more info in `build.properties`)
2. Open up a command prompt in the root project directory {{#gitRepoId}}`{{gitRepoId}}` {{/gitRepoId}}(the same directory as this README and `build.xml`)
3. Deploy to your Salesforce org
```bash
$ ant deploy
```
This command will:
- deploy all classes in the `deploy/classes` directory to your Salesforce org
- create a new [unmanaged package](https://help.salesforce.com/articleView?id=sharing_apps.htm) called **{{appName}} API Client**
- execute all of the unit tests included in this package (at least 75% code coverage required)
- create a new [remote site](https://help.salesforce.com/articleView?id=configuring_remoteproxy.htm) called **{{sanitizedName}}** configured for the endpoint: <{{basePath}}>
- rolls back any changes upon any error
A successful deployment will look like this:
```bash
[sf:deploy] Request Status: Succeeded
[sf:deploy] *********** DEPLOYMENT SUCCEEDED ***********
[sf:deploy] Finished request 0Af7A00000Ebd5oSAB successfully.
BUILD SUCCESSFUL
Total time: 34 seconds
```
### Test deployment only
To perform a test deployment without committing changes:
```bash
$ ant deployCheckOnly
```
All of the included tests will run as if it were a real deployment. Tests and other validations will report back while leaving your org untouched, allowing you to verify that a deployment will succeed without affecting anything in the org.
### Uninstallation
```bash
$ ant undeploy
```
Removes all classes and the Remote Site created by this package.
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Apex code:
```java{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
{{classname}} api = new {{classname}}();
{{#hasAuthMethods}}
{{classPrefix}}Client client = api.getClient();
{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setUsername('YOUR USERNAME');
{{{name}}}.setPassword('YOUR PASSWORD');
// You can also set your username and password in one line
{{{name}}}.setCredentials('YOUR USERNAME', 'YOUR PASSWORD');{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setApiKey('YOUR API KEY');{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Swagger.OAuth {{{name}}} = (Swagger.OAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setAccessToken('YOUR ACCESS TOKEN');{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{{paramName}}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
try {
// cross your fingers
{{#returnType}}{{{returnType}}} result = {{/returnType}}api.{{{operationId}}}({{#hasParams}}params{{/hasParams}});
{{#returnType}}
System.debug(result);
{{/returnType}}
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
{{/authMethods}}Authentication schemes defined for the API:
{{#authMethods}}### {{name}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorizatoin URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@@ -0,0 +1,395 @@
public class Swagger {
private static final String HEADER_CONTENT_TYPE = 'Content-Type';
private static final String HEADER_ACCEPT = 'Accept';
private static final String HEADER_ACCEPT_DELIMITER = ',';
private static final Map<String, String> DELIMITERS = new Map<String, String> {
'csv' => ',',
'ssv' => ' ',
'tsv' => '\t',
'pipes' => '|'
};
public class Param {
private String name, value;
public Param(String name, String value) {
this.name = name;
this.value = value;
}
public override String toString() {
return EncodingUtil.urlEncode(name, 'UTF-8') + '='
+ EncodingUtil.urlEncode(value, 'UTF-8');
}
}
public interface Authentication {
void apply(Map<String, Object> headers, List<Param> query);
}
public interface MappedProperties {
Map<String, String> getPropertyMappings();
}
public abstract class ApiKeyAuth implements Authentication {
protected final String paramName;
protected String key = '';
public void setApiKey(String key) {
this.key = key;
}
@TestVisible
private String getApiKey() {
return key;
}
}
public class ApiKeyQueryAuth extends ApiKeyAuth {
public ApiKeyQueryAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
query.add(new Param(paramName, key));
}
}
public class ApiKeyHeaderAuth extends ApiKeyAuth {
public ApiKeyHeaderAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put(paramName, key);
}
}
public class HttpBasicAuth implements Authentication {
private String username = '';
private String password = '';
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setCredentials(String username, String password) {
setUsername(username);
setPassword(password);
}
@TestVisible
private String getHeaderValue() {
return 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password));
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class OAuth2 implements Authentication {
private String accessToken = '';
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@TestVisible
private String getHeaderValue() {
return 'Bearer ' + accessToken;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class ApiException extends Exception {
private final Integer code;
private final String status;
private final Map<String, String> headers;
private final String body;
public ApiException(Integer code, String status, Map<String, String> headers, String body) {
this('API returned HTTP ' + code + ': ' + status);
this.code = code;
this.status = status;
this.headers = headers;
this.body = body;
}
public Integer getStatusCode() {
return code;
}
public String getStatus() {
return status;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}
public virtual class ApiClient {
protected String preferredContentType = 'application/json';
protected String preferredAccept = 'application/json';
protected final String basePath;
@TestVisible
protected final Map<String, Authentication> authentications = new Map<String, Authentication>();
public virtual Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
public virtual void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setCredentials(String username, String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setCredentials(username, password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new NoSuchElementException('No API key authentication configured!');
}
public virtual void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth2) {
((OAuth2) auth).setAccessToken(accessToken);
return;
}
}
throw new NoSuchElementException('No OAuth2 authentication configured!');
}
public List<Param> makeParams(String name, List<Object> values) {
List<Param> pairs = new List<Param>();
for (Object value : new List<Object>(values)) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public List<Param> makeParam(String name, List<Object> values, String format) {
List<Param> pairs = new List<Param>();
if (values != null) {
String delimiter = DELIMITERS.get(format);
pairs.add(new Param(name, String.join(values, delimiter)));
}
return pairs;
}
public List<Param> makeParam(String name, Object value) {
List<Param> pairs = new List<Param>();
if (value != null) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public virtual void assertNotNull(Object required, String parameterName) {
if (required == null) {
Exception e = new NullPointerException();
e.setMessage('Argument cannot be null: ' + parameterName);
throw e;
}
}
public virtual Object invoke(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods, Type returnType) {
HttpResponse res = getResponse(method, path, body, query, form, pathParams, headers,
accepts, contentTypes, authMethods);
Integer code = res.getStatusCode();
Boolean isFailure = code / 100 != 2;
if (isFailure) {
throw new ApiException(code, res.getStatus(), getHeaders(res), res.getBody());
} else if (returnType != null) {
return toReturnValue(res.getBody(), returnType, res.getHeader('Content-Type'));
}
return null;
}
@TestVisible
protected virtual Map<String, String> getHeaders(HttpResponse res) {
Map<String, String> headers = new Map<String, String>();
List<String> headerKeys = res.getHeaderKeys();
for (String headerKey : headerKeys) {
headers.put(headerKey, res.getHeader(headerKey));
}
return headers;
}
@TestVisible
protected virtual Object toReturnValue(String body, Type returnType, String contentType) {
if (contentType == 'application/json') {
Object o = returnType.newInstance();
if (o instanceof MappedProperties) {
Map<String, String> propertyMappings = ((MappedProperties) o).getPropertyMappings();
for (String baseName : propertyMappings.keySet()) {
body = body.replaceAll('"' + baseName + '"\\s*:',
'"' + propertyMappings.get(baseName) + '":');
}
}
JsonParser parser = Json.createParser(body);
parser.nextToken();
return parser.readValueAs(returnType);
}
return body;
}
@TestVisible
protected virtual HttpResponse getResponse(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods) {
HttpRequest req = new HttpRequest();
applyAuthentication(authMethods, headers, query);
req.setMethod(method);
req.setEndpoint(toEndpoint(path, pathParams, query));
String contentType = setContentTypeHeader(contentTypes, headers);
setAcceptHeader(accepts, headers);
setHeaders(req, headers);
if (method != 'GET') {
req.setBody(toBody(contentType, body, form));
}
return new Http().send(req);
}
@TestVisible
protected virtual void setHeaders(HttpRequest req, Map<String, Object> headers) {
for (String headerName : headers.keySet()) {
req.setHeader(headerName, String.valueOf(headers.get(headerName)));
}
}
@TestVisible
protected virtual String toBody(String contentType, Object body, List<Param> form) {
if (contentType.contains('application/x-www-form-urlencoded')) {
return paramsToString(form);
} else if (contentType.contains('application/json')) {
return Json.serialize(body);
}
return String.valueOf(body);
}
@TestVisible
protected virtual String setContentTypeHeader(List<String> contentTypes,
Map<String, Object> headers) {
if (contentTypes.isEmpty()) {
headers.put(HEADER_CONTENT_TYPE, preferredContentType);
return preferredContentType;
}
for (String contentType : contentTypes) {
if (preferredContentType == contentType) {
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
}
String contentType = contentTypes.get(0);
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
@TestVisible
protected virtual void setAcceptHeader(List<String> accepts, Map<String, Object> headers) {
for (String accept : accepts) {
if (preferredAccept == accept) {
headers.put(HEADER_ACCEPT, accept);
return;
}
}
if (!accepts.isEmpty()) {
headers.put(HEADER_ACCEPT, String.join(accepts, HEADER_ACCEPT_DELIMITER));
}
}
@TestVisible
protected virtual void applyAuthentication(List<String> names, Map<String, Object> headers,
List<Param> query) {
for (Authentication auth : getAuthMethods(names)) {
auth.apply(headers, query);
}
}
@TestVisible
protected virtual List<Authentication> getAuthMethods(List<String> names) {
List<Authentication> authMethods = new List<Authentication>();
for (String name : names) {
authMethods.add(authentications.get(name));
}
return authMethods;
}
@TestVisible
protected virtual String toPath(String path, Map<String, Object> params) {
String formatted = path;
for (String key : params.keySet()) {
formatted = formatted.replace('{' + key + '}', String.valueOf(params.get(key)));
}
return formatted;
}
@TestVisible
protected virtual String toEndpoint(String path, Map<String, Object> params,
List<Param> queryParams) {
String query = '?' + paramsToString(queryParams);
return basePath + toPath(path, params) + query.removeEnd('?');
}
@TestVisible
protected virtual String paramsToString(List<Param> params) {
String s = '';
for (Param p : params) {
s += '&' + p;
}
return s.removeStart('&');
}
}
}

View File

@@ -0,0 +1,18 @@
@isTest
public class SwaggerResponseMock implements HttpCalloutMock {
private final HttpResponse response;
private HttpRequest request;
public SwaggerResponseMock(HttpResponse response) {
this.response = response;
}
public HttpResponse respond(HttpRequest request) {
this.request = request;
return response;
}
public HttpRequest getRequest() {
return request;
}
}

View File

@@ -0,0 +1,782 @@
@isTest
private class SwaggerTest {
@isTest
private static void Param_urlEncodeKeyValuePairUtf8() {
String toEncodeLeft = 'Hello +%-_.!~*\'()@';
String toEncodeRight = 'World +%-_.!~*\'()@';
String expected = 'Hello+%2B%25-_.%21%7E*%27%28%29%40=World+%2B%25-_.%21%7E*%27%28%29%40';
String result = new Swagger.Param(toEncodeLeft, toEncodeRight).toString();
System.assertEquals(expected, result);
}
@isTest
private static void ApiKeyHeaderAuth_keyInHeaderWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyHeaderAuth auth = new Swagger.ApiKeyHeaderAuth('X-Authenticate');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authenticate'));
}
@isTest
private static void ApiKeyQueryAuth_keyInQueryParamWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyQueryAuth auth = new Swagger.ApiKeyQueryAuth('auth_token');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(headers.isEmpty());
System.assertEquals(1, query.size());
System.assertEquals('auth_token=foo-bar-api-key', query.get(0).toString());
}
@isTest
private static void HttpBasicAuth_base64EncodeCredentials() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setCredentials('username', 'password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void HttpBasicAuth_base64EncodeUsernamePassword() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setUsername('username');
auth.setPassword('password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void OAuth2_tokenInAuthorizationHeaderWithBearerPrefix() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Bearer foo-bar-api-key', headers.get('Authorization'));
}
@isTest
private static void ApiClient_returnAuthenticationMatchingInput() {
MockApiClient client = new MockApiClient();
Swagger.ApiKeyHeaderAuth auth1 = new Swagger.ApiKeyHeaderAuth('foo');
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('foo');
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
System.assertEquals(auth1, client.getAuthentication('auth1'));
System.assertEquals(auth2, client.getAuthentication('auth2'));
System.assertEquals(auth3, client.getAuthentication('auth3'));
System.assertEquals(auth4, client.getAuthentication('auth4'));
}
@isTest
private static void ApiClient_noAuthenticationsMatchInputReturnNull() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth = new Swagger.OAuth2();
client.authentications.put('auth', auth);
System.assertEquals(auth, client.getAuthentication('auth'));
System.assertEquals(null, client.getAuthentication('no-auth'));
}
@isTest
private static void ApiClient_setUsernamePasswordFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setUsername('username');
client.setPassword('password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setUsernameExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setUsername('username');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setPasswordExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setPassword('password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setCredentialsFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setCredentials('username', 'password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setCredentialsExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setCredentials('username', 'password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setApiKeyFirstKeyAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.HttpBasicAuth auth2 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth4 = new Swagger.ApiKeyQueryAuth('auth4');
Swagger.ApiKeyHeaderAuth auth5 = new Swagger.ApiKeyHeaderAuth('auth5');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setApiKey('foo-bar-api-key');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('Basic Og==', auth2.getHeaderValue());
System.assertEquals('Basic Og==', auth3.getHeaderValue());
System.assertEquals('foo-bar-api-key', auth4.getApiKey());
System.assertEquals('', auth5.getApiKey());
}
@isTest
private static void ApiClient_setApiKeyExceptionNoKeyAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setApiKey('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setAccessTokenFirstOauthOnly() {
MockApiClient client = new MockApiClient();
Swagger.HttpBasicAuth auth1 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
Swagger.OAuth2 auth5 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setAccessToken('foo-bar-api-key');
System.assertEquals('Basic Og==', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Bearer foo-bar-api-key', auth4.getHeaderValue());
System.assertEquals('Bearer ', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setAccessTokenExceptionNoOAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setAccessToken('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_oneKeyValuePairForEachValueInList() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', values);
System.assertEquals(5, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=4', params.get(1).toString());
System.assertEquals('foo=false', params.get(2).toString());
System.assertEquals('foo=12.4', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
}
@isTest
private static void ApiClient_nullMultiValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', null);
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_valuesListToSingleCsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'csv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%2C4%2Cfalse%2C12.4%2C', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleSsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'ssv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar+4+false+12.4+', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleTsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'tsv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%094%09false%0912.4%09', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSinglePipeSeparatedKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'pipes');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%7C4%7Cfalse%7C12.4%7C', params.get(0).toString());
}
@isTest
private static void ApiClient_nullValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', null, 'csv');
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_paramsFromAnyPrimitiveTypeDiscardNull() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = new List<Swagger.Param>();
params.addAll(client.makeParam('foo', 'bar'));
params.addAll(client.makeParam('foo', 10));
params.addAll(client.makeParam('foo', 12.6));
params.addAll(client.makeParam('foo', true));
params.addAll(client.makeParam('foo', ''));
params.addAll(client.makeParam('foo', Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0)));
params.addAll(client.makeParam('foo', null));
System.assertEquals(6, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=10', params.get(1).toString());
System.assertEquals('foo=12.6', params.get(2).toString());
System.assertEquals('foo=true', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
System.assertEquals('foo=2017-01-01+15%3A00%3A00', params.get(5).toString());
}
@isTest
private static void ApiClient_requiredParameterPasses() {
Swagger.ApiClient client = new Swagger.ApiClient();
client.assertNotNull('foo', 'bar');
}
@isTest
private static void ApiClient_requiredParameterFails() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.assertNotNull(null, 'bar');
} catch (NullPointerException e) {
System.assertEquals('Argument cannot be null: bar', e.getMessage());
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_extractHeadersFromResponse() {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'private, max-age=0');
Map<String, String> headers = new MockApiClient().getHeaders(res);
System.assertEquals(2, headers.size());
System.assertEquals('application/json', headers.get('Content-Type'));
System.assertEquals('private, max-age=0', headers.get('Cache-Control'));
}
@isTest
private static void ApiClient_deserializeResponseBodyByContentType() {
MockApiClient client = new MockApiClient();
String jsonBody = '{"red":"apple","yellow":"banana","orange":"orange"}';
Map<String, String> result1 = (Map<String, String>) client
.toReturnValue(jsonBody, Map<String, String>.class, 'application/json');
System.assertEquals(3, result1.size());
System.assertEquals('apple', result1.get('red'));
System.assertEquals('banana', result1.get('yellow'));
System.assertEquals('orange', result1.get('orange'));
String result2 = (String) client
.toReturnValue('Hello, World!', String.class, 'text/plain');
System.assertEquals('Hello, World!', result2);
}
@isTest
private static void ApiClient_addStringifiedHeadersToRequest() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>{
'Content-Type' => 'application/json',
'Max-Forwards' => 10
};
HttpRequest req = new HttpRequest();
client.setHeaders(req, headers);
System.assertEquals('application/json', req.getHeader('Content-Type'));
System.assertEquals('10', req.getHeader('Max-Forwards'));
}
@isTest
private static void ApiClient_serializeRequestBodyOrFormByContentType() {
MockApiClient client = new MockApiClient();
Map<String, Object> body1 = new Map<String, Object>{
'hello' => 'world',
'foo' => 15,
'bar' => Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0),
'bat' => false
};
Set<String> expected1 = new Set<String>{
'"hello":"world"',
'"foo":15',
'"bar":"2017-01-01T15:00:00.000Z"',
'"bat":false'
};
Set<String> actual1 = new Set<String>(client
.toBody('application/json', body1, new List<Swagger.Param>())
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(expected1, actual1);
String body2 = 'Hello, World!';
String actual2 = client.toBody('text/plain', body2, new List<Swagger.Param>());
System.assertEquals(body2, actual2);
List<Swagger.Param> form = new List<Swagger.Param>{
new Swagger.Param('hello', 'world'),
new Swagger.Param('date', '2017-01-01 15:00:00')
};
String expected3 = 'hello=world&date=2017-01-01+15%3A00%3A00';
String actual3 = client.toBody('application/x-www-form-urlencoded', '', form);
System.assertEquals(expected3, actual3);
}
@isTest
private static void ApiClient_usePreferredContentTypeOrFirstInList() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
String result1 = client.setContentTypeHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Content-Type'));
System.assertEquals('application/json', result1);
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
String result2 = client.setContentTypeHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml', headers2.get('Content-Type'));
System.assertEquals('application/xml', result2);
Map<String, Object> headers3 = new Map<String, Object>();
String result3 = client.setContentTypeHeader(new List<String>(), headers3);
System.assertEquals(1, headers3.size());
System.assertEquals('application/json', headers3.get('Content-Type'));
System.assertEquals('application/json', result3);
}
@isTest
private static void ApiClient_usePreferredAcceptOrAllInListNoDefault() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
client.setAcceptHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Accept'));
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
client.setAcceptHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml,text/plain', headers2.get('Accept'));
Map<String, Object> headers3 = new Map<String, Object>();
client.setAcceptHeader(new List<String>(), headers3);
System.assert(headers3.isEmpty());
}
@isTest
private static void ApiClient_applyOnlyGivenAuthMethodsToParams() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyHeaderAuth auth2 = new Swagger.ApiKeyHeaderAuth('X-Authentication-Token');
auth1.setAccessToken('boo-bat-api-key');
auth2.setApiKey('foo-bar-api-key');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.applyAuthentication(new List<String>{'auth2'}, headers, new List<Swagger.Param>());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authentication-Token'));
}
@isTest
private static void ApiClient_formUrlWithQueryParamsPathParams() {
MockApiClient client = new MockApiClient();
String path = '/departments/{department}';
Map<String, Object> params = new Map<String, Object>{'department' => 'finance'};
List<Swagger.Param> queryParams = new List<Swagger.Param>{
new Swagger.Param('foo', 'bar'),
new Swagger.Param('bat', '123')
};
String expected = 'https://www.mccombs.utexas.edu/departments/finance?foo=bar&bat=123';
String actual = client.toEndpoint(path, params, queryParams);
System.assertEquals(expected, actual);
}
@isTest
private static void ApiClient_setupRequestWithBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}',
new Map<String, Object> {
'title' => 'Chapter 4 quiz',
'timed' => true,
'time' => 60,
'points' => 20.5,
'due' => Datetime.newInstanceGmt(2016, 5, 10, 23, 59, 59),
'description' => ''
},
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'application/json', 'application/xml'},
new List<String>{'application/json', 'application/xml'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req
.getBody()
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('"title":"Chapter 4 quiz"'));
System.assert(body.contains('"timed":true'));
System.assert(body.contains('"time":60'));
System.assert(body.contains('"points":20.5'));
System.assert(body.contains('"due":"2016-05-10T23:59:59.000Z"'));
System.assert(body.contains('"description":""'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('application/json', req.getHeader('Accept'));
System.assertEquals('application/json', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithForm() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>{
new Swagger.Param('title', 'Chapter 4 quiz'),
new Swagger.Param('timed', 'true'),
new Swagger.Param('time', '60'),
new Swagger.Param('points', '20.5'),
new Swagger.Param('due', '2016-05-10 18:59:59'),
new Swagger.Param('description', 'complete & upload \'section1: advanced\'')
},
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'text/html', 'application/xml'},
new List<String>{'application/x-www-form-urlencoded'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req.getBody().split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('title=Chapter+4+quiz'));
System.assert(body.contains('timed=true'));
System.assert(body.contains('time=60'));
System.assert(body.contains('points=20.5'));
System.assert(body.contains('due=2016-05-10+18%3A59%3A59'));
System.assert(body.contains('description=complete+%26+upload+%27section1%3A+advanced%27'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('text/html,application/xml', req.getHeader('Accept'));
System.assertEquals('application/x-www-form-urlencoded', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithQuery() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'GET', '/courses/{course}/assignments', '',
new List<Swagger.Param>{
new Swagger.Param('title', '#chapter1:section2'),
new Swagger.Param('due', '2016-05-10 18:59:59')
},
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/xml'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
List<String> splitUrl = req.getEndpoint().split('\\?');
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments';
Set<String> query = new Set<String>(splitUrl.get(1).split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, splitUrl.get(0));
System.assertEquals(2, query.size());
System.assert(query.contains('title=%23chapter1%3Asection2'));
System.assert(query.contains('due=2016-05-10+18%3A59%3A59'));
System.assertEquals('GET', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('application/xml', req.getHeader('Accept'));
System.assertEquals('text/plain', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_nonSuccessfulStatusCodeException() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('Not Found');
res.setStatusCode(404);
res.setHeader('X-Request-ID', '1234567890');
res.setHeader('Content-Type', 'application/json');
res.setBody('{"error":"the specified course does not exist"}');
try {
client.invoke(
'GET', '/courses/{course}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'},
null
);
} catch (Swagger.ApiException e) {
Map<String, String> headers = e.getHeaders();
System.assertEquals('API returned HTTP 404: Not Found', e.getMessage());
System.assertEquals(404, e.getStatusCode());
System.assertEquals('Not Found', e.getStatus());
System.assertEquals('{"error":"the specified course does not exist"}', e.getBody());
System.assertEquals(2, headers.size());
System.assertEquals('1234567890', headers.get('X-Request-ID'));
System.assertEquals('application/json', headers.get('Content-Type'));
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_returnParsedBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{'
+ '"city":"Austin","country":"United States","latitude":30.28403639999999,'
+ '"longitude":-97.73789449999998,"postalCode":"78705","state":"Texas",'
+ '"street":"2110 Speedway"}');
Address a = (Address) client.invoke(
'GET', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
Address.class
);
System.assertEquals('Austin', a.getCity());
System.assertEquals('United States', a.getCountry());
System.assertEquals(30.28403639999999, a.getLatitude());
System.assertEquals(-97.73789449999998, a.getLongitude());
System.assertEquals('78705', a.getPostalCode());
System.assertEquals('Texas', a.getState());
System.assertEquals('2110 Speedway', a.getStreet());
}
@isTest
private static void ApiClient_noReturnTypeReturnsNull() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
Object o = client.invoke(
'POST', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
null
);
System.assertEquals(null, o);
}
private class MockApiClient extends Swagger.ApiClient {
public MockApiClient() {
basePath = 'https://www.mccombs.utexas.edu';
}
}
}

View File

@@ -0,0 +1,118 @@
{{>licenseInfo}}
{{#operations}}
public class {{classname}} {
{{classPrefix}}Client client;
public {{classname}}({{classPrefix}}Client client) {
this.client = client;
}
public {{classname}}() {
this.client = new {{classPrefix}}Client();
}
public {{classPrefix}}Client getClient() {
return this.client;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
* @throws Swagger.ApiException if fails to make API call
*/
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#hasParams}}Map<String, Object> params{{/hasParams}}) {
{{#allParams}}
{{#required}}
client.assertNotNull(params.get('{{paramName}}'), '{{paramName}}');
{{/required}}
{{/allParams}}
List<Swagger.Param> query = new List<Swagger.Param>();
{{#hasQueryParams}}
// cast query params to verify their expected type
{{/hasQueryParams}}
{{#queryParams}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
query.addAll(client.makeParams('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
query.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}'), '{{collectionFormat}}'));
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
query.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isListContainer}}
{{^hasMore}}
{{/hasMore}}
{{/queryParams}}
List<Swagger.Param> form = new List<Swagger.Param>();
{{#hasFormParams}}
// cast form params to verify their expected type
{{/hasFormParams}}
{{#formParams}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
form.addAll(client.makeParams('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
form.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}'), '{{collectionFormat}}'));
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
form.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isListContainer}}
{{/formParams}}
{{#returnType}}return ({{{returnType}}}) {{/returnType}}client.invoke(
'{{httpMethod}}', '{{path}}',{{#bodyParam}}
({{{dataType}}}) params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}} ''{{/bodyParam}},
query, form,
new Map<String, Object>{{#hasPathParams}}{
{{#pathParams}}
'{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}}
{{/pathParams}}
}{{/hasPathParams}}{{^hasPathParams}}(){{/hasPathParams}},
new Map<String, Object>{{#hasHeaderParams}}{
{{#headerParams}}
'{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}}
{{/headerParams}}
}{{/hasHeaderParams}}{{^hasHeaderParams}}(){{/hasHeaderParams}},
{{#hasProduces}}
new List<String>{ {{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}} },
{{/hasProduces}}
{{^hasProduces}}
new List<String>(),
{{/hasProduces}}
{{#hasConsumes}}
new List<String>{ {{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}} },
{{/hasConsumes}}
{{^hasConsumes}}
new List<String>(),
{{/hasConsumes}}
{{#hasAuthMethods}}
new List<String> { {{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}} },
{{/hasAuthMethods}}
{{^hasAuthMethods}}
new List<String>(),
{{/hasAuthMethods}}
{{#returnType}}
{{{returnType}}}.class
{{/returnType}}
{{^returnType}}
null
{{/returnType}}
);
}
{{/operation}}
}
{{/operations}}

View File

@@ -0,0 +1,83 @@
# {{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
<a name="{{operationId}}"></a>
# **{{operationId}}**
> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{{summary}}{{#notes}}
{{notes}}{{/notes}}
### Example
```java
{{classname}} api = new {{classname}}();
{{#hasAuthMethods}}
{{classPrefix}}Client client = api.getClient();
{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setUsername('YOUR USERNAME');
{{{name}}}.setPassword('YOUR PASSWORD');
// You can also set your username and password in one line
{{{name}}}.setCredentials('YOUR USERNAME', 'YOUR PASSWORD');{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setApiKey('YOUR API KEY');{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Swagger.OAuth {{{name}}} = (Swagger.OAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setAccessToken('YOUR ACCESS TOKEN');{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{{paramName}}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
try {
// cross your fingers
{{#returnType}}{{{returnType}}} result = {{/returnType}}api.{{{operationId}}}({{#hasParams}}params{{/hasParams}});
{{#returnType}}
System.debug(result);
{{/returnType}}
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{/operation}}
{{/operations}}

View File

@@ -0,0 +1,87 @@
@isTest
private class {{classname}}Test {
{{#operations}}
{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*/
@isTest
private static void {{operationId}}Test() {
HttpResponse res = new HttpResponse();
{{#restfulCreate}}
res.setStatusCode(201);
res.setStatus('Created');
{{/restfulCreate}}
{{^restfulCreate}}
res.setStatusCode(200);
res.setStatus('OK');
{{/restfulCreate}}
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{paramName}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
{{classPrefix}}Client client;
{{classname}} api;
{{#returnType}}
{{{returnType}}} response;
{{{returnType}}} expectedResponse;
{{/returnType}}
{{#authMethods}}
client = new {{classPrefix}}Client();
api = new {{classname}}(client);{{#isBasic}}
((Swagger.HttpBasicAuth){{/isBasic}}{{#isOAuth}}
((Swagger.OAuth2){{/isOAuth}}{{#isApiKey}}
((Swagger.ApiKeyAuth){{/isApiKey}} client.getAuthentication('{{name}}'))
{{#isBasic}}
.setCredentials('username', 'password');
{{/isBasic}}
{{#isOAuth}}
.setAccessToken('foo-bar-access-token');
{{/isOAuth}}
{{#isApiKey}}
.setApiKey('foo-bar-api-key');
{{/isApiKey}}
{{#examples}}
res.setHeader('Content-Type', '{{contentType}}');
res.setBody('{{{example}}}');
expectedResponse = {{{deserializedExample}}};
response = ({{{returnType}}}) api.{{operationId}}({{#hasParams}}params{{/hasParams}});
System.assertEquals(expectedResponse, response);
{{/examples}}
{{^examples}}
api.{{operationId}}({{#hasParams}}params{{/hasParams}});
{{/examples}}
{{/authMethods}}
{{^authMethods}}
api = new {{classname}}(new {{classPrefix}}Client());
{{#examples}}
res.setHeader('Content-Type', '{{contentType}}');
res.setBody('{{{example}}}');
expectedResponse = {{{deserializedExample}}};
response = ({{{returnType}}}) api.{{operationId}}({{#hasParams}}params{{/hasParams}});
System.assertEquals(expectedResponse, response);
{{/examples}}
{{^examples}}
api.{{operationId}}({{#hasParams}}params{{/hasParams}});
{{/examples}}
{{/authMethods}}
}
{{#hasMore}}
{{/hasMore}}
{{/operation}}
{{/operations}}
}

View File

@@ -0,0 +1,98 @@
<project name="{{appName}}" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce">
<property environment="env"/>
<property file="build.properties"/>
<condition property="SF_USERNAME" value="">
<not>
<isset property="SF_USERNAME"></isset>
</not>
</condition>
<condition property="SF_PASSWORD" value="">
<not>
<isset property="SF_PASSWORD"></isset>
</not>
</condition>
<condition property="SF_SESSIONID" value="">
<not>
<isset property="SF_SESSIONID"></isset>
</not>
</condition>
<condition property="sf.serverurl" value="login.salesforce.com">
<not>
<isset property="sf.serverurl"></isset>
</not>
</condition>
<condition property="sf.maxPoll" value="200">
<not>
<isset property="sf.maxPoll"></isset>
</not>
</condition>
<condition property="sf.username" value="${env.SF_USERNAME}" else="${SF_USERNAME}">
<isset property="env.SF_USERNAME"/>
</condition>
<condition property="sf.password" value="${env.SF_PASSWORD}" else="${SF_PASSWORD}">
<isset property="env.SF_PASSWORD"/>
</condition>
<condition property="sf.sessionId" value="${env.SF_SESSIONID}" else="${SF_SESSIONID}">
<isset property="env.SF_SESSIONID"/>
</condition>
<taskdef resource="com/salesforce/antlib.xml" uri="antlib:com.salesforce">
<classpath>
<pathelement location="./ant-salesforce.jar"/>
</classpath>
</taskdef>
<target name="deploy"
description="Deploys the API client library to your Salesforce organization">
<echo message="Deploying the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
rollbackOnError="true">
{{#apiInfo}}
{{#apis}}
<runTest>{{classname}}Test</runTest>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<runTest>{{classname}}Test</runTest>
{{/model}}
{{/models}}
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
<target name="undeploy"
description="Removes the API client library from your Salesforce organization">
<echo message="Removing the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="undeploy"/>
</target>
<target name="deployCheckOnly"
description="Deploys the API client library in check-only mode, without saving changes">
<echo message="Run 'ant deploy' to deploy this library to your organization."/>
<echo message="Testing deployment of this API client library without saving changes"/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
checkOnly="true">
{{#apiInfo}}
{{#apis}}
<runTest>{{classname}}Test</runTest>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<runTest>{{classname}}Test</runTest>
{{/model}}
{{/models}}
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
</project>

View File

@@ -0,0 +1,37 @@
# build.properties
#
# The first three properties (SF_USERNAME, SF_PASSWORD, SF_SESSIONID) may either be specified below
# or set from environment variables of the same names. The remaining non-uppercase properties, which
# have the "sf." prefix (e.g.: sf.serverurl) may only be specified in this file and not from
# environment variables.
# Required if sessionId isn<73>t specified. The Salesforce username for login. The username associated
# with this connection must have the <20>Modify All Data<74> permission. Typically, this is only enabled
# for System Administrator users.
#
# SF_USERNAME = username@example.com
# Required if sessionId isn<73>t specified. The password you use to log in to the org associated with
# this project. If you are using a security token, paste the 25-digit token value to the end of your
# password.
#
# SF_PASSWORD = password123
# Required if username and password aren<65>t specified. The ID of an active Salesforce session or the
# OAuth access token. A session is created after a user logs in to Salesforce successfully with a
# username and password. Use a session ID for logging in to an existing session instead of creating
# a new session. Alternatively, use an access token for OAuth authentication. For more information,
# see Authenticating Apps with OAuth in the Salesforce Help.
#
# SF_SESSIONID = 0000...
# Optional. The Salesforce server URL (if blank, defaults to login.salesforce.com). To connect to a
# sandbox instance, change this to test.salesforce.com.
#
sf.serverurl = test.salesforce.com
# Optional. Defaults to 200. The number of times to poll the server for the results of the deploy
# request. Note that deployment can succeed even if you stop waiting.
#
sf.maxPoll = 200

View File

@@ -0,0 +1,30 @@
public class {{classPrefix}}Client extends Swagger.ApiClient {
{{#hasAuthMethods}}
public {{classPrefix}}Client() {
basePath = '{{basePath}}';
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
authentications.put('{{name}}', new Swagger.ApiKeyQueryAuth('{{keyParamName}}'));
{{/isKeyInQuery}}
{{^isKeyInQuery}}
authentications.put('{{name}}', new Swagger.ApiKeyHeaderAuth('{{keyParamName}}'));
{{/isKeyInQuery}}
{{/isApiKey}}
{{^isApiKey}}
{{#isBasic}}
authentications.put('{{name}}', new Swagger.HttpBasicAuth());
{{/isBasic}}
{{^isBasic}}
authentications.put('{{name}}', new Swagger.OAuth2());
{{/isBasic}}
{{/isApiKey}}
{{/authMethods}}
}
{{/hasAuthMethods}}
{{^hasAuthMethods}}
public {{classPrefix}}Client() {
basePath = '{{basePath}}';
}
{{/hasAuthMethods}}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>{{apiVersion}}</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,7 @@
# {{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}

View File

@@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
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.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -0,0 +1,27 @@
*DS_Store*
/Referenced Packages
/salesforce.schema
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse
.project
.externalToolBuilders/
*.launch
*.iml
.idea
*.sublime*
config

View File

@@ -0,0 +1,11 @@
/*
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/

View File

@@ -0,0 +1,6 @@
{{>licenseInfo}}
{{#models}}
{{#model}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,10 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{name}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@@ -0,0 +1,10 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@@ -0,0 +1,3 @@
{{#models}}{{#model}}
{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}}
{{/model}}{{/models}}

View File

@@ -0,0 +1,130 @@
{{#models}}
{{#model}}
@isTest
private class {{classname}}Test {
{{#isEnum}}
{{#allowableValues}}
@isTest
private static void allowableValues() {
Set<{{classname}}> expected = new Set<{{classname}}>{
{{#enumVars}}
{{classname}}.{{name}}{{^-last}},{{/-last}}
{{/enumVars}}
};
Set<{{classname}}> actual = new Set<{{classname}}>({{classname}}.values());
System.assertEquals(expected, actual);
}
{{/allowableValues}}
{{/isEnum}}
{{^isEnum}}
@isTest
private static void equalsSameInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classVarName}}1;
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = {{classVarName}}3;
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}2.equals({{classVarName}}1));
System.assert({{classVarName}}1.equals({{classVarName}}1));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assert({{classVarName}}4.equals({{classVarName}}3));
System.assert({{classVarName}}3.equals({{classVarName}}3));
}
@isTest
private static void equalsIdenticalInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classname}}.getExample();
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = new {{classname}}();
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}2.equals({{classVarName}}1));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assert({{classVarName}}4.equals({{classVarName}}3));
}
@isTest
private static void notEqualsUnlikeInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals(false, {{classVarName}}1.equals({{classVarName}}2));
System.assertEquals(false, {{classVarName}}2.equals({{classVarName}}1));
}
@isTest
private static void notEqualsDifferentType() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals(false, {{classVarName}}1.equals('foo'));
System.assertEquals(false, {{classVarName}}2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
{{classname}} {{classVarName}}3;
System.assertEquals(false, {{classVarName}}1.equals({{classVarName}}3));
System.assertEquals(false, {{classVarName}}2.equals({{classVarName}}3));
}
@isTest
private static void consistentHashCodeValue() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals({{classVarName}}1.hashCode(), {{classVarName}}1.hashCode());
System.assertEquals({{classVarName}}2.hashCode(), {{classVarName}}2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classname}}.getExample();
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = new {{classname}}();
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assertEquals({{classVarName}}1.hashCode(), {{classVarName}}2.hashCode());
System.assertEquals({{classVarName}}3.hashCode(), {{classVarName}}4.hashCode());
}
{{#vendorExtensions}}
{{#hasPropertyMappings}}
@isTest
private static void maintainRenamedProperties() {
{{classname}} {{classVarName}} = new {{classname}}();
Map<String, String> propertyMappings = {{classVarName}}.getPropertyMappings();
{{#propertyMappings}}
System.assertEquals('{{internalName}}', propertyMappings.get('{{externalName}}'));
{{/propertyMappings}}
}
{{/hasPropertyMappings}}
{{#hasDefaultValues}}
@isTest
private static void defaultValuesPopulated() {
{{classname}} {{classVarName}} = new {{classname}}();
{{#vars}}
{{#defaultValue}}
System.assertEquals({{{defaultValue}}}, {{classVarName}}.{{name}});
{{/defaultValue}}
{{/vars}}
{{#vars}}
{{^defaultValue}}
System.assertEquals(null, {{classVarName}}.{{name}});
{{/defaultValue}}
{{/vars}}
}
{{/hasDefaultValues}}
{{/vendorExtensions}}
{{/isEnum}}
}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>{{appName}} API Client</fullName>
<description>Client library for calling the {{appName}} API.{{#appDescription}}
{{{appDescription}}}{{/appDescription}}
Generated with Swagger Codegen (github.com/swagger-api/swagger-codegen)</description>
<types>
{{#apiInfo}}
{{#apis}}
<members>{{classname}}</members>
<members>{{classname}}Test</members>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<members>{{classname}}</members>
<members>{{classname}}Test</members>
{{/model}}
{{/models}}
<members>{{classPrefix}}Client</members>
<members>Swagger</members>
<members>SwaggerTest</members>
<members>SwaggerResponseMock</members>
<name>ApexClass</name>
</types>
<types>
<members>{{sanitizedName}}</members>
<name>RemoteSiteSetting</name>
</types>
<version>{{apiVersion}}</version>
</Package>

View File

@@ -0,0 +1,84 @@
/**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/
public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{#interfaces}}{{#-first}} implements {{/-first}}{{^-first}}, {{/-first}}{{.}}{{/interfaces}} {
{{#vars}}
{{#isEnum}}
{{^isContainer}}
{{>modelInnerEnum}}
{{/isContainer}}
{{/isEnum}}
{{#items.isEnum}}
{{#items}}
{{^isContainer}}
{{>modelInnerEnum}}
{{/isContainer}}
{{/items}}
{{/items.isEnum}}
/**
{{#description}}
* {{{description}}}
{{/description}}
{{^description}}
* Get {{name}}
{{/description}}
{{#minimum}}
* minimum: {{minimum}}
{{/minimum}}
{{#maximum}}
* maximum: {{maximum}}
{{/maximum}}
* @return {{name}}
*/
public {{{datatypeWithEnum}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; }
{{/vars}}
{{#vendorExtensions}}
{{#hasPropertyMappings}}
private static final Map<String, String> propertyMappings = new Map<String, String>{
{{#propertyMappings}}
'{{externalName}}' => '{{internalName}}'{{^-last}},{{/-last}}
{{/propertyMappings}}
};
public Map<String, String> getPropertyMappings() {
return propertyMappings;
}
{{/hasPropertyMappings}}
{{#hasDefaultValues}}
public {{classname}}() {
{{#vars}}
{{#defaultValue}}
{{name}} = {{{defaultValue}}};
{{/defaultValue}}
{{/vars}}
}
{{/hasDefaultValues}}
{{/vendorExtensions}}
public static {{classname}} getExample() {
{{classname}} {{classVarName}} = new {{classname}}();
{{#vars}}
{{classVarName}}.{{name}} = {{{example}}};
{{/vars}}
return {{classVarName}};
}
public Boolean equals(Object obj) {
if (obj instanceof {{classname}}) {
{{classname}} {{classVarName}} = ({{classname}}) obj;
return {{#vars}}this.{{name}} == {{classVarName}}.{{name}}{{#hasMore}}
&& {{/hasMore}}{{/vars}};
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
{{#vars}}
hashCode = (17 * hashCode) + ({{name}} == null ? 0 : System.hashCode({{name}}));
{{/vars}}
return hashCode;
}
}

View File

@@ -0,0 +1,15 @@
# {{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#readOnly}} [readonly]{{/readOnly}}
{{/vars}}
{{#vars}}{{#isEnum}}
<a name="{{{datatypeWithEnum}}}"></a>
## Enum: {{datatypeWithEnum}}
Name | Value
---- | -----{{#allowableValues}}{{#enumVars}}
{{name}} | {{value}}{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{/vars}}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">{{#shortDescription}}
<description>{{{shortDescription}}}</description>{{/shortDescription}}
<disableProtocolSecurity>false</disableProtocolSecurity>
<isActive>true</isActive>
<url>{{basePath}}</url>
</RemoteSiteSetting>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>{{classPrefix}} API Client</fullName>
<version>{{apiVersion}}</version>
</Package>

View File

@@ -214,7 +214,8 @@ use {{invokerPackage}}\ObjectSerializer;
{{/isFile}}
}
{{/formParams}}
{{#bodyParams}}// body params
{{#bodyParams}}
// body params
$_tempBody = null;
if (isset(${{paramName}})) {
$_tempBody = ${{paramName}};

View File

@@ -145,7 +145,9 @@ export class {{classname}} {
}
{{/isListContainer}}
{{^isListContainer}}
headers.set('{{baseName}}', String({{paramName}}));
if ({{paramName}} !== undefined && {{paramName}} !== null) {
headers.set('{{baseName}}', String({{paramName}}));
}
{{/isListContainer}}
{{/headerParams}}

View File

@@ -0,0 +1,875 @@
package io.swagger.codegen.apex;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.languages.ApexClientCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
@SuppressWarnings("static-method")
public class ApexModelTest {
@Test(description = "convert a simple apex model with provided examples")
public void examplesProvidedTest() {
BaseIntegerProperty baseIntProp = new BaseIntegerProperty();
baseIntProp.setExample(5);
PasswordProperty passwordProp = new PasswordProperty();
passwordProp.setExample("password");
UUIDProperty uuidProp = new UUIDProperty();
uuidProp.setExample("793574b2-3a8e-4f6c-bfa5-c6929dc29f8a");
final Model model = new ModelImpl()
.property("boolProp", new BooleanProperty().example(false))
.property("dateProp", new DateProperty().example("1985-04-12"))
.property("dateTimeProp", new DateTimeProperty().example("1985-04-12T23:20:50.52Z"))
.property("decimalProp", new DecimalProperty().example("19.99"))
.property("doubleProp", new DoubleProperty().example(2.95))
.property("emailProp", new EmailProperty().example("info@example.com"))
.property("floatProp", new FloatProperty().example(3.49f))
.property("intProp", new IntegerProperty().example(10))
.property("longProp", new LongProperty().example(100000L))
.property("stringProp", new StringProperty().example("foo"))
.property("baseIntProp", baseIntProp)
.property("passwordProp", passwordProp)
.property("uuidProp", uuidProp);
final ApexClientCodegen codegen = new ApexClientCodegen();
codegen.setClassPrefix("Prefix");
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "PrefixSample");
Assert.assertEquals(cm.vars.size(), 13);
final List<CodegenProperty> vars = cm.vars;
final CodegenProperty property1 = vars.get(0);
Assert.assertEquals(property1.name, "boolProp");
Assert.assertEquals(property1.baseName, "boolProp");
Assert.assertEquals(property1.datatype, "Boolean");
Assert.assertEquals(property1.baseType, "Boolean");
Assert.assertEquals(property1.example, "false");
Assert.assertNull(property1.defaultValue);
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertTrue(property1.isNotContainer);
Assert.assertTrue(property1.isBoolean);
final CodegenProperty property2 = vars.get(1);
Assert.assertEquals(property2.name, "dateProp");
Assert.assertEquals(property2.baseName, "dateProp");
Assert.assertEquals(property2.datatype, "Date");
Assert.assertEquals(property2.baseType, "Date");
Assert.assertEquals(property2.example, "Date.newInstance(1985, 4, 12)");
Assert.assertNull(property2.defaultValue);
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isNotContainer);
Assert.assertTrue(property2.isDate);
final CodegenProperty property3 = vars.get(2);
Assert.assertEquals(property3.name, "dateTimeProp");
Assert.assertEquals(property3.baseName, "dateTimeProp");
Assert.assertEquals(property3.datatype, "Datetime");
Assert.assertEquals(property3.baseType, "Datetime");
Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(1985, 4, 12, 23, 20, 50)");
Assert.assertNull(property3.defaultValue);
Assert.assertTrue(property3.hasMore);
Assert.assertTrue(property3.isPrimitiveType);
Assert.assertTrue(property3.isNotContainer);
Assert.assertTrue(property3.isDateTime);
final CodegenProperty property4 = vars.get(3);
Assert.assertEquals(property4.name, "decimalProp");
Assert.assertEquals(property4.baseName, "decimalProp");
Assert.assertEquals(property4.datatype, "Double");
Assert.assertEquals(property4.baseType, "Double");
Assert.assertEquals(property4.example, "19.99");
Assert.assertNull(property4.defaultValue);
Assert.assertTrue(property4.hasMore);
Assert.assertTrue(property4.isPrimitiveType);
Assert.assertTrue(property4.isNotContainer);
final CodegenProperty property5 = vars.get(4);
Assert.assertEquals(property5.name, "doubleProp");
Assert.assertEquals(property5.baseName, "doubleProp");
Assert.assertEquals(property5.datatype, "Double");
Assert.assertEquals(property5.baseType, "Double");
Assert.assertEquals(property5.example, "2.95");
Assert.assertNull(property5.defaultValue);
Assert.assertTrue(property5.hasMore);
Assert.assertTrue(property5.isPrimitiveType);
Assert.assertTrue(property5.isNotContainer);
Assert.assertTrue(property5.isDouble);
final CodegenProperty property6 = vars.get(5);
Assert.assertEquals(property6.name, "emailProp");
Assert.assertEquals(property6.baseName, "emailProp");
Assert.assertEquals(property6.datatype, "String");
Assert.assertEquals(property6.baseType, "String");
Assert.assertEquals(property6.example, "'info@example.com'");
Assert.assertNull(property6.defaultValue);
Assert.assertTrue(property6.hasMore);
Assert.assertTrue(property6.isPrimitiveType);
Assert.assertTrue(property6.isNotContainer);
Assert.assertTrue(property6.isString);
final CodegenProperty property7 = vars.get(6);
Assert.assertEquals(property7.name, "floatProp");
Assert.assertEquals(property7.baseName, "floatProp");
Assert.assertEquals(property7.datatype, "Double");
Assert.assertEquals(property7.baseType, "Double");
Assert.assertEquals(property7.example, "3.49");
Assert.assertNull(property7.defaultValue);
Assert.assertTrue(property7.hasMore);
Assert.assertTrue(property7.isPrimitiveType);
Assert.assertTrue(property7.isNotContainer);
Assert.assertTrue(property7.isFloat);
final CodegenProperty property8 = vars.get(7);
Assert.assertEquals(property8.name, "intProp");
Assert.assertEquals(property8.baseName, "intProp");
Assert.assertEquals(property8.datatype, "Integer");
Assert.assertEquals(property8.baseType, "Integer");
Assert.assertEquals(property8.example, "10");
Assert.assertNull(property8.defaultValue);
Assert.assertTrue(property8.hasMore);
Assert.assertTrue(property8.isPrimitiveType);
Assert.assertTrue(property8.isNotContainer);
Assert.assertTrue(property8.isInteger);
final CodegenProperty property9 = vars.get(8);
Assert.assertEquals(property9.name, "longProp");
Assert.assertEquals(property9.baseName, "longProp");
Assert.assertEquals(property9.datatype, "Long");
Assert.assertEquals(property9.baseType, "Long");
Assert.assertEquals(property9.example, "100000L");
Assert.assertNull(property9.defaultValue);
Assert.assertTrue(property9.hasMore);
Assert.assertTrue(property9.isPrimitiveType);
Assert.assertTrue(property9.isNotContainer);
Assert.assertTrue(property9.isLong);
final CodegenProperty property10 = vars.get(9);
Assert.assertEquals(property10.name, "stringProp");
Assert.assertEquals(property10.baseName, "stringProp");
Assert.assertEquals(property10.datatype, "String");
Assert.assertEquals(property10.baseType, "String");
Assert.assertEquals(property10.example, "'foo'");
Assert.assertNull(property10.defaultValue);
Assert.assertTrue(property10.hasMore);
Assert.assertTrue(property10.isPrimitiveType);
Assert.assertTrue(property10.isNotContainer);
Assert.assertTrue(property10.isString);
final CodegenProperty property11 = vars.get(10);
Assert.assertEquals(property11.name, "baseIntProp");
Assert.assertEquals(property11.baseName, "baseIntProp");
Assert.assertEquals(property11.datatype, "Integer");
Assert.assertEquals(property11.baseType, "Integer");
Assert.assertEquals(property11.example, "5");
Assert.assertNull(property11.defaultValue);
Assert.assertTrue(property11.hasMore);
Assert.assertTrue(property11.isPrimitiveType);
Assert.assertTrue(property11.isNotContainer);
Assert.assertTrue(property11.isInteger);
final CodegenProperty property12 = vars.get(11);
Assert.assertEquals(property12.name, "passwordProp");
Assert.assertEquals(property12.baseName, "passwordProp");
Assert.assertEquals(property12.datatype, "String");
Assert.assertEquals(property12.baseType, "String");
Assert.assertEquals(property12.example, "'password'");
Assert.assertNull(property12.defaultValue);
Assert.assertTrue(property12.hasMore);
Assert.assertTrue(property12.isPrimitiveType);
Assert.assertTrue(property12.isNotContainer);
final CodegenProperty property13 = vars.get(12);
Assert.assertEquals(property13.name, "uuidProp");
Assert.assertEquals(property13.baseName, "uuidProp");
Assert.assertEquals(property13.datatype, "String");
Assert.assertEquals(property13.baseType, "String");
Assert.assertEquals(property13.example, "'793574b2-3a8e-4f6c-bfa5-c6929dc29f8a'");
Assert.assertNull(property13.defaultValue);
Assert.assertFalse(property13.hasMore);
Assert.assertTrue(property13.isPrimitiveType);
Assert.assertTrue(property13.isNotContainer);
}
@Test(description = "convert a simple apex model with default examples")
public void defaultExamplesTest() {
final Model model = new ModelImpl()
.property("boolProp", new BooleanProperty())
.property("dateProp", new DateProperty())
.property("dateTimeProp", new DateTimeProperty())
.property("decimalProp", new DecimalProperty())
.property("doubleProp", new DoubleProperty())
.property("emailProp", new EmailProperty())
.property("floatProp", new FloatProperty())
.property("intProp", new IntegerProperty())
.property("longProp", new LongProperty())
.property("stringProp", new StringProperty())
.property("baseIntProp", new BaseIntegerProperty())
.property("passwordProp", new PasswordProperty())
.property("uuidProp", new UUIDProperty())
.property("byteArrProp", new ByteArrayProperty())
.property("binaryProp", new BinaryProperty());
final ApexClientCodegen codegen = new ApexClientCodegen();
codegen.setClassPrefix("Prefix");
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "PrefixSample");
Assert.assertEquals(cm.vars.size(), 15);
final List<CodegenProperty> vars = cm.vars;
final CodegenProperty property1 = vars.get(0);
Assert.assertEquals(property1.name, "boolProp");
Assert.assertEquals(property1.baseName, "boolProp");
Assert.assertEquals(property1.datatype, "Boolean");
Assert.assertEquals(property1.baseType, "Boolean");
Assert.assertEquals(property1.example, "true");
Assert.assertNull(property1.defaultValue);
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertTrue(property1.isNotContainer);
Assert.assertTrue(property1.isBoolean);
final CodegenProperty property2 = vars.get(1);
Assert.assertEquals(property2.name, "dateProp");
Assert.assertEquals(property2.baseName, "dateProp");
Assert.assertEquals(property2.datatype, "Date");
Assert.assertEquals(property2.baseType, "Date");
Assert.assertEquals(property2.example, "Date.newInstance(2000, 1, 23)");
Assert.assertNull(property2.defaultValue);
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isNotContainer);
Assert.assertTrue(property2.isDate);
final CodegenProperty property3 = vars.get(2);
Assert.assertEquals(property3.name, "dateTimeProp");
Assert.assertEquals(property3.baseName, "dateTimeProp");
Assert.assertEquals(property3.datatype, "Datetime");
Assert.assertEquals(property3.baseType, "Datetime");
Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(2000, 1, 23, 4, 56, 7)");
Assert.assertNull(property3.defaultValue);
Assert.assertTrue(property3.hasMore);
Assert.assertTrue(property3.isPrimitiveType);
Assert.assertTrue(property3.isNotContainer);
Assert.assertTrue(property3.isDateTime);
final CodegenProperty property4 = vars.get(3);
Assert.assertEquals(property4.name, "decimalProp");
Assert.assertEquals(property4.baseName, "decimalProp");
Assert.assertEquals(property4.datatype, "Double");
Assert.assertEquals(property4.baseType, "Double");
Assert.assertEquals(property4.example, "1.3579");
Assert.assertNull(property4.defaultValue);
Assert.assertTrue(property4.hasMore);
Assert.assertTrue(property4.isPrimitiveType);
Assert.assertTrue(property4.isNotContainer);
final CodegenProperty property5 = vars.get(4);
Assert.assertEquals(property5.name, "doubleProp");
Assert.assertEquals(property5.baseName, "doubleProp");
Assert.assertEquals(property5.datatype, "Double");
Assert.assertEquals(property5.baseType, "Double");
Assert.assertEquals(property5.example, "1.3579");
Assert.assertNull(property5.defaultValue);
Assert.assertTrue(property5.hasMore);
Assert.assertTrue(property5.isPrimitiveType);
Assert.assertTrue(property5.isNotContainer);
Assert.assertTrue(property5.isDouble);
final CodegenProperty property6 = vars.get(5);
Assert.assertEquals(property6.name, "emailProp");
Assert.assertEquals(property6.baseName, "emailProp");
Assert.assertEquals(property6.datatype, "String");
Assert.assertEquals(property6.baseType, "String");
Assert.assertEquals(property6.example, "'example@example.com'");
Assert.assertNull(property6.defaultValue);
Assert.assertTrue(property6.hasMore);
Assert.assertTrue(property6.isPrimitiveType);
Assert.assertTrue(property6.isNotContainer);
Assert.assertTrue(property6.isString);
final CodegenProperty property7 = vars.get(6);
Assert.assertEquals(property7.name, "floatProp");
Assert.assertEquals(property7.baseName, "floatProp");
Assert.assertEquals(property7.datatype, "Double");
Assert.assertEquals(property7.baseType, "Double");
Assert.assertEquals(property7.example, "1.3579");
Assert.assertNull(property7.defaultValue);
Assert.assertTrue(property7.hasMore);
Assert.assertTrue(property7.isPrimitiveType);
Assert.assertTrue(property7.isNotContainer);
Assert.assertTrue(property7.isFloat);
final CodegenProperty property8 = vars.get(7);
Assert.assertEquals(property8.name, "intProp");
Assert.assertEquals(property8.baseName, "intProp");
Assert.assertEquals(property8.datatype, "Integer");
Assert.assertEquals(property8.baseType, "Integer");
Assert.assertEquals(property8.example, "123");
Assert.assertNull(property8.defaultValue);
Assert.assertTrue(property8.hasMore);
Assert.assertTrue(property8.isPrimitiveType);
Assert.assertTrue(property8.isNotContainer);
Assert.assertTrue(property8.isInteger);
final CodegenProperty property9 = vars.get(8);
Assert.assertEquals(property9.name, "longProp");
Assert.assertEquals(property9.baseName, "longProp");
Assert.assertEquals(property9.datatype, "Long");
Assert.assertEquals(property9.baseType, "Long");
Assert.assertEquals(property9.example, "123456789L");
Assert.assertNull(property9.defaultValue);
Assert.assertTrue(property9.hasMore);
Assert.assertTrue(property9.isPrimitiveType);
Assert.assertTrue(property9.isNotContainer);
Assert.assertTrue(property9.isLong);
final CodegenProperty property10 = vars.get(9);
Assert.assertEquals(property10.name, "stringProp");
Assert.assertEquals(property10.baseName, "stringProp");
Assert.assertEquals(property10.datatype, "String");
Assert.assertEquals(property10.baseType, "String");
Assert.assertEquals(property10.example, "'aeiou'");
Assert.assertNull(property10.defaultValue);
Assert.assertTrue(property10.hasMore);
Assert.assertTrue(property10.isPrimitiveType);
Assert.assertTrue(property10.isNotContainer);
Assert.assertTrue(property10.isString);
final CodegenProperty property11 = vars.get(10);
Assert.assertEquals(property11.name, "baseIntProp");
Assert.assertEquals(property11.baseName, "baseIntProp");
Assert.assertEquals(property11.datatype, "Integer");
Assert.assertEquals(property11.baseType, "Integer");
Assert.assertEquals(property11.example, "123");
Assert.assertNull(property11.defaultValue);
Assert.assertTrue(property11.hasMore);
Assert.assertTrue(property11.isPrimitiveType);
Assert.assertTrue(property11.isNotContainer);
Assert.assertTrue(property11.isInteger);
final CodegenProperty property12 = vars.get(11);
Assert.assertEquals(property12.name, "passwordProp");
Assert.assertEquals(property12.baseName, "passwordProp");
Assert.assertEquals(property12.datatype, "String");
Assert.assertEquals(property12.baseType, "String");
Assert.assertEquals(property12.example, "'password123'");
Assert.assertNull(property12.defaultValue);
Assert.assertTrue(property12.hasMore);
Assert.assertTrue(property12.isPrimitiveType);
Assert.assertTrue(property12.isNotContainer);
final CodegenProperty property13 = vars.get(12);
Assert.assertEquals(property13.name, "uuidProp");
Assert.assertEquals(property13.baseName, "uuidProp");
Assert.assertEquals(property13.datatype, "String");
Assert.assertEquals(property13.baseType, "String");
Assert.assertEquals(property13.example, "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'");
Assert.assertNull(property13.defaultValue);
Assert.assertTrue(property13.hasMore);
Assert.assertTrue(property13.isPrimitiveType);
Assert.assertTrue(property13.isNotContainer);
final CodegenProperty property14 = vars.get(13);
Assert.assertEquals(property14.name, "byteArrProp");
Assert.assertEquals(property14.baseName, "byteArrProp");
Assert.assertEquals(property14.datatype, "Blob");
Assert.assertEquals(property14.baseType, "Blob");
Assert.assertEquals(property14.example, "EncodingUtil.base64Decode('VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')");
Assert.assertNull(property14.defaultValue);
Assert.assertTrue(property14.hasMore);
Assert.assertTrue(property14.isPrimitiveType);
Assert.assertTrue(property14.isNotContainer);
Assert.assertTrue(property14.isByteArray);
final CodegenProperty property15 = vars.get(14);
Assert.assertEquals(property15.name, "binaryProp");
Assert.assertEquals(property15.baseName, "binaryProp");
Assert.assertEquals(property15.datatype, "String");
Assert.assertEquals(property15.baseType, "String");
Assert.assertEquals(property15.example, "");
Assert.assertNull(property15.defaultValue);
Assert.assertFalse(property15.hasMore);
Assert.assertTrue(property15.isPrimitiveType);
Assert.assertTrue(property15.isNotContainer);
Assert.assertTrue(property15.isBinary);
}
//
// @Test(description = "convert a model with list property")
// public void listPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("id", new LongProperty())
// .property("urls", new ArrayProperty()
// .items(new StringProperty()))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 2);
//
// final CodegenProperty property = cm.vars.get(1);
// Assert.assertEquals(property.baseName, "urls");
// Assert.assertEquals(property.getter, "getUrls");
// Assert.assertEquals(property.setter, "setUrls");
// Assert.assertEquals(property.datatype, "List<String>");
// Assert.assertEquals(property.name, "urls");
// Assert.assertEquals(property.defaultValue, "new ArrayList<String>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a map property")
// public void mapPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("translations", new MapProperty()
// .additionalProperties(new StringProperty()))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "translations");
// Assert.assertEquals(property.getter, "getTranslations");
// Assert.assertEquals(property.setter, "setTranslations");
// Assert.assertEquals(property.datatype, "Map<String, String>");
// Assert.assertEquals(property.name, "translations");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, String>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a map with complex list property")
// public void mapWithListPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("translations",
// new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet"))))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "translations");
// Assert.assertEquals(property.getter, "getTranslations");
// Assert.assertEquals(property.setter, "setTranslations");
// Assert.assertEquals(property.datatype, "Map<String, List<Pet>>");
// Assert.assertEquals(property.name, "translations");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, List<Pet>>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a 2D list property")
// public void list2DPropertyTest() {
// final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items(
// new ArrayProperty().items(new RefProperty("Pet"))));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "list2D");
// Assert.assertEquals(property.getter, "getList2D");
// Assert.assertEquals(property.setter, "setList2D");
// Assert.assertEquals(property.datatype, "List<List<Pet>>");
// Assert.assertEquals(property.name, "list2D");
// Assert.assertEquals(property.defaultValue, "new ArrayList<List<Pet>>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with complex properties")
// public void complexPropertiesTest() {
// final Model model = new ModelImpl().description("a sample model")
// .property("children", new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "Children");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "Children");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model with complex list property")
// public void complexListPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children")));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.complexType, "Children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "List<Children>");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "new ArrayList<Children>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with complex map property")
// public void complexMapPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children")));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.complexType, "Children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "Map<String, Children>");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, Children>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// Assert.assertFalse(property.isNotContainer);
//
// }
//
// @Test(description = "convert an array model")
// public void arrayModelTest() {
// final Model model = new ArrayModel()
// .description("an array model")
// .items(new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "an array model");
// Assert.assertEquals(cm.vars.size(), 0);
// Assert.assertEquals(cm.parent, "ArrayList<Children>");
// Assert.assertEquals(cm.imports.size(), 4);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4);
// }
//
// @Test(description = "convert an map model")
// public void mapModelTest() {
// final Model model = new ModelImpl()
// .description("an map model")
// .additionalProperties(new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "an map model");
// Assert.assertEquals(cm.vars.size(), 0);
// Assert.assertEquals(cm.parent, "HashMap<String, Children>");
// Assert.assertEquals(cm.imports.size(), 4);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4);
// }
//
// @Test(description = "convert a model with upper-case property names")
// public void upperCaseNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with upper-case property names")
// .property("NAME", new StringProperty())
// .required("NAME");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "NAME");
// Assert.assertEquals(property.getter, "getNAME");
// Assert.assertEquals(property.setter, "setNAME");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "NAME");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model with a 2nd char upper-case property names")
// public void secondCharUpperCaseNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with a 2nd char upper-case property names")
// .property("pId", new StringProperty())
// .required("pId");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "pId");
// Assert.assertEquals(property.getter, "getPId");
// Assert.assertEquals(property.setter, "setPId");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "pId");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model starting with two upper-case letter property names")
// public void firstTwoUpperCaseLetterNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with a property name starting with two upper-case letters")
// .property("ATTName", new StringProperty())
// .required("ATTName");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "ATTName");
// Assert.assertEquals(property.getter, "getAtTName");
// Assert.assertEquals(property.setter, "setAtTName");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "atTName");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert hyphens per issue 503")
// public void hyphensTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("created-at", new DateTimeProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "created-at");
// Assert.assertEquals(property.getter, "getCreatedAt");
// Assert.assertEquals(property.setter, "setCreatedAt");
// Assert.assertEquals(property.name, "createdAt");
// }
//
// @Test(description = "convert query[password] to queryPassword")
// public void squareBracketsTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("query[password]", new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "query[password]");
// Assert.assertEquals(property.getter, "getQueryPassword");
// Assert.assertEquals(property.setter, "setQueryPassword");
// Assert.assertEquals(property.name, "queryPassword");
// }
//
// @Test(description = "properly escape names per 567")
// public void escapeNamesTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("created-at", new DateTimeProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("with.dots", model);
//
// Assert.assertEquals(cm.classname, "WithDots");
// }
//
// @Test(description = "convert a model with binary data")
// public void binaryDataTest() {
// final Model model = new ModelImpl()
// .description("model with binary")
// .property("inputBinaryData", new ByteArrayProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "inputBinaryData");
// Assert.assertEquals(property.getter, "getInputBinaryData");
// Assert.assertEquals(property.setter, "setInputBinaryData");
// Assert.assertEquals(property.datatype, "byte[]");
// Assert.assertEquals(property.name, "inputBinaryData");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "byte[]");
// Assert.assertFalse(property.hasMore);
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "translate an invalid param name")
// public void invalidParamNameTest() {
// final Model model = new ModelImpl()
// .description("a model with a 2nd char upper-case property names")
// .property("_", new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "_");
// Assert.assertEquals(property.getter, "getU");
// Assert.assertEquals(property.setter, "setU");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "u");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a parameter")
// public void convertParameterTest() {
// final QueryParameter parameter = new QueryParameter()
// .property(new IntegerProperty())
// .name("limit")
// .required(true);
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenParameter cm = codegen.fromParameter(parameter, null);
//
// Assert.assertNull(cm.allowableValues);
// }
//
// @Test(description = "types used by inner properties should be imported")
// public void mapWithAnListOfBigDecimalTest() {
// final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl()
// .description("model with Map<String, List<BigDecimal>>")
// .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))));
// Assert.assertEquals(cm1.vars.get(0).datatype, "Map<String, List<BigDecimal>>");
// Assert.assertTrue(cm1.imports.contains("BigDecimal"));
//
// final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl()
// .description("model with Map<String, Map<String, List<BigDecimal>>>")
// .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))));
// Assert.assertEquals(cm2.vars.get(0).datatype, "Map<String, Map<String, List<BigDecimal>>>");
// Assert.assertTrue(cm2.imports.contains("BigDecimal"));
// }
//
// @DataProvider(name = "modelNames")
// public static Object[][] primeNumbers() {
// return new Object[][] {
// {"sample", "Sample"},
// {"sample_name", "SampleName"},
// {"sample__name", "SampleName"},
// {"/sample", "Sample"},
// {"\\sample", "Sample"},
// {"sample.name", "SampleName"},
// {"_sample", "Sample"},
// {"Sample", "Sample"},
// };
// }
//
// @Test(dataProvider = "modelNames", description = "avoid inner class")
// public void modelNameTest(String name, String expectedName) {
// final Model model = new ModelImpl();
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel(name, model);
//
// Assert.assertEquals(cm.name, name);
// Assert.assertEquals(cm.classname, expectedName);
// }
//
// @DataProvider(name = "classProperties")
// public static Object[][] classProperties() {
// return new Object[][] {
// {"class", "getPropertyClass", "setPropertyClass", "propertyClass"},
// {"_class", "getPropertyClass", "setPropertyClass", "propertyClass"},
// {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"}
// };
// }
//
// @Test(dataProvider = "classProperties", description = "handle 'class' properties")
// public void classPropertyTest(String baseName, String getter, String setter, String name) {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property(baseName, new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, baseName);
// Assert.assertEquals(property.getter, getter);
// Assert.assertEquals(property.setter, setter);
// Assert.assertEquals(property.name, name);
// }
}

View File

@@ -0,0 +1 @@
2.2.3-SNAPSHOT

View File

@@ -51,7 +51,7 @@ export class FakeApi {
if (response.status === 204) {
return undefined;
} else {
return response.json();
return response.json() || {};
}
});
}

27
samples/client/petstore/apex/.gitignore vendored Normal file
View File

@@ -0,0 +1,27 @@
*DS_Store*
/Referenced Packages
/salesforce.schema
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse
.project
.externalToolBuilders/
*.launch
*.iml
.idea
*.sublime*
config

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
# This 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

@@ -0,0 +1 @@
2.2.3-SNAPSHOT

View File

@@ -0,0 +1,181 @@
# Swagger Petstore API Client
This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
## Requirements
- [Java 8 JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
- [Apache Ant](http://ant.apache.org/) version 1.6 or later
- [Force.com Migration Tool](https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_install.htm)
- The `ant-salesforce.jar` file included with the Force.com Migration Tool must be placed in the root directory of this project (in the same directory as this README and `build.xml`)
- `ANT_HOME` and `JAVA_HOME` environment variables must be set accordingly
- On Windows, `JAVA_HOME` will probably look something like this:
```
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_121
```
- The `bin` directory from Ant must be on your `PATH`
If everything is set correctly:
- Running `java -version` in a command prompt should output something like:
```bash
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
```
- Running `ant -version` should output something like:
```bash
Apache Ant(TM) version 1.10.1 compiled on February 2 2017
```
For more information, see <https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_prereq.htm>
## Installation
1. Clone the repo from GitHub
```bash
$ git clone git@github.com:GIT_USER_ID/GIT_REPO_ID.git
```
Or, [download](https://github.com/GIT_USER_ID/GIT_REPO_ID/archive/master.zip) the repo as a ZIP and extract it to `GIT_REPO_ID`
1. Set the `SF_USERNAME` and `SF_PASSWORD` environment variables to your Salesforce username and password. Alternatively, they may be set in `build.properties`. Environment variables will override the values in `build.properties` if set.
`SF_SESSIONID` may also be set instead of `SF_USERNAME` and `SF_PASSWORD` (more info in `build.properties`)
2. Open up a command prompt in the root project directory `GIT_REPO_ID` (the same directory as this README and `build.xml`)
3. Deploy to your Salesforce org
```bash
$ ant deploy
```
This command will:
- deploy all classes in the `deploy/classes` directory to your Salesforce org
- create a new [unmanaged package](https://help.salesforce.com/articleView?id=sharing_apps.htm) called **Swagger Petstore API Client**
- execute all of the unit tests included in this package (at least 75% code coverage required)
- create a new [remote site](https://help.salesforce.com/articleView?id=configuring_remoteproxy.htm) called **Swagger_Petstore** configured for the endpoint: <http://petstore.swagger.io/v2>
- rolls back any changes upon any error
A successful deployment will look like this:
```bash
[sf:deploy] Request Status: Succeeded
[sf:deploy] *********** DEPLOYMENT SUCCEEDED ***********
[sf:deploy] Finished request 0Af7A00000Ebd5oSAB successfully.
BUILD SUCCESSFUL
Total time: 34 seconds
```
### Test deployment only
To perform a test deployment without committing changes:
```bash
$ ant deployCheckOnly
```
All of the included tests will run as if it were a real deployment. Tests and other validations will report back while leaving your org untouched, allowing you to verify that a deployment will succeed without affecting anything in the org.
### Uninstallation
```bash
$ ant undeploy
```
Removes all classes and the Remote Site created by this package.
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Apex code:
```java
SwagPetApi api = new SwagPetApi();
SwagClient client = api.getClient();
// Configure OAuth2 access token for authorization: petstore_auth
Swagger.OAuth petstore_auth = (Swagger.OAuth) client.getAuthentication('petstore_auth');
petstore_auth.setAccessToken('YOUR ACCESS TOKEN');
Map<String, Object> params = new Map<String, Object>{
'body' => SwagPet.getExample()
};
try {
// cross your fingers
api.addPet(params);
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*SwagPetApi* | [**addPet**](docs/SwagPetApi.md#addPet) | **POST** /pet | Add a new pet to the store
*SwagPetApi* | [**deletePet**](docs/SwagPetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
*SwagPetApi* | [**findPetsByStatus**](docs/SwagPetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
*SwagPetApi* | [**findPetsByTags**](docs/SwagPetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
*SwagPetApi* | [**getPetById**](docs/SwagPetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
*SwagPetApi* | [**updatePet**](docs/SwagPetApi.md#updatePet) | **PUT** /pet | Update an existing pet
*SwagPetApi* | [**updatePetWithForm**](docs/SwagPetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
*SwagPetApi* | [**uploadFile**](docs/SwagPetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
*SwagStoreApi* | [**deleteOrder**](docs/SwagStoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*SwagStoreApi* | [**getInventory**](docs/SwagStoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
*SwagStoreApi* | [**getOrderById**](docs/SwagStoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
*SwagStoreApi* | [**placeOrder**](docs/SwagStoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
*SwagUserApi* | [**createUser**](docs/SwagUserApi.md#createUser) | **POST** /user | Create user
*SwagUserApi* | [**createUsersWithArrayInput**](docs/SwagUserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array
*SwagUserApi* | [**createUsersWithListInput**](docs/SwagUserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array
*SwagUserApi* | [**deleteUser**](docs/SwagUserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user
*SwagUserApi* | [**getUserByName**](docs/SwagUserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name
*SwagUserApi* | [**loginUser**](docs/SwagUserApi.md#loginUser) | **GET** /user/login | Logs user into the system
*SwagUserApi* | [**logoutUser**](docs/SwagUserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
*SwagUserApi* | [**updateUser**](docs/SwagUserApi.md#updateUser) | **PUT** /user/{username} | Updated user
## Documentation for Models
- [SwagApiResponse](docs/SwagApiResponse.md)
- [SwagCategory](docs/SwagCategory.md)
- [SwagOrder](docs/SwagOrder.md)
- [SwagPet](docs/SwagPet.md)
- [SwagTag](docs/SwagTag.md)
- [SwagUser](docs/SwagUser.md)
## Documentation for Authorization
Authentication schemes defined for the API:
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
### petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- write:pets: modify pets in your account
- read:pets: read your pets
## Author
apiteam@swagger.io

View File

@@ -0,0 +1,37 @@
# build.properties
#
# The first three properties (SF_USERNAME, SF_PASSWORD, SF_SESSIONID) may either be specified below
# or set from environment variables of the same names. The remaining non-uppercase properties, which
# have the "sf." prefix (e.g.: sf.serverurl) may only be specified in this file and not from
# environment variables.
# Required if sessionId isn<73>t specified. The Salesforce username for login. The username associated
# with this connection must have the <20>Modify All Data<74> permission. Typically, this is only enabled
# for System Administrator users.
#
# SF_USERNAME = username@example.com
# Required if sessionId isn<73>t specified. The password you use to log in to the org associated with
# this project. If you are using a security token, paste the 25-digit token value to the end of your
# password.
#
# SF_PASSWORD = password123
# Required if username and password aren<65>t specified. The ID of an active Salesforce session or the
# OAuth access token. A session is created after a user logs in to Salesforce successfully with a
# username and password. Use a session ID for logging in to an existing session instead of creating
# a new session. Alternatively, use an access token for OAuth authentication. For more information,
# see Authenticating Apps with OAuth in the Salesforce Help.
#
# SF_SESSIONID = 0000...
# Optional. The Salesforce server URL (if blank, defaults to login.salesforce.com). To connect to a
# sandbox instance, change this to test.salesforce.com.
#
sf.serverurl = test.salesforce.com
# Optional. Defaults to 200. The number of times to poll the server for the results of the deploy
# request. Note that deployment can succeed even if you stop waiting.
#
sf.maxPoll = 200

View File

@@ -0,0 +1,96 @@
<project name="Swagger Petstore" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce">
<property environment="env"/>
<property file="build.properties"/>
<condition property="SF_USERNAME" value="">
<not>
<isset property="SF_USERNAME"></isset>
</not>
</condition>
<condition property="SF_PASSWORD" value="">
<not>
<isset property="SF_PASSWORD"></isset>
</not>
</condition>
<condition property="SF_SESSIONID" value="">
<not>
<isset property="SF_SESSIONID"></isset>
</not>
</condition>
<condition property="sf.serverurl" value="login.salesforce.com">
<not>
<isset property="sf.serverurl"></isset>
</not>
</condition>
<condition property="sf.maxPoll" value="200">
<not>
<isset property="sf.maxPoll"></isset>
</not>
</condition>
<condition property="sf.username" value="${env.SF_USERNAME}" else="${SF_USERNAME}">
<isset property="env.SF_USERNAME"/>
</condition>
<condition property="sf.password" value="${env.SF_PASSWORD}" else="${SF_PASSWORD}">
<isset property="env.SF_PASSWORD"/>
</condition>
<condition property="sf.sessionId" value="${env.SF_SESSIONID}" else="${SF_SESSIONID}">
<isset property="env.SF_SESSIONID"/>
</condition>
<taskdef resource="com/salesforce/antlib.xml" uri="antlib:com.salesforce">
<classpath>
<pathelement location="./ant-salesforce.jar"/>
</classpath>
</taskdef>
<target name="deploy"
description="Deploys the API client library to your Salesforce organization">
<echo message="Deploying the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
rollbackOnError="true">
<runTest>SwagPetApiTest</runTest>
<runTest>SwagStoreApiTest</runTest>
<runTest>SwagUserApiTest</runTest>
<runTest>SwagApiResponseTest</runTest>
<runTest>SwagCategoryTest</runTest>
<runTest>SwagOrderTest</runTest>
<runTest>SwagPetTest</runTest>
<runTest>SwagTagTest</runTest>
<runTest>SwagUserTest</runTest>
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
<target name="undeploy"
description="Removes the API client library from your Salesforce organization">
<echo message="Removing the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="undeploy"/>
</target>
<target name="deployCheckOnly"
description="Deploys the API client library in check-only mode, without saving changes">
<echo message="Run 'ant deploy' to deploy this library to your organization."/>
<echo message="Testing deployment of this API client library without saving changes"/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
checkOnly="true">
<runTest>SwagPetApiTest</runTest>
<runTest>SwagStoreApiTest</runTest>
<runTest>SwagUserApiTest</runTest>
<runTest>SwagApiResponseTest</runTest>
<runTest>SwagCategoryTest</runTest>
<runTest>SwagOrderTest</runTest>
<runTest>SwagPetTest</runTest>
<runTest>SwagTagTest</runTest>
<runTest>SwagUserTest</runTest>
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
</project>

View File

@@ -0,0 +1,69 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* Describes the result of uploading an image resource
*/
public class SwagApiResponse implements Swagger.MappedProperties {
/**
* Get code
* @return code
*/
public Integer code { get; set; }
/**
* Get r_type
* @return r_type
*/
public String r_type { get; set; }
/**
* Get message
* @return message
*/
public String message { get; set; }
private static final Map<String, String> propertyMappings = new Map<String, String>{
'type' => 'r_type'
};
public Map<String, String> getPropertyMappings() {
return propertyMappings;
}
public static SwagApiResponse getExample() {
SwagApiResponse apiResponse = new SwagApiResponse();
apiResponse.code = 123;
apiResponse.r_type = 'aeiou';
apiResponse.message = 'aeiou';
return apiResponse;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagApiResponse) {
SwagApiResponse apiResponse = (SwagApiResponse) obj;
return this.code == apiResponse.code
&& this.r_type == apiResponse.r_type
&& this.message == apiResponse.message;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (code == null ? 0 : System.hashCode(code));
hashCode = (17 * hashCode) + (r_type == null ? 0 : System.hashCode(r_type));
hashCode = (17 * hashCode) + (message == null ? 0 : System.hashCode(message));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,87 @@
@isTest
private class SwagApiResponseTest {
@isTest
private static void equalsSameInstance() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = apiResponse1;
SwagApiResponse apiResponse3 = new SwagApiResponse();
SwagApiResponse apiResponse4 = apiResponse3;
System.assert(apiResponse1.equals(apiResponse2));
System.assert(apiResponse2.equals(apiResponse1));
System.assert(apiResponse1.equals(apiResponse1));
System.assert(apiResponse3.equals(apiResponse4));
System.assert(apiResponse4.equals(apiResponse3));
System.assert(apiResponse3.equals(apiResponse3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = SwagApiResponse.getExample();
SwagApiResponse apiResponse3 = new SwagApiResponse();
SwagApiResponse apiResponse4 = new SwagApiResponse();
System.assert(apiResponse1.equals(apiResponse2));
System.assert(apiResponse2.equals(apiResponse1));
System.assert(apiResponse3.equals(apiResponse4));
System.assert(apiResponse4.equals(apiResponse3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = new SwagApiResponse();
System.assertEquals(false, apiResponse1.equals(apiResponse2));
System.assertEquals(false, apiResponse2.equals(apiResponse1));
}
@isTest
private static void notEqualsDifferentType() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = new SwagApiResponse();
System.assertEquals(false, apiResponse1.equals('foo'));
System.assertEquals(false, apiResponse2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = new SwagApiResponse();
SwagApiResponse apiResponse3;
System.assertEquals(false, apiResponse1.equals(apiResponse3));
System.assertEquals(false, apiResponse2.equals(apiResponse3));
}
@isTest
private static void consistentHashCodeValue() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = new SwagApiResponse();
System.assertEquals(apiResponse1.hashCode(), apiResponse1.hashCode());
System.assertEquals(apiResponse2.hashCode(), apiResponse2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagApiResponse apiResponse1 = SwagApiResponse.getExample();
SwagApiResponse apiResponse2 = SwagApiResponse.getExample();
SwagApiResponse apiResponse3 = new SwagApiResponse();
SwagApiResponse apiResponse4 = new SwagApiResponse();
System.assert(apiResponse1.equals(apiResponse2));
System.assert(apiResponse3.equals(apiResponse4));
System.assertEquals(apiResponse1.hashCode(), apiResponse2.hashCode());
System.assertEquals(apiResponse3.hashCode(), apiResponse4.hashCode());
}
@isTest
private static void maintainRenamedProperties() {
SwagApiResponse apiResponse = new SwagApiResponse();
Map<String, String> propertyMappings = apiResponse.getPropertyMappings();
System.assertEquals('r_type', propertyMappings.get('type'));
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,52 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A category for a pet
*/
public class SwagCategory {
/**
* Get id
* @return id
*/
public Long id { get; set; }
/**
* Get name
* @return name
*/
public String name { get; set; }
public static SwagCategory getExample() {
SwagCategory category = new SwagCategory();
category.id = 123456789L;
category.name = 'aeiou';
return category;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagCategory) {
SwagCategory category = (SwagCategory) obj;
return this.id == category.id
&& this.name == category.name;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (id == null ? 0 : System.hashCode(id));
hashCode = (17 * hashCode) + (name == null ? 0 : System.hashCode(name));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,80 @@
@isTest
private class SwagCategoryTest {
@isTest
private static void equalsSameInstance() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = category1;
SwagCategory category3 = new SwagCategory();
SwagCategory category4 = category3;
System.assert(category1.equals(category2));
System.assert(category2.equals(category1));
System.assert(category1.equals(category1));
System.assert(category3.equals(category4));
System.assert(category4.equals(category3));
System.assert(category3.equals(category3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = SwagCategory.getExample();
SwagCategory category3 = new SwagCategory();
SwagCategory category4 = new SwagCategory();
System.assert(category1.equals(category2));
System.assert(category2.equals(category1));
System.assert(category3.equals(category4));
System.assert(category4.equals(category3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = new SwagCategory();
System.assertEquals(false, category1.equals(category2));
System.assertEquals(false, category2.equals(category1));
}
@isTest
private static void notEqualsDifferentType() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = new SwagCategory();
System.assertEquals(false, category1.equals('foo'));
System.assertEquals(false, category2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = new SwagCategory();
SwagCategory category3;
System.assertEquals(false, category1.equals(category3));
System.assertEquals(false, category2.equals(category3));
}
@isTest
private static void consistentHashCodeValue() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = new SwagCategory();
System.assertEquals(category1.hashCode(), category1.hashCode());
System.assertEquals(category2.hashCode(), category2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagCategory category1 = SwagCategory.getExample();
SwagCategory category2 = SwagCategory.getExample();
SwagCategory category3 = new SwagCategory();
SwagCategory category4 = new SwagCategory();
System.assert(category1.equals(category2));
System.assert(category3.equals(category4));
System.assertEquals(category1.hashCode(), category2.hashCode());
System.assertEquals(category3.hashCode(), category4.hashCode());
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,7 @@
public class SwagClient extends Swagger.ApiClient {
public SwagClient() {
basePath = 'http://petstore.swagger.io/v2';
authentications.put('api_key', new Swagger.ApiKeyHeaderAuth('api_key'));
authentications.put('petstore_auth', new Swagger.OAuth2());
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,101 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* An order for a pets from the pet store
*/
public class SwagOrder {
/**
* Get id
* @return id
*/
public Long id { get; set; }
/**
* Get petId
* @return petId
*/
public Long petId { get; set; }
/**
* Get quantity
* @return quantity
*/
public Integer quantity { get; set; }
/**
* Get shipDate
* @return shipDate
*/
public Datetime shipDate { get; set; }
/**
* Order Status
*/
public enum StatusEnum {
PLACED,
APPROVED,
DELIVERED
}
/**
* Order Status
* @return status
*/
public StatusEnum status { get; set; }
/**
* Get complete
* @return complete
*/
public Boolean complete { get; set; }
public SwagOrder() {
complete = false;
}
public static SwagOrder getExample() {
SwagOrder order = new SwagOrder();
order.id = 123456789L;
order.petId = 123456789L;
order.quantity = 123;
order.shipDate = Datetime.newInstanceGmt(2000, 1, 23, 4, 56, 7);
order.status = StatusEnum.PLACED;
order.complete = true;
return order;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagOrder) {
SwagOrder order = (SwagOrder) obj;
return this.id == order.id
&& this.petId == order.petId
&& this.quantity == order.quantity
&& this.shipDate == order.shipDate
&& this.status == order.status
&& this.complete == order.complete;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (id == null ? 0 : System.hashCode(id));
hashCode = (17 * hashCode) + (petId == null ? 0 : System.hashCode(petId));
hashCode = (17 * hashCode) + (quantity == null ? 0 : System.hashCode(quantity));
hashCode = (17 * hashCode) + (shipDate == null ? 0 : System.hashCode(shipDate));
hashCode = (17 * hashCode) + (status == null ? 0 : System.hashCode(status));
hashCode = (17 * hashCode) + (complete == null ? 0 : System.hashCode(complete));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,91 @@
@isTest
private class SwagOrderTest {
@isTest
private static void equalsSameInstance() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = order1;
SwagOrder order3 = new SwagOrder();
SwagOrder order4 = order3;
System.assert(order1.equals(order2));
System.assert(order2.equals(order1));
System.assert(order1.equals(order1));
System.assert(order3.equals(order4));
System.assert(order4.equals(order3));
System.assert(order3.equals(order3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = SwagOrder.getExample();
SwagOrder order3 = new SwagOrder();
SwagOrder order4 = new SwagOrder();
System.assert(order1.equals(order2));
System.assert(order2.equals(order1));
System.assert(order3.equals(order4));
System.assert(order4.equals(order3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = new SwagOrder();
System.assertEquals(false, order1.equals(order2));
System.assertEquals(false, order2.equals(order1));
}
@isTest
private static void notEqualsDifferentType() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = new SwagOrder();
System.assertEquals(false, order1.equals('foo'));
System.assertEquals(false, order2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = new SwagOrder();
SwagOrder order3;
System.assertEquals(false, order1.equals(order3));
System.assertEquals(false, order2.equals(order3));
}
@isTest
private static void consistentHashCodeValue() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = new SwagOrder();
System.assertEquals(order1.hashCode(), order1.hashCode());
System.assertEquals(order2.hashCode(), order2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagOrder order1 = SwagOrder.getExample();
SwagOrder order2 = SwagOrder.getExample();
SwagOrder order3 = new SwagOrder();
SwagOrder order4 = new SwagOrder();
System.assert(order1.equals(order2));
System.assert(order3.equals(order4));
System.assertEquals(order1.hashCode(), order2.hashCode());
System.assertEquals(order3.hashCode(), order4.hashCode());
}
@isTest
private static void defaultValuesPopulated() {
SwagOrder order = new SwagOrder();
System.assertEquals(false, order.complete);
System.assertEquals(null, order.id);
System.assertEquals(null, order.petId);
System.assertEquals(null, order.quantity);
System.assertEquals(null, order.shipDate);
System.assertEquals(null, order.status);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,102 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A pet for sale in the pet store
*/
public class SwagPet {
/**
* Get id
* @return id
*/
public Long id { get; set; }
/**
* Get category
* @return category
*/
public SwagCategory category { get; set; }
/**
* Get name
* @return name
*/
public String name { get; set; }
/**
* Get photoUrls
* @return photoUrls
*/
public List<String> photoUrls { get; set; }
/**
* Get tags
* @return tags
*/
public List<SwagTag> tags { get; set; }
/**
* pet status in the store
*/
public enum StatusEnum {
AVAILABLE,
PENDING,
SOLD
}
/**
* pet status in the store
* @return status
*/
public StatusEnum status { get; set; }
public SwagPet() {
photoUrls = new List<String>();
tags = new List<SwagTag>();
}
public static SwagPet getExample() {
SwagPet pet = new SwagPet();
pet.id = 123456789L;
pet.category = SwagCategory.getExample();
pet.name = 'doggie';
pet.photoUrls = new List<String>{'aeiou'};
pet.tags = new List<SwagTag>{SwagTag.getExample()};
pet.status = StatusEnum.AVAILABLE;
return pet;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagPet) {
SwagPet pet = (SwagPet) obj;
return this.id == pet.id
&& this.category == pet.category
&& this.name == pet.name
&& this.photoUrls == pet.photoUrls
&& this.tags == pet.tags
&& this.status == pet.status;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (id == null ? 0 : System.hashCode(id));
hashCode = (17 * hashCode) + (category == null ? 0 : System.hashCode(category));
hashCode = (17 * hashCode) + (name == null ? 0 : System.hashCode(name));
hashCode = (17 * hashCode) + (photoUrls == null ? 0 : System.hashCode(photoUrls));
hashCode = (17 * hashCode) + (tags == null ? 0 : System.hashCode(tags));
hashCode = (17 * hashCode) + (status == null ? 0 : System.hashCode(status));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,241 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
public class SwagPetApi {
SwagClient client;
public SwagPetApi(SwagClient client) {
this.client = client;
}
public SwagPetApi() {
this.client = new SwagClient();
}
public SwagClient getClient() {
return this.client;
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void addPet(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'POST', '/pet',
(SwagPet) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'petstore_auth' },
null
);
}
/**
* Deletes a pet
*
* @param petId Pet id to delete (required)
* @param apiKey (optional)
* @throws Swagger.ApiException if fails to make API call
*/
public void deletePet(Map<String, Object> params) {
client.assertNotNull(params.get('petId'), 'petId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'DELETE', '/pet/{petId}', '',
query, form,
new Map<String, Object>{
'petId' => (Long) params.get('petId')
},
new Map<String, Object>{
'api_key' => (String) params.get('apiKey')
},
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'petstore_auth' },
null
);
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param status Status values that need to be considered for filter (required)
* @return List<SwagPet>
* @throws Swagger.ApiException if fails to make API call
*/
public List<SwagPet> findPetsByStatus(Map<String, Object> params) {
client.assertNotNull(params.get('status'), 'status');
List<Swagger.Param> query = new List<Swagger.Param>();
// cast query params to verify their expected type
query.addAll(client.makeParam('status', (List<String>) params.get('status'), 'csv'));
List<Swagger.Param> form = new List<Swagger.Param>();
return (List<SwagPet>) client.invoke(
'GET', '/pet/findByStatus', '',
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'petstore_auth' },
List<SwagPet>.class
);
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by (required)
* @return List<SwagPet>
* @throws Swagger.ApiException if fails to make API call
*/
public List<SwagPet> findPetsByTags(Map<String, Object> params) {
client.assertNotNull(params.get('tags'), 'tags');
List<Swagger.Param> query = new List<Swagger.Param>();
// cast query params to verify their expected type
query.addAll(client.makeParam('tags', (List<String>) params.get('tags'), 'csv'));
List<Swagger.Param> form = new List<Swagger.Param>();
return (List<SwagPet>) client.invoke(
'GET', '/pet/findByTags', '',
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'petstore_auth' },
List<SwagPet>.class
);
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return (required)
* @return SwagPet
* @throws Swagger.ApiException if fails to make API call
*/
public SwagPet getPetById(Map<String, Object> params) {
client.assertNotNull(params.get('petId'), 'petId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
return (SwagPet) client.invoke(
'GET', '/pet/{petId}', '',
query, form,
new Map<String, Object>{
'petId' => (Long) params.get('petId')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'api_key' },
SwagPet.class
);
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void updatePet(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'PUT', '/pet',
(SwagPet) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'petstore_auth' },
null
);
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated (required)
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @throws Swagger.ApiException if fails to make API call
*/
public void updatePetWithForm(Map<String, Object> params) {
client.assertNotNull(params.get('petId'), 'petId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
// cast form params to verify their expected type
form.addAll(client.makeParam('name', (String) params.get('name')));
form.addAll(client.makeParam('status', (String) params.get('status')));
client.invoke(
'POST', '/pet/{petId}', '',
query, form,
new Map<String, Object>{
'petId' => (Long) params.get('petId')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/x-www-form-urlencoded' },
new List<String> { 'petstore_auth' },
null
);
}
/**
* uploads an image
*
* @param petId ID of pet to update (required)
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return SwagApiResponse
* @throws Swagger.ApiException if fails to make API call
*/
public SwagApiResponse uploadFile(Map<String, Object> params) {
client.assertNotNull(params.get('petId'), 'petId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
// cast form params to verify their expected type
form.addAll(client.makeParam('additionalMetadata', (String) params.get('additionalMetadata')));
form.addAll(client.makeParam('file', (Blob) params.get('file')));
return (SwagApiResponse) client.invoke(
'POST', '/pet/{petId}/uploadImage', '',
query, form,
new Map<String, Object>{
'petId' => (Long) params.get('petId')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/x-www-form-urlencoded' },
new List<String> { 'petstore_auth' },
SwagApiResponse.class
);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,247 @@
@isTest
private class SwagPetApiTest {
/**
* Add a new pet to the store
*
*
*/
@isTest
private static void addPetTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setStatus('Created');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => SwagPet.getExample()
};
SwagClient client;
SwagPetApi api;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
api.addPet(params);
}
/**
* Deletes a pet
*
*
*/
@isTest
private static void deletePetTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'petId' => 2147483648L,
'apiKey' => 'apiKey_example'
};
SwagClient client;
SwagPetApi api;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
api.deletePet(params);
}
/**
* Finds Pets by status
*
* Multiple status values can be provided with comma separated strings
*/
@isTest
private static void findPetsByStatusTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'status' => new List<String>{'available'}
};
SwagClient client;
SwagPetApi api;
List<SwagPet> response;
List<SwagPet> expectedResponse;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
res.setHeader('Content-Type', 'application/json');
res.setBody('[ {\n "photoUrls" : [ "aeiou" ],\n "name" : "doggie",\n "id" : 0,\n "category" : {\n "name" : "aeiou",\n "id" : 6\n },\n "tags" : [ {\n "name" : "aeiou",\n "id" : 1\n } ],\n "status" : "available"\n} ]');
expectedResponse = new List<SwagPet>{SwagPet.getExample()};
response = (List<SwagPet>) api.findPetsByStatus(params);
System.assertEquals(expectedResponse, response);
}
/**
* Finds Pets by tags
*
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*/
@isTest
private static void findPetsByTagsTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'tags' => new List<String>{'aeiou'}
};
SwagClient client;
SwagPetApi api;
List<SwagPet> response;
List<SwagPet> expectedResponse;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
res.setHeader('Content-Type', 'application/json');
res.setBody('[ {\n "photoUrls" : [ "aeiou" ],\n "name" : "doggie",\n "id" : 0,\n "category" : {\n "name" : "aeiou",\n "id" : 6\n },\n "tags" : [ {\n "name" : "aeiou",\n "id" : 1\n } ],\n "status" : "available"\n} ]');
expectedResponse = new List<SwagPet>{SwagPet.getExample()};
response = (List<SwagPet>) api.findPetsByTags(params);
System.assertEquals(expectedResponse, response);
}
/**
* Find pet by ID
*
* Returns a single pet
*/
@isTest
private static void getPetByIdTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'petId' => 2147483648L
};
SwagClient client;
SwagPetApi api;
SwagPet response;
SwagPet expectedResponse;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.ApiKeyAuth) client.getAuthentication('api_key'))
.setApiKey('foo-bar-api-key');
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "photoUrls" : [ "aeiou" ],\n "name" : "doggie",\n "id" : 0,\n "category" : {\n "name" : "aeiou",\n "id" : 6\n },\n "tags" : [ {\n "name" : "aeiou",\n "id" : 1\n } ],\n "status" : "available"\n}');
expectedResponse = SwagPet.getExample();
response = (SwagPet) api.getPetById(params);
System.assertEquals(expectedResponse, response);
}
/**
* Update an existing pet
*
*
*/
@isTest
private static void updatePetTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => SwagPet.getExample()
};
SwagClient client;
SwagPetApi api;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
api.updatePet(params);
}
/**
* Updates a pet in the store with form data
*
*
*/
@isTest
private static void updatePetWithFormTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'petId' => 2147483648L,
'name' => 'name_example',
'status' => 'status_example'
};
SwagClient client;
SwagPetApi api;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
api.updatePetWithForm(params);
}
/**
* uploads an image
*
*
*/
@isTest
private static void uploadFileTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'petId' => 2147483648L,
'additionalMetadata' => 'additionalMetadata_example',
'file' => Blob.valueOf('Sample text file\nContents')
};
SwagClient client;
SwagPetApi api;
SwagApiResponse response;
SwagApiResponse expectedResponse;
client = new SwagClient();
api = new SwagPetApi(client);
((Swagger.OAuth2) client.getAuthentication('petstore_auth'))
.setAccessToken('foo-bar-access-token');
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "code" : 0,\n "type" : "aeiou",\n "message" : "aeiou"\n}');
expectedResponse = SwagApiResponse.getExample();
response = (SwagApiResponse) api.uploadFile(params);
System.assertEquals(expectedResponse, response);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,91 @@
@isTest
private class SwagPetTest {
@isTest
private static void equalsSameInstance() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = pet1;
SwagPet pet3 = new SwagPet();
SwagPet pet4 = pet3;
System.assert(pet1.equals(pet2));
System.assert(pet2.equals(pet1));
System.assert(pet1.equals(pet1));
System.assert(pet3.equals(pet4));
System.assert(pet4.equals(pet3));
System.assert(pet3.equals(pet3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = SwagPet.getExample();
SwagPet pet3 = new SwagPet();
SwagPet pet4 = new SwagPet();
System.assert(pet1.equals(pet2));
System.assert(pet2.equals(pet1));
System.assert(pet3.equals(pet4));
System.assert(pet4.equals(pet3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = new SwagPet();
System.assertEquals(false, pet1.equals(pet2));
System.assertEquals(false, pet2.equals(pet1));
}
@isTest
private static void notEqualsDifferentType() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = new SwagPet();
System.assertEquals(false, pet1.equals('foo'));
System.assertEquals(false, pet2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = new SwagPet();
SwagPet pet3;
System.assertEquals(false, pet1.equals(pet3));
System.assertEquals(false, pet2.equals(pet3));
}
@isTest
private static void consistentHashCodeValue() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = new SwagPet();
System.assertEquals(pet1.hashCode(), pet1.hashCode());
System.assertEquals(pet2.hashCode(), pet2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagPet pet1 = SwagPet.getExample();
SwagPet pet2 = SwagPet.getExample();
SwagPet pet3 = new SwagPet();
SwagPet pet4 = new SwagPet();
System.assert(pet1.equals(pet2));
System.assert(pet3.equals(pet4));
System.assertEquals(pet1.hashCode(), pet2.hashCode());
System.assertEquals(pet3.hashCode(), pet4.hashCode());
}
@isTest
private static void defaultValuesPopulated() {
SwagPet pet = new SwagPet();
System.assertEquals(new List<String>(), pet.photoUrls);
System.assertEquals(new List<SwagTag>(), pet.tags);
System.assertEquals(null, pet.id);
System.assertEquals(null, pet.category);
System.assertEquals(null, pet.name);
System.assertEquals(null, pet.status);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,122 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
public class SwagStoreApi {
SwagClient client;
public SwagStoreApi(SwagClient client) {
this.client = client;
}
public SwagStoreApi() {
this.client = new SwagClient();
}
public SwagClient getClient() {
return this.client;
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void deleteOrder(Map<String, Object> params) {
client.assertNotNull(params.get('orderId'), 'orderId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'DELETE', '/store/order/{orderId}', '',
query, form,
new Map<String, Object>{
'orderId' => (String) params.get('orderId')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map<String, Integer>
* @throws Swagger.ApiException if fails to make API call
*/
public Map<String, Integer> getInventory() {
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
return (Map<String, Integer>) client.invoke(
'GET', '/store/inventory', '',
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String> { 'api_key' },
Map<String, Integer>.class
);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched (required)
* @return SwagOrder
* @throws Swagger.ApiException if fails to make API call
*/
public SwagOrder getOrderById(Map<String, Object> params) {
client.assertNotNull(params.get('orderId'), 'orderId');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
return (SwagOrder) client.invoke(
'GET', '/store/order/{orderId}', '',
query, form,
new Map<String, Object>{
'orderId' => (Long) params.get('orderId')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
SwagOrder.class
);
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet (required)
* @return SwagOrder
* @throws Swagger.ApiException if fails to make API call
*/
public SwagOrder placeOrder(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
return (SwagOrder) client.invoke(
'POST', '/store/order',
(SwagOrder) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
SwagOrder.class
);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,115 @@
@isTest
private class SwagStoreApiTest {
/**
* Delete purchase order by ID
*
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*/
@isTest
private static void deleteOrderTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'orderId' => 'orderId_example'
};
SwagClient client;
SwagStoreApi api;
api = new SwagStoreApi(new SwagClient());
api.deleteOrder(params);
}
/**
* Returns pet inventories by status
*
* Returns a map of status codes to quantities
*/
@isTest
private static void getInventoryTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
SwagClient client;
SwagStoreApi api;
Map<String, Integer> response;
Map<String, Integer> expectedResponse;
client = new SwagClient();
api = new SwagStoreApi(client);
((Swagger.ApiKeyAuth) client.getAuthentication('api_key'))
.setApiKey('foo-bar-api-key');
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "key" : 0\n}');
expectedResponse = new Map<String, Integer>{'key'=>123};
response = (Map<String, Integer>) api.getInventory();
System.assertEquals(expectedResponse, response);
}
/**
* Find purchase order by ID
*
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
*/
@isTest
private static void getOrderByIdTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'orderId' => 2147483648L
};
SwagClient client;
SwagStoreApi api;
SwagOrder response;
SwagOrder expectedResponse;
api = new SwagStoreApi(new SwagClient());
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "petId" : 6,\n "quantity" : 1,\n "id" : 0,\n "shipDate" : "2000-01-23T04:56:07.000+00:00",\n "complete" : false,\n "status" : "placed"\n}');
expectedResponse = SwagOrder.getExample();
response = (SwagOrder) api.getOrderById(params);
System.assertEquals(expectedResponse, response);
}
/**
* Place an order for a pet
*
*
*/
@isTest
private static void placeOrderTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => SwagOrder.getExample()
};
SwagClient client;
SwagStoreApi api;
SwagOrder response;
SwagOrder expectedResponse;
api = new SwagStoreApi(new SwagClient());
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "petId" : 6,\n "quantity" : 1,\n "id" : 0,\n "shipDate" : "2000-01-23T04:56:07.000+00:00",\n "complete" : false,\n "status" : "placed"\n}');
expectedResponse = SwagOrder.getExample();
response = (SwagOrder) api.placeOrder(params);
System.assertEquals(expectedResponse, response);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,52 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A tag for a pet
*/
public class SwagTag {
/**
* Get id
* @return id
*/
public Long id { get; set; }
/**
* Get name
* @return name
*/
public String name { get; set; }
public static SwagTag getExample() {
SwagTag tag = new SwagTag();
tag.id = 123456789L;
tag.name = 'aeiou';
return tag;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagTag) {
SwagTag tag = (SwagTag) obj;
return this.id == tag.id
&& this.name == tag.name;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (id == null ? 0 : System.hashCode(id));
hashCode = (17 * hashCode) + (name == null ? 0 : System.hashCode(name));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,80 @@
@isTest
private class SwagTagTest {
@isTest
private static void equalsSameInstance() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = tag1;
SwagTag tag3 = new SwagTag();
SwagTag tag4 = tag3;
System.assert(tag1.equals(tag2));
System.assert(tag2.equals(tag1));
System.assert(tag1.equals(tag1));
System.assert(tag3.equals(tag4));
System.assert(tag4.equals(tag3));
System.assert(tag3.equals(tag3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = SwagTag.getExample();
SwagTag tag3 = new SwagTag();
SwagTag tag4 = new SwagTag();
System.assert(tag1.equals(tag2));
System.assert(tag2.equals(tag1));
System.assert(tag3.equals(tag4));
System.assert(tag4.equals(tag3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = new SwagTag();
System.assertEquals(false, tag1.equals(tag2));
System.assertEquals(false, tag2.equals(tag1));
}
@isTest
private static void notEqualsDifferentType() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = new SwagTag();
System.assertEquals(false, tag1.equals('foo'));
System.assertEquals(false, tag2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = new SwagTag();
SwagTag tag3;
System.assertEquals(false, tag1.equals(tag3));
System.assertEquals(false, tag2.equals(tag3));
}
@isTest
private static void consistentHashCodeValue() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = new SwagTag();
System.assertEquals(tag1.hashCode(), tag1.hashCode());
System.assertEquals(tag2.hashCode(), tag2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagTag tag1 = SwagTag.getExample();
SwagTag tag2 = SwagTag.getExample();
SwagTag tag3 = new SwagTag();
SwagTag tag4 = new SwagTag();
System.assert(tag1.equals(tag2));
System.assert(tag3.equals(tag4));
System.assertEquals(tag1.hashCode(), tag2.hashCode());
System.assertEquals(tag3.hashCode(), tag4.hashCode());
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,106 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A User who is purchasing from the pet store
*/
public class SwagUser {
/**
* Get id
* @return id
*/
public Long id { get; set; }
/**
* Get username
* @return username
*/
public String username { get; set; }
/**
* Get firstName
* @return firstName
*/
public String firstName { get; set; }
/**
* Get lastName
* @return lastName
*/
public String lastName { get; set; }
/**
* Get email
* @return email
*/
public String email { get; set; }
/**
* Get password
* @return password
*/
public String password { get; set; }
/**
* Get phone
* @return phone
*/
public String phone { get; set; }
/**
* User Status
* @return userStatus
*/
public Integer userStatus { get; set; }
public static SwagUser getExample() {
SwagUser user = new SwagUser();
user.id = 123456789L;
user.username = 'aeiou';
user.firstName = 'aeiou';
user.lastName = 'aeiou';
user.email = 'aeiou';
user.password = 'aeiou';
user.phone = 'aeiou';
user.userStatus = 123;
return user;
}
public Boolean equals(Object obj) {
if (obj instanceof SwagUser) {
SwagUser user = (SwagUser) obj;
return this.id == user.id
&& this.username == user.username
&& this.firstName == user.firstName
&& this.lastName == user.lastName
&& this.email == user.email
&& this.password == user.password
&& this.phone == user.phone
&& this.userStatus == user.userStatus;
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
hashCode = (17 * hashCode) + (id == null ? 0 : System.hashCode(id));
hashCode = (17 * hashCode) + (username == null ? 0 : System.hashCode(username));
hashCode = (17 * hashCode) + (firstName == null ? 0 : System.hashCode(firstName));
hashCode = (17 * hashCode) + (lastName == null ? 0 : System.hashCode(lastName));
hashCode = (17 * hashCode) + (email == null ? 0 : System.hashCode(email));
hashCode = (17 * hashCode) + (password == null ? 0 : System.hashCode(password));
hashCode = (17 * hashCode) + (phone == null ? 0 : System.hashCode(phone));
hashCode = (17 * hashCode) + (userStatus == null ? 0 : System.hashCode(userStatus));
return hashCode;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,223 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
public class SwagUserApi {
SwagClient client;
public SwagUserApi(SwagClient client) {
this.client = client;
}
public SwagUserApi() {
this.client = new SwagClient();
}
public SwagClient getClient() {
return this.client;
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void createUser(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'POST', '/user',
(SwagUser) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Creates list of users with given input array
*
* @param body List of user object (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void createUsersWithArrayInput(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'POST', '/user/createWithArray',
(List<SwagUser>) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Creates list of users with given input array
*
* @param body List of user object (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void createUsersWithListInput(Map<String, Object> params) {
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'POST', '/user/createWithList',
(List<SwagUser>) params.get('body'),
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void deleteUser(Map<String, Object> params) {
client.assertNotNull(params.get('username'), 'username');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'DELETE', '/user/{username}', '',
query, form,
new Map<String, Object>{
'username' => (String) params.get('username')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing. (required)
* @return SwagUser
* @throws Swagger.ApiException if fails to make API call
*/
public SwagUser getUserByName(Map<String, Object> params) {
client.assertNotNull(params.get('username'), 'username');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
return (SwagUser) client.invoke(
'GET', '/user/{username}', '',
query, form,
new Map<String, Object>{
'username' => (String) params.get('username')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
SwagUser.class
);
}
/**
* Logs user into the system
*
* @param username The user name for login (required)
* @param password The password for login in clear text (required)
* @return String
* @throws Swagger.ApiException if fails to make API call
*/
public String loginUser(Map<String, Object> params) {
client.assertNotNull(params.get('username'), 'username');
client.assertNotNull(params.get('password'), 'password');
List<Swagger.Param> query = new List<Swagger.Param>();
// cast query params to verify their expected type
query.addAll(client.makeParam('username', (String) params.get('username')));
query.addAll(client.makeParam('password', (String) params.get('password')));
List<Swagger.Param> form = new List<Swagger.Param>();
return (String) client.invoke(
'GET', '/user/login', '',
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
String.class
);
}
/**
* Logs out current logged in user session
*
* @throws Swagger.ApiException if fails to make API call
*/
public void logoutUser() {
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'GET', '/user/logout', '',
query, form,
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted (required)
* @param body Updated user object (required)
* @throws Swagger.ApiException if fails to make API call
*/
public void updateUser(Map<String, Object> params) {
client.assertNotNull(params.get('username'), 'username');
client.assertNotNull(params.get('body'), 'body');
List<Swagger.Param> query = new List<Swagger.Param>();
List<Swagger.Param> form = new List<Swagger.Param>();
client.invoke(
'PUT', '/user/{username}',
(SwagUser) params.get('body'),
query, form,
new Map<String, Object>{
'username' => (String) params.get('username')
},
new Map<String, Object>(),
new List<String>{ 'application/json' },
new List<String>{ 'application/json' },
new List<String>(),
null
);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,204 @@
@isTest
private class SwagUserApiTest {
/**
* Create user
*
* This can only be done by the logged in user.
*/
@isTest
private static void createUserTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setStatus('Created');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => SwagUser.getExample()
};
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.createUser(params);
}
/**
* Creates list of users with given input array
*
*
*/
@isTest
private static void createUsersWithArrayInputTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => new List<SwagUser>{SwagUser.getExample()}
};
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.createUsersWithArrayInput(params);
}
/**
* Creates list of users with given input array
*
*
*/
@isTest
private static void createUsersWithListInputTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'body' => new List<SwagUser>{SwagUser.getExample()}
};
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.createUsersWithListInput(params);
}
/**
* Delete user
*
* This can only be done by the logged in user.
*/
@isTest
private static void deleteUserTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'username' => 'username_example'
};
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.deleteUser(params);
}
/**
* Get user by user name
*
*
*/
@isTest
private static void getUserByNameTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'username' => 'username_example'
};
SwagClient client;
SwagUserApi api;
SwagUser response;
SwagUser expectedResponse;
api = new SwagUserApi(new SwagClient());
res.setHeader('Content-Type', 'application/json');
res.setBody('{\n "firstName" : "aeiou",\n "lastName" : "aeiou",\n "password" : "aeiou",\n "userStatus" : 6,\n "phone" : "aeiou",\n "id" : 0,\n "email" : "aeiou",\n "username" : "aeiou"\n}');
expectedResponse = SwagUser.getExample();
response = (SwagUser) api.getUserByName(params);
System.assertEquals(expectedResponse, response);
}
/**
* Logs user into the system
*
*
*/
@isTest
private static void loginUserTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'username' => 'username_example',
'password' => 'password_example'
};
SwagClient client;
SwagUserApi api;
String response;
String expectedResponse;
api = new SwagUserApi(new SwagClient());
res.setHeader('Content-Type', 'application/json');
res.setBody('"aeiou"');
expectedResponse = 'aeiou';
response = (String) api.loginUser(params);
System.assertEquals(expectedResponse, response);
}
/**
* Logs out current logged in user session
*
*
*/
@isTest
private static void logoutUserTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.logoutUser();
}
/**
* Updated user
*
* This can only be done by the logged in user.
*/
@isTest
private static void updateUserTest() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
Map<String, Object> params = new Map<String, Object>{
'username' => 'username_example',
'body' => SwagUser.getExample()
};
SwagClient client;
SwagUserApi api;
api = new SwagUserApi(new SwagClient());
api.updateUser(params);
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,80 @@
@isTest
private class SwagUserTest {
@isTest
private static void equalsSameInstance() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = user1;
SwagUser user3 = new SwagUser();
SwagUser user4 = user3;
System.assert(user1.equals(user2));
System.assert(user2.equals(user1));
System.assert(user1.equals(user1));
System.assert(user3.equals(user4));
System.assert(user4.equals(user3));
System.assert(user3.equals(user3));
}
@isTest
private static void equalsIdenticalInstance() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = SwagUser.getExample();
SwagUser user3 = new SwagUser();
SwagUser user4 = new SwagUser();
System.assert(user1.equals(user2));
System.assert(user2.equals(user1));
System.assert(user3.equals(user4));
System.assert(user4.equals(user3));
}
@isTest
private static void notEqualsUnlikeInstance() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = new SwagUser();
System.assertEquals(false, user1.equals(user2));
System.assertEquals(false, user2.equals(user1));
}
@isTest
private static void notEqualsDifferentType() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = new SwagUser();
System.assertEquals(false, user1.equals('foo'));
System.assertEquals(false, user2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = new SwagUser();
SwagUser user3;
System.assertEquals(false, user1.equals(user3));
System.assertEquals(false, user2.equals(user3));
}
@isTest
private static void consistentHashCodeValue() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = new SwagUser();
System.assertEquals(user1.hashCode(), user1.hashCode());
System.assertEquals(user2.hashCode(), user2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
SwagUser user1 = SwagUser.getExample();
SwagUser user2 = SwagUser.getExample();
SwagUser user3 = new SwagUser();
SwagUser user4 = new SwagUser();
System.assert(user1.equals(user2));
System.assert(user3.equals(user4));
System.assertEquals(user1.hashCode(), user2.hashCode());
System.assertEquals(user3.hashCode(), user4.hashCode());
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,395 @@
public class Swagger {
private static final String HEADER_CONTENT_TYPE = 'Content-Type';
private static final String HEADER_ACCEPT = 'Accept';
private static final String HEADER_ACCEPT_DELIMITER = ',';
private static final Map<String, String> DELIMITERS = new Map<String, String> {
'csv' => ',',
'ssv' => ' ',
'tsv' => '\t',
'pipes' => '|'
};
public class Param {
private String name, value;
public Param(String name, String value) {
this.name = name;
this.value = value;
}
public override String toString() {
return EncodingUtil.urlEncode(name, 'UTF-8') + '='
+ EncodingUtil.urlEncode(value, 'UTF-8');
}
}
public interface Authentication {
void apply(Map<String, Object> headers, List<Param> query);
}
public interface MappedProperties {
Map<String, String> getPropertyMappings();
}
public abstract class ApiKeyAuth implements Authentication {
protected final String paramName;
protected String key = '';
public void setApiKey(String key) {
this.key = key;
}
@TestVisible
private String getApiKey() {
return key;
}
}
public class ApiKeyQueryAuth extends ApiKeyAuth {
public ApiKeyQueryAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
query.add(new Param(paramName, key));
}
}
public class ApiKeyHeaderAuth extends ApiKeyAuth {
public ApiKeyHeaderAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put(paramName, key);
}
}
public class HttpBasicAuth implements Authentication {
private String username = '';
private String password = '';
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setCredentials(String username, String password) {
setUsername(username);
setPassword(password);
}
@TestVisible
private String getHeaderValue() {
return 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password));
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class OAuth2 implements Authentication {
private String accessToken = '';
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@TestVisible
private String getHeaderValue() {
return 'Bearer ' + accessToken;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class ApiException extends Exception {
private final Integer code;
private final String status;
private final Map<String, String> headers;
private final String body;
public ApiException(Integer code, String status, Map<String, String> headers, String body) {
this('API returned HTTP ' + code + ': ' + status);
this.code = code;
this.status = status;
this.headers = headers;
this.body = body;
}
public Integer getStatusCode() {
return code;
}
public String getStatus() {
return status;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}
public virtual class ApiClient {
protected String preferredContentType = 'application/json';
protected String preferredAccept = 'application/json';
protected final String basePath;
@TestVisible
protected final Map<String, Authentication> authentications = new Map<String, Authentication>();
public virtual Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
public virtual void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setCredentials(String username, String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setCredentials(username, password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new NoSuchElementException('No API key authentication configured!');
}
public virtual void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth2) {
((OAuth2) auth).setAccessToken(accessToken);
return;
}
}
throw new NoSuchElementException('No OAuth2 authentication configured!');
}
public List<Param> makeParams(String name, List<Object> values) {
List<Param> pairs = new List<Param>();
for (Object value : new List<Object>(values)) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public List<Param> makeParam(String name, List<Object> values, String format) {
List<Param> pairs = new List<Param>();
if (values != null) {
String delimiter = DELIMITERS.get(format);
pairs.add(new Param(name, String.join(values, delimiter)));
}
return pairs;
}
public List<Param> makeParam(String name, Object value) {
List<Param> pairs = new List<Param>();
if (value != null) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public virtual void assertNotNull(Object required, String parameterName) {
if (required == null) {
Exception e = new NullPointerException();
e.setMessage('Argument cannot be null: ' + parameterName);
throw e;
}
}
public virtual Object invoke(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods, Type returnType) {
HttpResponse res = getResponse(method, path, body, query, form, pathParams, headers,
accepts, contentTypes, authMethods);
Integer code = res.getStatusCode();
Boolean isFailure = code / 100 != 2;
if (isFailure) {
throw new ApiException(code, res.getStatus(), getHeaders(res), res.getBody());
} else if (returnType != null) {
return toReturnValue(res.getBody(), returnType, res.getHeader('Content-Type'));
}
return null;
}
@TestVisible
protected virtual Map<String, String> getHeaders(HttpResponse res) {
Map<String, String> headers = new Map<String, String>();
List<String> headerKeys = res.getHeaderKeys();
for (String headerKey : headerKeys) {
headers.put(headerKey, res.getHeader(headerKey));
}
return headers;
}
@TestVisible
protected virtual Object toReturnValue(String body, Type returnType, String contentType) {
if (contentType == 'application/json') {
Object o = returnType.newInstance();
if (o instanceof MappedProperties) {
Map<String, String> propertyMappings = ((MappedProperties) o).getPropertyMappings();
for (String baseName : propertyMappings.keySet()) {
body = body.replaceAll('"' + baseName + '"\\s*:',
'"' + propertyMappings.get(baseName) + '":');
}
}
JsonParser parser = Json.createParser(body);
parser.nextToken();
return parser.readValueAs(returnType);
}
return body;
}
@TestVisible
protected virtual HttpResponse getResponse(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods) {
HttpRequest req = new HttpRequest();
applyAuthentication(authMethods, headers, query);
req.setMethod(method);
req.setEndpoint(toEndpoint(path, pathParams, query));
String contentType = setContentTypeHeader(contentTypes, headers);
setAcceptHeader(accepts, headers);
setHeaders(req, headers);
if (method != 'GET') {
req.setBody(toBody(contentType, body, form));
}
return new Http().send(req);
}
@TestVisible
protected virtual void setHeaders(HttpRequest req, Map<String, Object> headers) {
for (String headerName : headers.keySet()) {
req.setHeader(headerName, String.valueOf(headers.get(headerName)));
}
}
@TestVisible
protected virtual String toBody(String contentType, Object body, List<Param> form) {
if (contentType.contains('application/x-www-form-urlencoded')) {
return paramsToString(form);
} else if (contentType.contains('application/json')) {
return Json.serialize(body);
}
return String.valueOf(body);
}
@TestVisible
protected virtual String setContentTypeHeader(List<String> contentTypes,
Map<String, Object> headers) {
if (contentTypes.isEmpty()) {
headers.put(HEADER_CONTENT_TYPE, preferredContentType);
return preferredContentType;
}
for (String contentType : contentTypes) {
if (preferredContentType == contentType) {
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
}
String contentType = contentTypes.get(0);
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
@TestVisible
protected virtual void setAcceptHeader(List<String> accepts, Map<String, Object> headers) {
for (String accept : accepts) {
if (preferredAccept == accept) {
headers.put(HEADER_ACCEPT, accept);
return;
}
}
if (!accepts.isEmpty()) {
headers.put(HEADER_ACCEPT, String.join(accepts, HEADER_ACCEPT_DELIMITER));
}
}
@TestVisible
protected virtual void applyAuthentication(List<String> names, Map<String, Object> headers,
List<Param> query) {
for (Authentication auth : getAuthMethods(names)) {
auth.apply(headers, query);
}
}
@TestVisible
protected virtual List<Authentication> getAuthMethods(List<String> names) {
List<Authentication> authMethods = new List<Authentication>();
for (String name : names) {
authMethods.add(authentications.get(name));
}
return authMethods;
}
@TestVisible
protected virtual String toPath(String path, Map<String, Object> params) {
String formatted = path;
for (String key : params.keySet()) {
formatted = formatted.replace('{' + key + '}', String.valueOf(params.get(key)));
}
return formatted;
}
@TestVisible
protected virtual String toEndpoint(String path, Map<String, Object> params,
List<Param> queryParams) {
String query = '?' + paramsToString(queryParams);
return basePath + toPath(path, params) + query.removeEnd('?');
}
@TestVisible
protected virtual String paramsToString(List<Param> params) {
String s = '';
for (Param p : params) {
s += '&' + p;
}
return s.removeStart('&');
}
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,18 @@
@isTest
public class SwaggerResponseMock implements HttpCalloutMock {
private final HttpResponse response;
private HttpRequest request;
public SwaggerResponseMock(HttpResponse response) {
this.response = response;
}
public HttpResponse respond(HttpRequest request) {
this.request = request;
return response;
}
public HttpRequest getRequest() {
return request;
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,782 @@
@isTest
private class SwaggerTest {
@isTest
private static void Param_urlEncodeKeyValuePairUtf8() {
String toEncodeLeft = 'Hello +%-_.!~*\'()@';
String toEncodeRight = 'World +%-_.!~*\'()@';
String expected = 'Hello+%2B%25-_.%21%7E*%27%28%29%40=World+%2B%25-_.%21%7E*%27%28%29%40';
String result = new Swagger.Param(toEncodeLeft, toEncodeRight).toString();
System.assertEquals(expected, result);
}
@isTest
private static void ApiKeyHeaderAuth_keyInHeaderWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyHeaderAuth auth = new Swagger.ApiKeyHeaderAuth('X-Authenticate');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authenticate'));
}
@isTest
private static void ApiKeyQueryAuth_keyInQueryParamWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyQueryAuth auth = new Swagger.ApiKeyQueryAuth('auth_token');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(headers.isEmpty());
System.assertEquals(1, query.size());
System.assertEquals('auth_token=foo-bar-api-key', query.get(0).toString());
}
@isTest
private static void HttpBasicAuth_base64EncodeCredentials() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setCredentials('username', 'password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void HttpBasicAuth_base64EncodeUsernamePassword() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setUsername('username');
auth.setPassword('password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void OAuth2_tokenInAuthorizationHeaderWithBearerPrefix() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Bearer foo-bar-api-key', headers.get('Authorization'));
}
@isTest
private static void ApiClient_returnAuthenticationMatchingInput() {
MockApiClient client = new MockApiClient();
Swagger.ApiKeyHeaderAuth auth1 = new Swagger.ApiKeyHeaderAuth('foo');
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('foo');
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
System.assertEquals(auth1, client.getAuthentication('auth1'));
System.assertEquals(auth2, client.getAuthentication('auth2'));
System.assertEquals(auth3, client.getAuthentication('auth3'));
System.assertEquals(auth4, client.getAuthentication('auth4'));
}
@isTest
private static void ApiClient_noAuthenticationsMatchInputReturnNull() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth = new Swagger.OAuth2();
client.authentications.put('auth', auth);
System.assertEquals(auth, client.getAuthentication('auth'));
System.assertEquals(null, client.getAuthentication('no-auth'));
}
@isTest
private static void ApiClient_setUsernamePasswordFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setUsername('username');
client.setPassword('password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setUsernameExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setUsername('username');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setPasswordExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setPassword('password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setCredentialsFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setCredentials('username', 'password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setCredentialsExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setCredentials('username', 'password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setApiKeyFirstKeyAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.HttpBasicAuth auth2 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth4 = new Swagger.ApiKeyQueryAuth('auth4');
Swagger.ApiKeyHeaderAuth auth5 = new Swagger.ApiKeyHeaderAuth('auth5');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setApiKey('foo-bar-api-key');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('Basic Og==', auth2.getHeaderValue());
System.assertEquals('Basic Og==', auth3.getHeaderValue());
System.assertEquals('foo-bar-api-key', auth4.getApiKey());
System.assertEquals('', auth5.getApiKey());
}
@isTest
private static void ApiClient_setApiKeyExceptionNoKeyAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setApiKey('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setAccessTokenFirstOauthOnly() {
MockApiClient client = new MockApiClient();
Swagger.HttpBasicAuth auth1 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
Swagger.OAuth2 auth5 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setAccessToken('foo-bar-api-key');
System.assertEquals('Basic Og==', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Bearer foo-bar-api-key', auth4.getHeaderValue());
System.assertEquals('Bearer ', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setAccessTokenExceptionNoOAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setAccessToken('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_oneKeyValuePairForEachValueInList() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', values);
System.assertEquals(5, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=4', params.get(1).toString());
System.assertEquals('foo=false', params.get(2).toString());
System.assertEquals('foo=12.4', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
}
@isTest
private static void ApiClient_nullMultiValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', null);
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_valuesListToSingleCsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'csv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%2C4%2Cfalse%2C12.4%2C', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleSsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'ssv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar+4+false+12.4+', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleTsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'tsv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%094%09false%0912.4%09', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSinglePipeSeparatedKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'pipes');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%7C4%7Cfalse%7C12.4%7C', params.get(0).toString());
}
@isTest
private static void ApiClient_nullValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', null, 'csv');
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_paramsFromAnyPrimitiveTypeDiscardNull() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = new List<Swagger.Param>();
params.addAll(client.makeParam('foo', 'bar'));
params.addAll(client.makeParam('foo', 10));
params.addAll(client.makeParam('foo', 12.6));
params.addAll(client.makeParam('foo', true));
params.addAll(client.makeParam('foo', ''));
params.addAll(client.makeParam('foo', Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0)));
params.addAll(client.makeParam('foo', null));
System.assertEquals(6, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=10', params.get(1).toString());
System.assertEquals('foo=12.6', params.get(2).toString());
System.assertEquals('foo=true', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
System.assertEquals('foo=2017-01-01+15%3A00%3A00', params.get(5).toString());
}
@isTest
private static void ApiClient_requiredParameterPasses() {
Swagger.ApiClient client = new Swagger.ApiClient();
client.assertNotNull('foo', 'bar');
}
@isTest
private static void ApiClient_requiredParameterFails() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.assertNotNull(null, 'bar');
} catch (NullPointerException e) {
System.assertEquals('Argument cannot be null: bar', e.getMessage());
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_extractHeadersFromResponse() {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'private, max-age=0');
Map<String, String> headers = new MockApiClient().getHeaders(res);
System.assertEquals(2, headers.size());
System.assertEquals('application/json', headers.get('Content-Type'));
System.assertEquals('private, max-age=0', headers.get('Cache-Control'));
}
@isTest
private static void ApiClient_deserializeResponseBodyByContentType() {
MockApiClient client = new MockApiClient();
String jsonBody = '{"red":"apple","yellow":"banana","orange":"orange"}';
Map<String, String> result1 = (Map<String, String>) client
.toReturnValue(jsonBody, Map<String, String>.class, 'application/json');
System.assertEquals(3, result1.size());
System.assertEquals('apple', result1.get('red'));
System.assertEquals('banana', result1.get('yellow'));
System.assertEquals('orange', result1.get('orange'));
String result2 = (String) client
.toReturnValue('Hello, World!', String.class, 'text/plain');
System.assertEquals('Hello, World!', result2);
}
@isTest
private static void ApiClient_addStringifiedHeadersToRequest() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>{
'Content-Type' => 'application/json',
'Max-Forwards' => 10
};
HttpRequest req = new HttpRequest();
client.setHeaders(req, headers);
System.assertEquals('application/json', req.getHeader('Content-Type'));
System.assertEquals('10', req.getHeader('Max-Forwards'));
}
@isTest
private static void ApiClient_serializeRequestBodyOrFormByContentType() {
MockApiClient client = new MockApiClient();
Map<String, Object> body1 = new Map<String, Object>{
'hello' => 'world',
'foo' => 15,
'bar' => Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0),
'bat' => false
};
Set<String> expected1 = new Set<String>{
'"hello":"world"',
'"foo":15',
'"bar":"2017-01-01T15:00:00.000Z"',
'"bat":false'
};
Set<String> actual1 = new Set<String>(client
.toBody('application/json', body1, new List<Swagger.Param>())
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(expected1, actual1);
String body2 = 'Hello, World!';
String actual2 = client.toBody('text/plain', body2, new List<Swagger.Param>());
System.assertEquals(body2, actual2);
List<Swagger.Param> form = new List<Swagger.Param>{
new Swagger.Param('hello', 'world'),
new Swagger.Param('date', '2017-01-01 15:00:00')
};
String expected3 = 'hello=world&date=2017-01-01+15%3A00%3A00';
String actual3 = client.toBody('application/x-www-form-urlencoded', '', form);
System.assertEquals(expected3, actual3);
}
@isTest
private static void ApiClient_usePreferredContentTypeOrFirstInList() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
String result1 = client.setContentTypeHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Content-Type'));
System.assertEquals('application/json', result1);
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
String result2 = client.setContentTypeHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml', headers2.get('Content-Type'));
System.assertEquals('application/xml', result2);
Map<String, Object> headers3 = new Map<String, Object>();
String result3 = client.setContentTypeHeader(new List<String>(), headers3);
System.assertEquals(1, headers3.size());
System.assertEquals('application/json', headers3.get('Content-Type'));
System.assertEquals('application/json', result3);
}
@isTest
private static void ApiClient_usePreferredAcceptOrAllInListNoDefault() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
client.setAcceptHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Accept'));
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
client.setAcceptHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml,text/plain', headers2.get('Accept'));
Map<String, Object> headers3 = new Map<String, Object>();
client.setAcceptHeader(new List<String>(), headers3);
System.assert(headers3.isEmpty());
}
@isTest
private static void ApiClient_applyOnlyGivenAuthMethodsToParams() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyHeaderAuth auth2 = new Swagger.ApiKeyHeaderAuth('X-Authentication-Token');
auth1.setAccessToken('boo-bat-api-key');
auth2.setApiKey('foo-bar-api-key');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.applyAuthentication(new List<String>{'auth2'}, headers, new List<Swagger.Param>());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authentication-Token'));
}
@isTest
private static void ApiClient_formUrlWithQueryParamsPathParams() {
MockApiClient client = new MockApiClient();
String path = '/departments/{department}';
Map<String, Object> params = new Map<String, Object>{'department' => 'finance'};
List<Swagger.Param> queryParams = new List<Swagger.Param>{
new Swagger.Param('foo', 'bar'),
new Swagger.Param('bat', '123')
};
String expected = 'https://www.mccombs.utexas.edu/departments/finance?foo=bar&bat=123';
String actual = client.toEndpoint(path, params, queryParams);
System.assertEquals(expected, actual);
}
@isTest
private static void ApiClient_setupRequestWithBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}',
new Map<String, Object> {
'title' => 'Chapter 4 quiz',
'timed' => true,
'time' => 60,
'points' => 20.5,
'due' => Datetime.newInstanceGmt(2016, 5, 10, 23, 59, 59),
'description' => ''
},
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'application/json', 'application/xml'},
new List<String>{'application/json', 'application/xml'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req
.getBody()
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('"title":"Chapter 4 quiz"'));
System.assert(body.contains('"timed":true'));
System.assert(body.contains('"time":60'));
System.assert(body.contains('"points":20.5'));
System.assert(body.contains('"due":"2016-05-10T23:59:59.000Z"'));
System.assert(body.contains('"description":""'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('application/json', req.getHeader('Accept'));
System.assertEquals('application/json', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithForm() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>{
new Swagger.Param('title', 'Chapter 4 quiz'),
new Swagger.Param('timed', 'true'),
new Swagger.Param('time', '60'),
new Swagger.Param('points', '20.5'),
new Swagger.Param('due', '2016-05-10 18:59:59'),
new Swagger.Param('description', 'complete & upload \'section1: advanced\'')
},
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'text/html', 'application/xml'},
new List<String>{'application/x-www-form-urlencoded'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req.getBody().split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('title=Chapter+4+quiz'));
System.assert(body.contains('timed=true'));
System.assert(body.contains('time=60'));
System.assert(body.contains('points=20.5'));
System.assert(body.contains('due=2016-05-10+18%3A59%3A59'));
System.assert(body.contains('description=complete+%26+upload+%27section1%3A+advanced%27'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('text/html,application/xml', req.getHeader('Accept'));
System.assertEquals('application/x-www-form-urlencoded', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithQuery() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'GET', '/courses/{course}/assignments', '',
new List<Swagger.Param>{
new Swagger.Param('title', '#chapter1:section2'),
new Swagger.Param('due', '2016-05-10 18:59:59')
},
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/xml'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
List<String> splitUrl = req.getEndpoint().split('\\?');
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments';
Set<String> query = new Set<String>(splitUrl.get(1).split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, splitUrl.get(0));
System.assertEquals(2, query.size());
System.assert(query.contains('title=%23chapter1%3Asection2'));
System.assert(query.contains('due=2016-05-10+18%3A59%3A59'));
System.assertEquals('GET', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('application/xml', req.getHeader('Accept'));
System.assertEquals('text/plain', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_nonSuccessfulStatusCodeException() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('Not Found');
res.setStatusCode(404);
res.setHeader('X-Request-ID', '1234567890');
res.setHeader('Content-Type', 'application/json');
res.setBody('{"error":"the specified course does not exist"}');
try {
client.invoke(
'GET', '/courses/{course}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'},
null
);
} catch (Swagger.ApiException e) {
Map<String, String> headers = e.getHeaders();
System.assertEquals('API returned HTTP 404: Not Found', e.getMessage());
System.assertEquals(404, e.getStatusCode());
System.assertEquals('Not Found', e.getStatus());
System.assertEquals('{"error":"the specified course does not exist"}', e.getBody());
System.assertEquals(2, headers.size());
System.assertEquals('1234567890', headers.get('X-Request-ID'));
System.assertEquals('application/json', headers.get('Content-Type'));
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_returnParsedBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{'
+ '"city":"Austin","country":"United States","latitude":30.28403639999999,'
+ '"longitude":-97.73789449999998,"postalCode":"78705","state":"Texas",'
+ '"street":"2110 Speedway"}');
Address a = (Address) client.invoke(
'GET', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
Address.class
);
System.assertEquals('Austin', a.getCity());
System.assertEquals('United States', a.getCountry());
System.assertEquals(30.28403639999999, a.getLatitude());
System.assertEquals(-97.73789449999998, a.getLongitude());
System.assertEquals('78705', a.getPostalCode());
System.assertEquals('Texas', a.getState());
System.assertEquals('2110 Speedway', a.getStreet());
}
@isTest
private static void ApiClient_noReturnTypeReturnsNull() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
Object o = client.invoke(
'POST', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
null
);
System.assertEquals(null, o);
}
private class MockApiClient extends Swagger.ApiClient {
public MockApiClient() {
basePath = 'https://www.mccombs.utexas.edu';
}
}
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>36.0</apiVersion>
<status>Active</status>
</ApexClass>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Swagger Petstore API Client</fullName>
<description>Client library for calling the Swagger Petstore API.
This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
Generated with Swagger Codegen (github.com/swagger-api/swagger-codegen)</description>
<types>
<members>SwagPetApi</members>
<members>SwagPetApiTest</members>
<members>SwagStoreApi</members>
<members>SwagStoreApiTest</members>
<members>SwagUserApi</members>
<members>SwagUserApiTest</members>
<members>SwagApiResponse</members>
<members>SwagApiResponseTest</members>
<members>SwagCategory</members>
<members>SwagCategoryTest</members>
<members>SwagOrder</members>
<members>SwagOrderTest</members>
<members>SwagPet</members>
<members>SwagPetTest</members>
<members>SwagTag</members>
<members>SwagTagTest</members>
<members>SwagUser</members>
<members>SwagUserTest</members>
<members>SwagClient</members>
<members>Swagger</members>
<members>SwaggerTest</members>
<members>SwaggerResponseMock</members>
<name>ApexClass</name>
</types>
<types>
<members>Swagger_Petstore</members>
<name>RemoteSiteSetting</name>
</types>
<version>36.0</version>
</Package>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">
<description>This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authori</description>
<disableProtocolSecurity>false</disableProtocolSecurity>
<isActive>true</isActive>
<url>http://petstore.swagger.io/v2</url>
</RemoteSiteSetting>

View File

@@ -0,0 +1,12 @@
# SwagApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **Integer** | | [optional]
**r_type** | **String** | | [optional]
**message** | **String** | | [optional]

View File

@@ -0,0 +1,11 @@
# SwagCategory
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**name** | **String** | | [optional]

View File

@@ -0,0 +1,24 @@
# SwagOrder
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**petId** | **Long** | | [optional]
**quantity** | **Integer** | | [optional]
**shipDate** | **Datetime** | | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional]
**complete** | **Boolean** | | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PLACED | &quot;placed&quot;
APPROVED | &quot;approved&quot;
DELIVERED | &quot;delivered&quot;

View File

@@ -0,0 +1,24 @@
# SwagPet
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**category** | [**SwagCategory**](SwagCategory.md) | | [optional]
**name** | **String** | |
**photoUrls** | **List&lt;String&gt;** | |
**tags** | [**List&lt;SwagTag&gt;**](SwagTag.md) | | [optional]
**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
AVAILABLE | &quot;available&quot;
PENDING | &quot;pending&quot;
SOLD | &quot;sold&quot;

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