diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index ea5aad656b5..d44a7b1cb7c 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -35,3 +35,5 @@ cd $APP_DIR ./bin/silex-petstore-server.sh ./bin/spring-mvc-petstore-server.sh ./bin/tizen-petstore.sh +./bin/typescript-angular-petstore.sh +./bin/typescript-node-petstore.sh diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh index a72a6cf84f0..c3fe78f0f36 100755 --- a/bin/csharp-petstore.sh +++ b/bin/csharp-petstore.sh @@ -26,6 +26,6 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l csharp -o samples/client/petstore/csharp" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l csharp -o samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/silex-petstore-server.sh b/bin/silex-petstore-server.sh index 5ead9db0002..ffa030b88c3 100755 --- a/bin/silex-petstore-server.sh +++ b/bin/silex-petstore-server.sh @@ -26,6 +26,6 @@ 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/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l silex -o samples/client/petstore/silex" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l silex -o samples/server/petstore/silex" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/sinatra-petstore-server.sh b/bin/sinatra-petstore-server.sh new file mode 100755 index 00000000000..4f7e19cee39 --- /dev/null +++ b/bin/sinatra-petstore-server.sh @@ -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/sinatra -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l sinatra -o samples/server/petstore/sinatra" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-angular-petstore.sh b/bin/typescript-angular-petstore.sh new file mode 100755 index 00000000000..60c10790c90 --- /dev/null +++ b/bin/typescript-angular-petstore.sh @@ -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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular -o samples/client/petstore/typescript-angular" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-node-petstore.sh b/bin/typescript-node-petstore.sh new file mode 100755 index 00000000000..53c5a6f8d82 --- /dev/null +++ b/bin/typescript-node-petstore.sh @@ -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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -o samples/client/petstore/typescript-node" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index a564ec5f883..33ea13b5e31 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -7,6 +7,7 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.codegen.CliOption; import java.io.File; import java.util.Arrays; @@ -14,15 +15,14 @@ import java.util.HashMap; import java.util.HashSet; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "IO.Swagger.Client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-csharp-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/csharp"; + protected String packageName = "IO.Swagger"; + protected String packageVersion = "1.0.0"; + protected String clientPackage = "IO.Swagger.Client"; + protected String sourceFolder = "src" + File.separator + "main" + File.separator + "csharp"; public CSharpClientCodegen() { super(); - outputFolder = "generated-code/csharp"; + outputFolder = "generated-code" + File.separator + "csharp"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); templateDir = "csharp"; @@ -34,17 +34,6 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") ); - additionalProperties.put("invokerPackage", invokerPackage); - - supportingFiles.add(new SupportingFile("Configuration.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); - supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); - supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); - supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); languageSpecificPrimitives = new HashSet( Arrays.asList( @@ -85,6 +74,43 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("map", "Dictionary"); typeMapping.put("object", "Object"); + cliOptions.clear(); + cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); + cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); + + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("packageVersion")) { + packageVersion = (String) additionalProperties.get("packageVersion"); + } else { + additionalProperties.put("packageVersion", packageVersion); + } + + if (additionalProperties.containsKey("packageName")) { + packageName = (String) additionalProperties.get("packageName"); + apiPackage = packageName + ".Api"; + modelPackage = packageName + ".Model"; + clientPackage = packageName + ".Client"; + } else { + additionalProperties.put("packageName", packageName); + } + + additionalProperties.put("clientPackage", clientPackage); + + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); + supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); + supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); + supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); + } public CodegenType getTag() { @@ -106,11 +132,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String apiFileFolder() { - return (outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/')).replace('.', File.separatorChar); + return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); } public String modelFileFolder() { - return (outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/')).replace('.', File.separatorChar); + return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 0690163f137..e2ddba4bf34 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -18,12 +19,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "Swagger\\Client"; protected String groupId = "swagger"; protected String artifactId = "swagger-client"; + protected String packagePath = "SwaggerClient-php"; protected String artifactVersion = null; + protected String srcBasePath = "lib"; public PhpClientCodegen() { super(); - outputFolder = "generated-code/php"; + outputFolder = "generated-code" + File.separator + "php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; @@ -38,6 +41,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("modelPackage", modelPackage); additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("srcBasePath", srcBasePath); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("groupId", groupId); additionalProperties.put("artifactId", artifactId); @@ -81,16 +85,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("list", "array"); typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - - supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, "lib"), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); - supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); + + cliOptions.add(new CliOption("packagePath", "main package name for classes")); + cliOptions.add(new CliOption("srcBasePath", "directory directory under packagePath to serve as source root")); } public String getPackagePath() { - return "SwaggerClient-php"; + return packagePath; } public String toPackagePath(String packageName, String basePath) { @@ -99,13 +100,27 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; } + String regFirstPathSeparator; + if ("/".equals(File.separator)) { // for mac, linux + regFirstPathSeparator = "^/"; + } else { // for windows + regFirstPathSeparator = "^\\\\"; + } + + String regLastPathSeparator; + if ("/".equals(File.separator)) { // for mac, linux + regLastPathSeparator = "/$"; + } else { // for windows + regLastPathSeparator = "\\\\$"; + } + return (getPackagePath() + File.separatorChar + basePath // Replace period, backslash, forward slash with file separator in package name + packageName.replaceAll("[\\.\\\\/]", File.separator) // Trim prefix file separators from package path - .replaceAll("^" + File.separator, "")) - // Trim trailing file separators from the overall path - .replaceAll(File.separator + "$", ""); + .replaceAll(regFirstPathSeparator, "")) + // Trim trailing file separators from the overall path + .replaceAll(regLastPathSeparator+ "$", ""); } public CodegenType getTag() { @@ -120,6 +135,39 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a PHP client library."; } + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("packagePath")) { + this.setPackagePath((String) additionalProperties.get("packagePath")); + } + + if (additionalProperties.containsKey("srcBasePath")) { + this.setSrcBasePath((String) additionalProperties.get("srcBasePath")); + } + + if (additionalProperties.containsKey("modelPackage")) { + this.setModelPackage((String) additionalProperties.get("modelPackage")); + } + + if (additionalProperties.containsKey("apiPackage")) { + this.setApiPackage((String) additionalProperties.get("apiPackage")); + } + + additionalProperties.put("srcBasePath", srcBasePath); + additionalProperties.put("modelPackage", modelPackage); + additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); + + supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); + supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); + supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); + supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); + } + @Override public String escapeReservedWord(String name) { return "_" + name; @@ -127,11 +175,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/" + toPackagePath(apiPackage(), "lib")); + return (outputFolder + "/" + toPackagePath(apiPackage(), srcBasePath)); } public String modelFileFolder() { - return (outputFolder + "/" + toPackagePath(modelPackage(), "lib")); + return (outputFolder + "/" + toPackagePath(modelPackage(), srcBasePath)); } @Override @@ -184,6 +232,17 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return "null"; } + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setPackagePath(String packagePath) { + this.packagePath = packagePath; + } + + public void setSrcBasePath(String srcBasePath) { + this.srcBasePath = srcBasePath; + } @Override public String toVarName(String name) { @@ -221,5 +280,4 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as the model name return toModelName(name); } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index a14fa71f425..475a816aa5c 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -13,25 +14,19 @@ import java.util.Arrays; import java.util.HashSet; public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String module = "SwaggerPetstore"; - protected String invokerPackage; - protected String eggPackage; + protected String packageName = null; + protected String packageVersion = null; public PythonClientCodegen() { super(); - eggPackage = module + "-python"; - - invokerPackage = eggPackage + File.separatorChar + module; - + modelPackage = "models"; + apiPackage = "api"; outputFolder = "generated-code" + File.separatorChar + "python"; modelTemplateFiles.put("model.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py"); templateDir = "python"; - apiPackage = invokerPackage + File.separatorChar + "apis"; - modelPackage = invokerPackage + File.separatorChar + "models"; - languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); @@ -60,14 +55,43 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try")); - additionalProperties.put("module", module); + cliOptions.clear(); + cliOptions.add(new CliOption("packageName", "python package name (convension: under_score), default: swagger_client")); + cliOptions.add(new CliOption("packageVersion", "python package version, default: 1.0.0")); + } - supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); - supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); - supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); - supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); - supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); - supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("packageName")) { + setPackageName((String) additionalProperties.get("packageName")); + } + else { + setPackageName("swagger_client"); + } + + if (additionalProperties.containsKey("packageVersion")) { + setPackageVersion((String) additionalProperties.get("packageVersion")); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put("packageName", packageName); + additionalProperties.put("packageVersion", packageVersion); + + String swaggerFolder = packageName; + + modelPackage = swaggerFolder + File.separatorChar + "models"; + apiPackage = swaggerFolder + File.separatorChar + "apis"; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); + supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); + supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); } @@ -225,4 +249,23 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return underscore(operationId); } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + /** + * Generate Python package name from String `packageName` + * + * (PEP 0008) Python packages should also have short, all-lowercase names, + * although the use of underscores is discouraged. + */ + public String generatePackageName(String packageName) { + return underscore(packageName.replaceAll("[^\\w]+", "")); + } } + + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index d8c143aad1d..6ad296a0210 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -20,6 +20,9 @@ import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; @@ -214,4 +217,17 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(operationId, true); } + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid warnings for importing class in the same package in Scala + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage() + "."; + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) iterator.remove(); + } + return objs; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java new file mode 100644 index 00000000000..44cf978eb1d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -0,0 +1,215 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; + +public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String gemName = null; + protected String moduleName = null; + protected String gemVersion = "1.0.0"; + protected String libFolder = "lib"; + + public SinatraServerCodegen() { + super(); + apiPackage = "lib"; + outputFolder = "generated-code" + File.separator + "sinatra"; + + // no model + modelTemplateFiles.clear(); + apiTemplateFiles.put("api.mustache", ".rb"); + templateDir = "sinatra"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + reservedWords = new HashSet( + Arrays.asList( + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") + ); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); + + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); + + // remove modelPackage and apiPackage added by default + cliOptions.clear(); + } + + @Override + public void processOpts() { + super.processOpts(); + + // use constant model/api package (folder path) + //setModelPackage("models"); + setApiPackage("api"); + + supportingFiles.add(new SupportingFile("my_app.mustache", "", "my_app.rb")); + supportingFiles.add(new SupportingFile("Swaggering.rb", libFolder, "swaggering.rb")); + supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); + supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "sinatra"; + } + + public String getHelp() { + return "Generates a Sinatra server library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } + return type; + } + + public String toDefaultValue(Property p) { + return "null"; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // camelize (lower first character) the variable name + // petId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(operationId); + } + + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java new file mode 100644 index 00000000000..a31e15878cf --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -0,0 +1,25 @@ +package io.swagger.codegen.languages; + +import java.io.File; + +import io.swagger.codegen.SupportingFile; + +public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen { + + @Override + public String getName() { + return "typescript-angular"; + } + + public TypeScriptAngularClientCodegen() { + super(); + outputFolder = "generated-code/typescript-angular"; + modelTemplateFiles.put("model.mustache", ".ts"); + apiTemplateFiles.put("api.mustache", ".ts"); + templateDir = "TypeScript-Angular"; + apiPackage = "api"; + modelPackage = "api"; + + supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java new file mode 100644 index 00000000000..19b8514f8e3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -0,0 +1,169 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class TypeScriptNodeClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-typescript-node-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/typescript"; + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "typescript-node"; + } + + @Override + public String getHelp() { + return "Generates a TypeScript nodejs client library."; + } + + public TypeScriptNodeClientCodegen() { + super(); + outputFolder = "generated-code/typescript-node"; + modelTemplateFiles.put("model.mustache", ".ts"); + apiTemplateFiles.put("api.mustache", ".ts"); + templateDir = "TypeScript-node"; + apiPackage = "api"; + modelPackage = "model"; + + reservedWords = new HashSet(Arrays.asList("abstract", + "continue", "for", "new", "switch", "assert", "default", "if", + "package", "synchronized", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", + "byte", "else", "import", "public", "throws", "case", "enum", + "instanceof", "return", "transient", "catch", "extends", "int", + "short", "try", "char", "final", "interface", "static", "void", + "class", "finally", "const", "super", "while")); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + languageSpecificPrimitives = new HashSet(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object")); + instantiationTypes.put("array", "Array"); + + typeMapping = new HashMap(); + typeMapping.put("Array", "Array"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "number"); + typeMapping.put("float", "number"); + typeMapping.put("number", "number"); + typeMapping.put("long", "number"); + typeMapping.put("short", "number"); + typeMapping.put("char", "string"); + typeMapping.put("double", "number"); + typeMapping.put("object", "any"); + typeMapping.put("integer", "number"); + + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize the variable name + // pet_id => PetId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) + throw new RuntimeException(name + + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else + type = swaggerType; + return type; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 352401ba0d8..e12c835a90a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -421,10 +421,10 @@ public class ApiClient { throw new ApiException(500, "unknown method type " + method); } - if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } - else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { + else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if(response.hasEntity()) { return (String) response.getEntity(String.class); } @@ -445,7 +445,7 @@ public class ApiClient { } } throw new ApiException( - response.getClientResponseStatus().getStatusCode(), + response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody); diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index ce3edfd1359..7360129285e 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -15,6 +15,7 @@ io.swagger.codegen.languages.RubyClientCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen +io.swagger.codegen.languages.SinatraServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator @@ -22,4 +23,6 @@ io.swagger.codegen.languages.SwaggerGenerator io.swagger.codegen.languages.SwaggerYamlGenerator io.swagger.codegen.languages.SwiftGenerator io.swagger.codegen.languages.TizenClientCodegen +io.swagger.codegen.languages.TypeScriptAngularClientCodegen +io.swagger.codegen.languages.TypeScriptNodeClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.d.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.d.mustache new file mode 100644 index 00000000000..a8bf1c58267 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.d.mustache @@ -0,0 +1,13 @@ +{{#models}} +{{#model}} +/// +{{/model}} +{{/models}} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +/// +{{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache new file mode 100644 index 00000000000..88f7f9ff15a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -0,0 +1,68 @@ +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +{{#operations}} +module {{package}} { + 'use strict'; + + {{#description}} + /** + * {{&description}} + */ + {{/description}} + export class {{classname}} { + private basePath = '{{basePath}}'; + + static $inject: string[] = ['$http']; + + constructor(private $http: ng.IHttpService, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + {{#operation}} + public {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}, {{/allParams}} extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + var path = this.basePath + '{{path}}'; + {{#pathParams}} + path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + {{/pathParams}} + var queryParameters: any = {}; + var headerParams: any = {}; + {{#allParams}}{{#required}} + // verify required parameter '{{paramName}}' is set + if (!{{paramName}}) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); + } + {{/required}}{{/allParams}} + {{#queryParams}}if ({{paramName}} !== undefined) { + queryParameters['{{paramName}}'] = {{paramName}}; + }{{/queryParams}} + {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}};{{/headerParams}} + var httpRequestParams: any = { + method: '{{httpMethod}}', + url: path, + json: true, + {{#bodyParam}}data: {{paramName}}, + {{/bodyParam}} + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + {{/operation}} + } + + angular.module('{{package}}_{{classname}}', ['$http']) + .service('{{classname}}', {{classname}}); +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache new file mode 100644 index 00000000000..b425d14d5e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache @@ -0,0 +1,39 @@ +/// + +module {{package}} { + 'use strict'; + +{{#models}} +{{#model}} +{{#description}} + /** + * {{{description}}} + */ +{{/description}} + export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} + +{{#description}} + /** + * {{{description}}} + */ +{{/description}} + {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} + } + +{{#hasEnums}} + export module {{classname}} { +{{#vars}} +{{#isEnum}} + + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} + } +{{/hasEnums}} +{{/model}} +{{/models}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache new file mode 100644 index 00000000000..eb569cdc928 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -0,0 +1,73 @@ +/* tslint:disable:no-unused-variable */ + +{{#operations}} +{{#description}} + /** + * {{&description}} + */ +{{/description}} +export class {{classname}} { + private basePath = '{{basePath}}'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + {{#operation}} + public {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}} ) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { + var path = this.url + this.basePath + '{{path}}'; + + {{#pathParams}} + path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + {{/pathParams}} + + var queryParameters: any = {}; + var headerParams: any = {}; + + {{#allParams}}{{#required}} + // verify required parameter '{{paramName}}' is set + if (!{{paramName}}) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); + } + {{/required}}{{/allParams}} + + {{#queryParams}}if ({{paramName}} !== undefined) { + queryParameters['{{paramName}}'] = {{paramName}}; + } + {{/queryParams}} + + {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}}; + {{/headerParams}} + + var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + + request({ + method: '{{httpMethod}}', + qs: queryParameters, + uri: path, + json: true, + {{#bodyParam}}body: {{paramName}}, + {{/bodyParam}} + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache new file mode 100644 index 00000000000..55c8997e1bc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache @@ -0,0 +1,33 @@ +{{#models}} +{{#model}} +{{#description}} +/** + * {{{description}}} + */ +{{/description}} +export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} + +{{#description}} + /** + * {{{description}}} + */ +{{/description}} + {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +} + +{{#hasEnums}} +export module {{classname}} { +{{#vars}} +{{#isEnum}} + + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index ad57cffdf34..c6f57bd4a37 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Newtonsoft.Json; using RestSharp; -namespace {{invokerPackage}} { +namespace {{packageName}}.Client { /// /// API client is mainly responible for making the HTTP call to the API backend /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index 38a340be249..65c6193b84f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -1,6 +1,6 @@ using System; -namespace {{invokerPackage}} { +namespace {{packageName}}.Client { /// /// API Exception /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 1f5c00a356d..485d97058ce 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -4,14 +4,18 @@ using System.IO; using System.Linq; using System.Net; using System.Text; -using {{invokerPackage}}; -namespace {{invokerPackage}} { +namespace {{packageName}}.Client { /// /// Represents a set of configuration settings /// public class Configuration{ + /// + /// Version of the package + /// + public const string Version = "{{packageVersion}}"; + /// /// Gets or sets the API client. This is the default API client for making HTTP calls. /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index e22d5517ab5..652d15a30b3 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -2,12 +2,12 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using RestSharp; -using {{invokerPackage}}; -using {{modelPackage}}; +using {{packageName}}.Client; +using {{packageName}}.Model; {{#imports}} {{/imports}} -namespace {{package}} { +namespace {{packageName}}.Api { {{#operations}} public interface I{{classname}} { diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index ce0e62de192..c0fac63b385 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -7,13 +7,13 @@ using Newtonsoft.Json; {{#models}} {{#model}} -namespace {{package}} { +namespace {{packageName}}.Model { /// /// {{description}} /// [DataContract] - public class {{classname}} { + public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} { {{#vars}} {{#description}}/* {{{description}}} */{{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] @@ -39,11 +39,11 @@ namespace {{package}} { /// Get the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() { + public {{#parent}} new {{/parent}}string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } - {{/model}} - {{/models}} +{{/model}} +{{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 9badb4dbb37..2862a0e0538 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -25,141 +25,60 @@ class ApiClient { public static $PUT = "PUT"; public static $DELETE = "DELETE"; - /** @var string[] Array of default headers where the key is the header name and the value is the header value */ - private $default_header = array(); + /** @var Configuration */ + protected $config; - /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curl_timeout = 0; - - /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $user_agent = "PHP-Swagger"; + /** @var ObjectSerializer */ + protected $serializer; /** - * @param string $host Base url of the API server (optional) + * @param Configuration $config config for this ApiClient */ - function __construct($host = null) { - if ($host === null) { - $this->host = '{{basePath}}'; - } else { - $this->host = $host; + function __construct(Configuration $config = null) { + if ($config == null) { + $config = Configuration::getDefaultConfiguration(); } + + $this->config = $config; + $this->serializer = new ObjectSerializer(); } /** - * add default header - * - * @param string $header_name header name (e.g. Token) - * @param string $header_value header value (e.g. 1z8wp3) + * get the config + * @return Configuration */ - public function addDefaultHeader($header_name, $header_value) { - if (!is_string($header_name)) - throw new \InvalidArgumentException('Header name must be a string.'); - - $this->default_header[$header_name] = $header_value; + public function getConfig() { + return $this->config; } /** - * get the default header - * - * @return array default header + * get the serializer + * @return ObjectSerializer */ - public function getDefaultHeader() { - return $this->default_header; + public function getSerializer() { + return $this->serializer; } - /** - * delete the default header based on header name - * - * @param string $header_name header name (e.g. Token) - */ - public function deleteDefaultHeader($header_name) { - unset($this->default_header[$header_name]); - } - - /** - * set the user agent of the api client - * - * @param string $user_agent the user agent of the api client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) - throw new \InvalidArgumentException('User-agent must be a string.'); - - $this->user_agent= $user_agent; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - - $this->curl_timeout = $seconds; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } - - /** * Get API key (with prefix if set) - * @param string key name + * @param string $apiKey name of apikey * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; + $prefix = $this->config->getApiKeyPrefix($apiKey); + $apiKey = $this->config->getApiKey($apiKey); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; } else { - return; + $keyWithPrefix = $apiKey; } - } - /** - * update hearder and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; - - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - {{#authMethods}} - case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - break; - {{/authMethods}} - default: - //TODO show warning about security definition not found - } - } + return $keyWithPrefix; } /** @@ -168,18 +87,15 @@ class ApiClient { * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header + * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { $headers = array(); - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # construct the http header - $headerParams = array_merge((array)$this->default_header, (array)$headerParams); + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -190,15 +106,15 @@ class ApiClient { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); + $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - $url = $this->host . $resourcePath; + $url = $this->config->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -227,14 +143,14 @@ class ApiClient { curl_setopt($curl, CURLOPT_URL, $url); // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } @@ -250,8 +166,8 @@ class ApiClient { $response_info = curl_getinfo($curl); // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } // Handle the response @@ -269,153 +185,13 @@ class ApiClient { return $data; } - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public function toPathValue($value) { - return rawurlencode($this->toString($value)); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $this->toString($object); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public function toHeaderValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public function toFormValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = $this->deserialize($value, $subClass); - } - } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { - $subClass = substr($class, 0, -2); - $values = array(); - foreach ($data as $key => $value) { - $values[] = $this->deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = $this->deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - /* * return the header 'Accept' based on an array of Accept provided * - * @param array[string] $accept Array of header + * @param string[] $accept Array of header * @return string Accept (e.g. application/json) */ - public function selectHeaderAccept($accept) { + public static function selectHeaderAccept($accept) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return NULL; } elseif (preg_grep("/application\/json/i", $accept)) { @@ -428,10 +204,10 @@ class ApiClient { /* * return the content type based on an array of content-type provided * - * @param array[string] content_type_array Array fo content-type + * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ - public function selectHeaderContentType($content_type) { + public static function selectHeaderContentType($content_type) { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; } elseif (preg_grep("/application\/json/i", $content_type)) { @@ -440,6 +216,4 @@ class ApiClient { return implode(',', $content_type); } } - } - diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index a835d579d32..6d5415f798d 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -22,15 +22,20 @@ use \Exception; class ApiException extends Exception { /** @var string The HTTP body of the server response. */ - protected $response_body; + protected $responseBody; /** @var string[] The HTTP header of the server response. */ - protected $response_headers; + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_headers = $responseHeaders; - $this->response_body = $responseBody; + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; } /** @@ -39,7 +44,7 @@ class ApiException extends Exception { * @return string HTTP response header */ public function getResponseHeaders() { - return $this->response_headers; + return $this->responseHeaders; } /** @@ -48,7 +53,18 @@ class ApiException extends Exception { * @return string HTTP response body */ public function getResponseBody() { - return $this->response_body; + return $this->responseBody; } + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache new file mode 100644 index 00000000000..56a61e97c91 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -0,0 +1,151 @@ +format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public function toPathValue($value) { + return rawurlencode($this->toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return $this->toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value a string which will be part of the header + * @return string the header string + */ + public function toHeaderValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the form parameter + * @return string the form string + */ + public function toFormValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the parameter + * @return string the header string + */ + public function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + public function deserialize($data, $class) { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = $this->deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); + $values = array(); + foreach ($data as $key => $value) { + $values[] = $this->deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter($this->deserialize($propertyValue, $type)); + } + } + $deserialized = $instance; + } + + return $deserialized; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 3ed7f18c579..cd483ffa881 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -22,31 +22,29 @@ namespace {{apiPackage}}; -use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\Configuration; +use \{{invokerPackage}}\ApiClient; +use \{{invokerPackage}}\ApiException; +use \{{invokerPackage}}\ObjectSerializer; {{#operations}} class {{classname}} { - /** - * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('{{basePath}}'); + } + + $this->apiClient = $apiClient; + } + /** * @return \{{invokerPackage}}\ApiClient get the API client */ @@ -55,10 +53,12 @@ class {{classname}} { } /** - * @param \{{invokerPackage}} $apiClient set the API client + * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * @return {{classname}} */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } {{#operation}} @@ -69,6 +69,7 @@ class {{classname}} { * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} @@ -86,28 +87,29 @@ class {{classname}} { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); }{{/queryParams}} {{#headerParams}}// header params if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); }{{/headerParams}} {{#pathParams}}// path params if(${{paramName}} !== null) { $resourcePath = str_replace("{" . "{{baseName}}" . "}", - $this->apiClient->toPathValue(${{paramName}}), $resourcePath); + $this->apiClient->getSerializer()->toPathValue(${{paramName}}), + $resourcePath); }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@'.{{/isFile}}$this->apiClient->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; @@ -122,22 +124,38 @@ class {{classname}} { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); - + {{#authMethods}}{{#isApiKey}} + $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); + if (isset($apiKey)) { + {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} + }{{/isApiKey}} + {{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->apiClient->getConfig()->getUsername().":".$this->apiClient->getConfig()->getPassword());{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{/authMethods}} // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - {{#returnType}}if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { {{#responses}}{{#dataType}} + case {{code}}: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}'); + $e->setResponseObject($data); + break;{{/dataType}}{{/responses}} + } + + throw $e; + } + {{#returnType}} + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); - return $responseObject;{{/returnType}} + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'{{returnType}}'); + return $responseObject; + {{/returnType}} } {{/operation}} -{{newline}} -{{/operations}} } +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 4f56a6e20c0..04be6e11992 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -4,7 +4,7 @@ * * After registering this autoload function with SPL, the following line * would cause the function to attempt to load the \{{invokerPackage}}\Baz\Qux class - * from /path/to/project/lib/Baz/Qux.php: + * from /path/to/project/{{srcBasePath}}/Baz/Qux.php: * * new \{{invokerPackage}}\Baz\Qux; * @@ -17,7 +17,7 @@ spl_autoload_register(function ($class) { $prefix = '{{escapedInvokerPackage}}\\'; // base directory for the namespace prefix - $base_dir = __DIR__ . '/lib/'; + $base_dir = __DIR__ . '/{{srcBasePath}}/'; // does the class use the namespace prefix? $len = strlen($prefix); diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index f4e38c84f73..d36267617c4 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -28,6 +28,6 @@ "squizlabs/php_codesniffer": "~2.0" }, "autoload": { - "psr-4": { "{{escapedInvokerPackage}}\\" : "lib/" } + "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } } } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 030910ffca7..b85ad289418 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -17,37 +17,250 @@ namespace {{invokerPackage}}; -use \{{invokerPackage}}\ApiClient; - class Configuration { + private static $defaultConfiguration = null; + /** @var string[] Associate array to store API key(s) */ - public static $apiKey = array(); + protected $apiKeys = array(); /** string[] Associate array to store API prefix (e.g. Bearer) */ - public static $apiKeyPrefix = array(); + protected $apiKeyPrefixes = array(); /** @var string Username for HTTP basic authentication */ - public static $username = ''; + protected $username = ''; /** @var string Password for HTTP basic authentication */ - public static $password = ''; + protected $password = ''; /** @var \{{invokerPackage}}\ApiClient The default instance of ApiClient */ - public static $apiClient; + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; /** @var bool Debug switch (default set to false) */ - public static $debug = false; + protected $debug = false; /** @var string Debug file location (log to STDOUT by default) */ - public static $debug_file = 'php://output'; + protected $debugFile = 'php://output'; - /* - * manually initalize ApiClient + /** + * @param string $key + * @param string $value + * @return Configuration */ - public static function init() { - if (self::$apiClient === null) - self::$apiClient = new ApiClient(); + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; } + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + public function setCurlTimeout($seconds) { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + } + + $this->curlTimeout = $seconds; + return $this; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; + } + + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index cc2d57197ab..35795bf8c0b 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -40,18 +40,48 @@ class {{classname}} implements ArrayAccess { {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + {{#vars}} /** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/ - public ${{name}}; + protected ${{name}}; {{/vars}} - /** - * @param mixed[] Array of parameters to initialize the object with - */ public function __construct(array $data = null) { - {{#vars}}$this->{{name}} = @$data["{{name}}"];{{#hasMore}} - {{/hasMore}}{{/vars}} + if ($data != null) { + {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} + {{/hasMore}}{{/vars}} + } + } + {{#vars}} + /** + * get {{name}} + * @return {{datatype}} + */ + public function {{getter}}() { + return $this->{{name}}; } + /** + * set {{name}} + * @param {{datatype}} ${{name}} + * @return $this + */ + public function {{setter}}(${{name}}) { + $this->{{name}} = ${{name}}; + return $this; + } + {{/vars}} public function offsetExists($offset) { return isset($this->$offset); } diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index f1ba52d2930..af4fa69baf3 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -1,6 +1,9 @@ import sys from setuptools import setup, find_packages +NAME = "{{packageName}}" +VERSION = "{{packageVersion}}" + {{#apiInfo}}{{#apis}}{{^hasMore}} # To install the library, open a Terminal shell, then run this @@ -15,8 +18,8 @@ from setuptools import setup, find_packages REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] setup( - name="{{module}}", - version="{{version}}", + name=NAME, + version=VERSION, description="{{appName}}", author_email="{{infoEmail}}", url="{{infoUrl}}", diff --git a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index f432c2dc59e..9c2e9c073cd 100644 --- a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -141,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } case _ => null } - response.getClientResponseStatus().getStatusCode() match { + response.getStatusInfo().getStatusCode() match { case 204 => "" case code: Int if (Range(200, 299).contains(code)) => { response.hasEntity() match { @@ -155,7 +155,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, case false => "no data" } throw new ApiException( - response.getClientResponseStatus().getStatusCode(), + response.getStatusInfo().getStatusCode(), entity) } } @@ -172,7 +172,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } } } - + def newClient(host: String): Client = asyncHttpClient match { case true => { import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig @@ -200,4 +200,3 @@ object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, authPreemptive = {{authPreemptive}}) class ApiException(val code: Int, msg: String) extends RuntimeException(msg) - diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 2d8a1257eb4..c6fe4a1f356 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -72,6 +72,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.9.1 add_sources @@ -208,7 +209,7 @@ 2.10.4 1.2 2.2 - 1.7 + 1.19 1.5.0 1.0.5 1.0.0 @@ -216,6 +217,8 @@ 4.8.1 3.1.5 - 2.1.3 + 2.2.4 + + UTF-8 diff --git a/modules/swagger-codegen/src/main/resources/sinatra/Gemfile b/modules/swagger-codegen/src/main/resources/sinatra/Gemfile new file mode 100644 index 00000000000..be9c3168ea6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +gem "sinatra" +gem "sinatra-cross_origin" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/sinatra/README.md b/modules/swagger-codegen/src/main/resources/sinatra/README.md new file mode 100644 index 00000000000..c5b8cfffe77 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/README.md @@ -0,0 +1,29 @@ +# Swagger for Sinatra + +## Overview +This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find +out more about both the spec and the framework at http://swagger.io. For more information about +Wordnik's APIs, please visit http://developer.wordnik.com. + +## Prerequisites +You need to install ruby 1.9.3 and the following gems: + +``` +sinatra +sinatra-cross_origin +``` + +## Getting started +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +rackup -p 4567 config.ru +``` + +In your [swagger ui](https://github.com/swagger-api/swagger-ui), put in the following URL: + +``` +http://localhost:4567/resources.json +``` + +Voila! diff --git a/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb new file mode 100644 index 00000000000..79aca1da2c9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb @@ -0,0 +1,154 @@ +require 'json' +require 'sinatra/base' +require 'sinatra/cross_origin' + +class Configuration + attr_accessor :base_path, :api_version, :swagger_version, :format_specifier + + def initialize + @api_version = '1.0' + @base_path = 'http://localhost:4567' + @swagger_version = '1.1' + @format_specifier = ".json" + end +end + +class Swaggering < Sinatra::Base + register Sinatra::CrossOrigin + + @@routes = {} + @@configuration = Configuration.new + + attr_accessor :configuration + + def self.configure + get("/resources" + @@configuration.format_specifier) { + cross_origin + Swaggering.to_resource_listing + } + @@configuration ||= Configuration.new + yield(@@configuration) if block_given? + end + + def self.add_route(method, path, swag={}, opts={}, &block) + fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + + accepted = case method + when 'get' + get(fullPath, opts, &block) + true + when 'post' + post(fullPath, opts, &block) + true + when 'delete' + delete(fullPath, opts, &block) + true + when 'put' + put(fullPath, opts, &block) + true + else + false + end + + if accepted then + resourcePath = swag["resourcePath"].to_s + ops = @@routes[resourcePath] + if ops.nil? + ops = Array.new + @@routes.merge!(resourcePath => ops) + + get(resourcePath + @@configuration.format_specifier) do + cross_origin + Swaggering.to_api(resourcePath) + end + end + + swag.merge!("httpMethod" => method.to_s.upcase) + ops.push(swag) + end + end + + def self.to_resource_listing + apis = Array.new + (@@routes.keys).each do |key| + api = { + "path" => (key + ".{format}"), + "description" => "no description" + } + apis.push api + end + + resource = { + "apiVersion" => @@configuration.api_version, + "swaggerVersion" => @@configuration.swagger_version, + "apis" => apis + } + + resource.to_json + end + + def self.to_api(resourcePath) + apis = {} + models = [] + + @@routes[resourcePath].each do |route| + endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2') + path = (resourcePath + ".{format}" + endpoint) + api = apis[path] + if api.nil? + api = {"path" => path, "description" => "description", "operations" => []} + apis.merge!(path => api) + end + + parameters = route["parameters"] + + unless parameters.nil? then + parameters.each do |param| + av_string = param["allowableValues"] + unless av_string.nil? + if av_string.count('[') > 0 + pattern = /^([A-Z]*)\[(.*)\]/ + match = pattern.match av_string + case match.to_a[1] + when "LIST" + allowables = match.to_a[2].split(',') + param["allowableValues"] = { + "valueType" => "LIST", + "values" => allowables + } + when "RANGE" + allowables = match.to_a[2].split(',') + param["allowableValues"] = { + "valueType" => "RANGE", + "min" => allowables[0], + "max" => allowables[1] + } + end + end + end + end + end + + op = { + "httpMethod" => route["httpMethod"], + "description" => route["summary"], + "responseClass" => route["responseClass"], + "notes" => route["notes"], + "nickname" => route["nickname"], + "summary" => route["summary"], + "parameters" => route["parameters"] + } + api["operations"].push(op) + end + + api_listing = { + "apiVersion" => @@configuration.api_version, + "swaggerVersion" => @@configuration.swagger_version, + "basePath" => @@configuration.base_path, + "resourcePath" => resourcePath, + "apis" => apis.values, + "models" => models + } + api_listing.to_json + end +end diff --git a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache new file mode 100644 index 00000000000..cfeae19de7a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache @@ -0,0 +1,57 @@ +require 'json' + +{{#operations}} +{{#operation}} + +MyApp.add_route('{{httpMethod}}', '{{path}}', { + "resourcePath" => "/{{baseName}}", + "summary" => "{{{summary}}}", + "nickname" => "{{nickname}}", + "responseClass" => "{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}", + "endpoint" => "{{path}}", + "notes" => "{{{notes}}}", + "parameters" => [ + {{#queryParams}} + { + "name" => "{{paramName}}", + "description" => "{{description}}", + "dataType" => "{{swaggerDataType}}", + "paramType" => "query", + "allowMultiple" => {{allowMultiple}}, + "allowableValues" => "{{allowableValues}}", + {{#defaultValue}}"defaultValue" => {{{defaultValue}}}{{/defaultValue}} + }, + {{/queryParams}} + {{#pathParams}} + { + "name" => "{{paramName}}", + "description" => "{{description}}", + "dataType" => "{{swaggerDataType}}", + "paramType" => "path", + }, + {{/pathParams}} + {{#headerParams}} + { + "name" => "{{paramName}}", + "description" => "{{description}}", + "dataType" => "{{swaggerDataType}}", + "paramType" => "header", + }, + {{/headerParams}} + {{#bodyParams}} + { + "name" => "body", + "description" => "{{description}}", + "dataType" => "{{swaggerDataType}}", + "paramType" => "body", + } + {{/bodyParams}} + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/sinatra/config.ru b/modules/swagger-codegen/src/main/resources/sinatra/config.ru new file mode 100644 index 00000000000..395d0587123 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/config.ru @@ -0,0 +1,2 @@ +require './my_app' +run MyApp diff --git a/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache new file mode 100644 index 00000000000..72b5267a140 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache @@ -0,0 +1,12 @@ +require './lib/swaggering' + +# only need to extend if you want special configuration! +class MyApp < Swaggering + self.configure do |config| + config.api_version = '0.2' + end +end + +{{#apis}} +require './lib/{{className}}.rb' +{{/apis}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala new file mode 100644 index 00000000000..5e28e3e8dc7 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala @@ -0,0 +1,170 @@ +package typescriptangular + +import io.swagger.codegen.languages.TypeScriptAngularClientCodegen +import io.swagger.models._ +import io.swagger.models.properties._ +import org.junit.runner.RunWith +import org.scalatest.{FlatSpec, Matchers} +import org.scalatest.junit.JUnitRunner + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class TypeScriptAngularModelTest extends FlatSpec with Matchers { + + it should "convert a simple TypeScript Angular model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(3) + + val vars = cm.vars + vars.get(0).baseName should be("id") + vars.get(0).datatype should be("number") + vars.get(0).name should be("id") + vars.get(0).defaultValue should be("null") + vars.get(0).baseType should be("number") + vars.get(0).hasMore should equal(true) + vars.get(0).required should equal(true) + vars.get(0).isNotContainer should equal(true) + + vars.get(1).baseName should be("name") + vars.get(1).datatype should be("string") + vars.get(1).name should be("name") + vars.get(1).defaultValue should be("null") + vars.get(1).baseType should be("string") + vars.get(1).hasMore should equal(true) + vars.get(1).required should equal(true) + vars.get(1).isNotContainer should equal(true) + + vars.get(2).baseName should be("createdAt") + vars.get(2).complexType should be("DateTime") + vars.get(2).datatype should be("DateTime") + vars.get(2).name should be("createdAt") + vars.get(2).defaultValue should be("null") + vars.get(2).hasMore should equal(null) + vars.get(2).required should equal(null) + vars.get(2).isNotContainer should equal(true) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(2) + + val vars = cm.vars + vars.get(0).baseName should be("id") + vars.get(0).datatype should be("number") + vars.get(0).name should be("id") + vars.get(0).defaultValue should be("null") + vars.get(0).baseType should be("number") + vars.get(0).hasMore should equal(true) + vars.get(0).required should equal(true) + vars.get(0).isNotContainer should equal(true) + + vars.get(1).baseName should be("urls") + vars.get(1).datatype should be("Array") + vars.get(1).name should be("urls") + vars.get(1).baseType should be("Array") + vars.get(1).hasMore should be(null) + vars.get(1).required should equal(null) + vars.get(1).isContainer should equal(true) + } + + it should "convert a model with complex property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(1) + + val vars = cm.vars + vars.get(0).baseName should be("children") + vars.get(0).datatype should be("Children") + vars.get(0).name should be("children") + vars.get(0).baseType should be("Children") + vars.get(0).required should equal(null) + vars.get(0).isNotContainer should equal(true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(1) + + val vars = cm.vars + vars.get(0).baseName should be("children") + vars.get(0).complexType should be("Children") + vars.get(0).datatype should be("Array") + vars.get(0).name should be("children") + vars.get(0).baseType should be("Array") + vars.get(0).required should equal(null) + vars.get(0).isContainer should equal(true) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("an array model") + cm.vars.size should be(0) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new TypeScriptAngularClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("an map model") + cm.vars.size should be(0) + cm.imports.size should be(1) + (cm.imports.asScala.toSet & Set("Children")).size should be(1) + } +} diff --git a/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala new file mode 100644 index 00000000000..0b91d717bf6 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala @@ -0,0 +1,170 @@ +package typescriptnode + +import io.swagger.codegen.languages.TypeScriptNodeClientCodegen +import io.swagger.models._ +import io.swagger.models.properties._ +import org.junit.runner.RunWith +import org.scalatest.{FlatSpec, Matchers} +import org.scalatest.junit.JUnitRunner + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class TypeScriptNodeModelTest extends FlatSpec with Matchers { + + it should "convert a simple TypeScript Node model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(3) + + val vars = cm.vars + vars.get(0).baseName should be("id") + vars.get(0).datatype should be("number") + vars.get(0).name should be("id") + vars.get(0).defaultValue should be("null") + vars.get(0).baseType should be("number") + vars.get(0).hasMore should equal(true) + vars.get(0).required should equal(true) + vars.get(0).isNotContainer should equal(true) + + vars.get(1).baseName should be("name") + vars.get(1).datatype should be("string") + vars.get(1).name should be("name") + vars.get(1).defaultValue should be("null") + vars.get(1).baseType should be("string") + vars.get(1).hasMore should equal(true) + vars.get(1).required should equal(true) + vars.get(1).isNotContainer should equal(true) + + vars.get(2).baseName should be("createdAt") + vars.get(2).complexType should be("DateTime") + vars.get(2).datatype should be("DateTime") + vars.get(2).name should be("createdAt") + vars.get(2).defaultValue should be("null") + vars.get(2).hasMore should equal(null) + vars.get(2).required should equal(null) + vars.get(2).isNotContainer should equal(true) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(2) + + val vars = cm.vars + vars.get(0).baseName should be("id") + vars.get(0).datatype should be("number") + vars.get(0).name should be("id") + vars.get(0).defaultValue should be("null") + vars.get(0).baseType should be("number") + vars.get(0).hasMore should equal(true) + vars.get(0).required should equal(true) + vars.get(0).isNotContainer should equal(true) + + vars.get(1).baseName should be("urls") + vars.get(1).datatype should be("Array") + vars.get(1).name should be("urls") + vars.get(1).baseType should be("Array") + vars.get(1).hasMore should be(null) + vars.get(1).required should equal(null) + vars.get(1).isContainer should equal(true) + } + + it should "convert a model with complex property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(1) + + val vars = cm.vars + vars.get(0).baseName should be("children") + vars.get(0).datatype should be("Children") + vars.get(0).name should be("children") + vars.get(0).baseType should be("Children") + vars.get(0).required should equal(null) + vars.get(0).isNotContainer should equal(true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("a sample model") + cm.vars.size should be(1) + + val vars = cm.vars + vars.get(0).baseName should be("children") + vars.get(0).complexType should be("Children") + vars.get(0).datatype should be("Array") + vars.get(0).name should be("children") + vars.get(0).baseType should be("Array") + vars.get(0).required should equal(null) + vars.get(0).isContainer should equal(true) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("an array model") + cm.vars.size should be(0) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new TypeScriptNodeClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.description should be("an map model") + cm.vars.size should be(0) + cm.imports.size should be(1) + (cm.imports.asScala.toSet & Set("Children")).size should be(1) + } +} diff --git a/samples/client/petstore/csharp/bin/Newtonsoft.Json.dll b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/Newtonsoft.Json.dll similarity index 100% rename from samples/client/petstore/csharp/bin/Newtonsoft.Json.dll rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/Newtonsoft.Json.dll diff --git a/samples/client/petstore/csharp/bin/RestSharp.dll b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/RestSharp.dll similarity index 100% rename from samples/client/petstore/csharp/bin/RestSharp.dll rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/RestSharp.dll diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat similarity index 55% rename from samples/client/petstore/csharp/compile.bat rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat index 63b79e03eed..bb6ae8097ea 100644 --- a/samples/client/petstore/csharp/compile.bat +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat @@ -1,3 +1,3 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/IO.Swagger.Client.dll /recurse:src\*.cs /doc:bin/IO.Swagger.Client.xml +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/.dll /recurse:src\*.cs /doc:bin/.xml diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs similarity index 100% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs similarity index 100% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs similarity index 100% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs similarity index 100% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs similarity index 100% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs similarity index 92% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs index 4e7975e3ad0..ab24fc1252c 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Net; using System.Text; -using IO.Swagger.Client; namespace IO.Swagger.Client { /// @@ -12,6 +11,11 @@ namespace IO.Swagger.Client { /// public class Configuration{ + /// + /// Version of the package + /// + public const string Version = "1.0.0"; + /// /// Gets or sets the API client. This is the default API client for making HTTP calls. /// diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs similarity index 99% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs index 74121762af9..4a410e8220d 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs @@ -49,6 +49,4 @@ namespace IO.Swagger.Model { } } - - } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs similarity index 99% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs index 7451619050c..9e7e706f77e 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs @@ -77,6 +77,4 @@ namespace IO.Swagger.Model { } } - - } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs similarity index 99% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs index 0bfba35b1e3..49e6d582f5e 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs @@ -77,6 +77,4 @@ namespace IO.Swagger.Model { } } - - } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs similarity index 99% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs index 53901491a47..47c87ae9ef1 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs @@ -49,6 +49,4 @@ namespace IO.Swagger.Model { } } - - } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs similarity index 99% rename from samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs rename to samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs index e58d0296a06..f2c3db54608 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs @@ -91,6 +91,4 @@ namespace IO.Swagger.Model { } } - - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj new file mode 100644 index 00000000000..7a0b8f7674b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -0,0 +1,68 @@ + + + + Debug + AnyCPU + {1011E844-3414-4D65-BF1F-7C8CE0167174} + Library + SwaggerClientTest + SwaggerClientTest + v4.5 + + + true + full + false + bin\Debug + DEBUG; + prompt + 4 + false + + + full + true + bin\Release + prompt + 4 + false + + + + + packages\NUnit.2.6.3\lib\nunit.framework.dll + + + Lib\SwaggerClient\bin\Newtonsoft.Json.dll + + + Lib\SwaggerClient\bin\RestSharp.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln new file mode 100644 index 00000000000..dfb6e762ce2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln @@ -0,0 +1,17 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwaggerClientTest", "SwaggerClientTest.csproj", "{1011E844-3414-4D65-BF1F-7C8CE0167174}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1011E844-3414-4D65-BF1F-7C8CE0167174}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1011E844-3414-4D65-BF1F-7C8CE0167174}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs new file mode 100644 index 00000000000..4fa44c936ae --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs new file mode 100644 index 00000000000..8e6ea0f99d2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -0,0 +1,109 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; + + +namespace SwaggerClient.TestPet +{ + [TestFixture ()] + public class TestPet + { + public long petId = 11088; + + [SetUp] public void Init() + { + // create pet + Pet p = new Pet(); + p.Id = petId; + p.Name = "Csharp test"; + p.Status = "available"; + // create Category object + Category category = new Category(); + category.Id = 56; + category.Name = "sample category name2"; + List photoUrls = new List(new String[] {"sample photoUrls"}); + // create Tag object + Tag tag = new Tag(); + tag.Id = petId; + tag.Name = "sample tag name1"; + List tags = new List(new Tag[] {tag}); + p.Tags = tags; + p.Category = category; + p.PhotoUrls = photoUrls; + + // add pet before testing + PetApi petApi = new PetApi("http://petstore.swagger.io/v2/"); + petApi.AddPet (p); + + } + + [TearDown] public void Cleanup() + { + // remove the pet after testing + PetApi petApi = new PetApi (); + petApi.DeletePet("test key", petId); + } + + + [Test ()] + public void TestGetPetById () + { + PetApi petApi = new PetApi (); + Pet response = petApi.GetPetById (petId); + Assert.IsInstanceOf (response, "Response is a Pet"); + + Assert.AreEqual ("Csharp test", response.Name); + Assert.AreEqual ("available", response.Status); + + Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual ("sample tag name1", response.Tags [0].Name); + + Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); + + Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.AreEqual (56, response.Category.Id); + Assert.AreEqual ("sample category name2", response.Category.Name); + + } + + [Test ()] + public void TestUpdatePetWithForm () + { + PetApi petApi = new PetApi (); + petApi.UpdatePetWithForm (petId.ToString(), "new form name", "pending"); + + Pet response = petApi.GetPetById (petId); + Assert.IsInstanceOf (response, "Response is a Pet"); + Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + + Assert.AreEqual ("new form name", response.Name); + Assert.AreEqual ("pending", response.Status); + + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual (56, response.Category.Id); + } + + [Test ()] + public void TestFindPetByStatus () + { + PetApi petApi = new PetApi (); + List statusList = new List(new String[] {"available"}); + + List listPet = petApi.FindPetsByStatus (statusList); + foreach (Pet pet in listPet) // Loop through List with foreach. + { + Assert.IsInstanceOf (pet, "Response is a Pet"); + Assert.AreEqual ("available", pet.Status); + } + + } + + } +} + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll new file mode 100644 index 00000000000..26fdaffec14 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll new file mode 100644 index 00000000000..a7331ed6e23 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll new file mode 100755 index 00000000000..bac89714b9c Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb new file mode 100644 index 00000000000..a7a6c4d4364 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll new file mode 100644 index 00000000000..780727f219d Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs new file mode 100644 index 00000000000..fdcb678cdda --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs @@ -0,0 +1,2 @@ +// +[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5", FrameworkDisplayName = "")] diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt new file mode 100644 index 00000000000..9afb7990f57 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -0,0 +1,8 @@ +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll new file mode 100755 index 00000000000..bac89714b9c Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb new file mode 100644 index 00000000000..a7a6c4d4364 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages.config b/samples/client/petstore/csharp/SwaggerClientTest/packages.config new file mode 100644 index 00000000000..d4e241a20a0 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/NUnit.2.6.3.nupkg b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/NUnit.2.6.3.nupkg new file mode 100644 index 00000000000..61e3a5ecfc1 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/NUnit.2.6.3.nupkg differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.dll b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.dll new file mode 100644 index 00000000000..780727f219d Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.xml b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.xml new file mode 100644 index 00000000000..4c8c26e8829 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/lib/nunit.framework.xml @@ -0,0 +1,10960 @@ + + + + nunit.framework + + + + + The different targets a test action attribute can be applied to + + + + + Default target, which is determined by where the action attribute is attached + + + + + Target a individual test case + + + + + Target a suite of test cases + + + + + Delegate used by tests that execute code and + capture any thrown exception. + + + + + The Assert class contains a collection of static methods that + implement the most common assertions used in NUnit. + + + + + We don't actually want any instances of this object, but some people + like to inherit from it to add other static methods. Hence, the + protected constructor disallows any instances of this object. + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + The message to initialize the with. + + + + Throws a with the message and arguments + that are passed in. This allows a test to be cut short, with a result + of success returned to NUnit. + + + + + Throws an with the message and arguments + that are passed in. This is used by the other Assert functions. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This is used by the other Assert functions. + + The message to initialize the with. + + + + Throws an . + This is used by the other Assert functions. + + + + + Throws an with the message and arguments + that are passed in. This causes the test to be reported as ignored. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This causes the test to be reported as ignored. + + The message to initialize the with. + + + + Throws an . + This causes the test to be reported as ignored. + + + + + Throws an with the message and arguments + that are passed in. This causes the test to be reported as inconclusive. + + The message to initialize the with. + Arguments to be used in formatting the message + + + + Throws an with the message that is + passed in. This causes the test to be reported as inconclusive. + + The message to initialize the with. + + + + Throws an . + This causes the test to be reported as Inconclusive. + + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + Used as a synonym for That in rare cases where a private setter + causes a Visual Basic compilation error. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + Used as a synonym for That in rare cases where a private setter + causes a Visual Basic compilation error. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + Used as a synonym for That in rare cases where a private setter + causes a Visual Basic compilation error. + + + This method is provided for use by VB developers needing to test + the value of properties with private setters. + + The actual value to test + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + A constraint to be satisfied by the exception + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + A constraint to be satisfied by the exception + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws a particular exception when called. + + A constraint to be satisfied by the exception + A TestDelegate + + + + Verifies that a delegate throws a particular exception when called. + + The exception Type expected + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + The exception Type expected + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws a particular exception when called. + + The exception Type expected + A TestDelegate + + + + Verifies that a delegate throws a particular exception when called. + + Type of the expected exception + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws a particular exception when called. + + Type of the expected exception + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws a particular exception when called. + + Type of the expected exception + A TestDelegate + + + + Verifies that a delegate throws an exception when called + and returns it. + + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception when called + and returns it. + + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws an exception when called + and returns it. + + A TestDelegate + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate throws an exception of a certain Type + or one derived from it when called and returns it. + + The expected Exception Type + A TestDelegate + + + + Verifies that a delegate does not throw an exception + + A TestDelegate + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that a delegate does not throw an exception. + + A TestDelegate + The message that will be displayed on failure + + + + Verifies that a delegate does not throw an exception. + + A TestDelegate + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display in case of failure + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + The message to display in case of failure + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + + + + Verifies that the object that is passed in is not equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + The message to display in case of failure + + + + Verifies that the object that is passed in is equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + + + Verifies that two ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two unsigned ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two unsigned ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two unsigned ints are equal. If they are not, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two unsigned longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two unsigned longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two unsigned longs are equal. If they are not, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two decimals are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two decimals are equal. If they are not, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two decimals are equal. If they are not, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equal then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are not equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are not equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are not equal an is thrown. + + The value that is expected + The actual value + + + + Verifies that two ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two unsigned ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two unsigned ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two unsigned ints are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two unsigned longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two unsigned longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two unsigned longs are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two decimals are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two decimals are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two decimals are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two floats are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two floats are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two floats are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two doubles are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two doubles are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + The message to display in case of failure + + + + Verifies that two doubles are not equal. If they are equal, then an + is thrown. + + The expected value + The actual value + + + + Verifies that two objects are not equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that two objects are not equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are equal an is thrown. + + The value that is expected + The actual value + The message to display in case of failure + + + + Verifies that two objects are not equal. Two objects are considered + equal if both are null, or if both have the same value. NUnit + has special semantics for some object types. + If they are equal an is thrown. + + The value that is expected + The actual value + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + + + + Asserts that two objects do not refer to the same object. If they + are the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that two objects do not refer to the same object. If they + are the same an is thrown. + + The expected object + The actual object + The message to display in case of failure + + + + Asserts that two objects do not refer to the same object. If they + are the same an is thrown. + + The expected object + The actual object + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to display in case of failure + + + + Verifies that the double that is passed in is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + The message to display in case of failure + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + + + + Assert that a string is not empty - that is not equal to string.Empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is not empty - that is not equal to string.Empty + + The string to be tested + The message to display in case of failure + + + + Assert that a string is not empty - that is not equal to string.Empty + + The string to be tested + + + + Assert that an array, list or other collection is not empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that an array, list or other collection is not empty + + An array, list or other collection implementing ICollection + The message to display in case of failure + + + + Assert that an array, list or other collection is not empty + + An array, list or other collection implementing ICollection + + + + Assert that a string is either null or equal to string.Empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is either null or equal to string.Empty + + The string to be tested + The message to display in case of failure + + + + Assert that a string is either null or equal to string.Empty + + The string to be tested + + + + Assert that a string is not null or empty + + The string to be tested + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Assert that a string is not null or empty + + The string to be tested + The message to display in case of failure + + + + Assert that a string is not null or empty + + The string to be tested + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + The message to display in case of failure + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than the second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message to display in case of failure + + + + Verifies that the first value is greater than or equal tothe second + value. If it is not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message to display in case of failure + + + + Verifies that the first value is less than or equal to the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Asserts that an object is contained in a list. + + The expected object + The list to be examined + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is contained in a list. + + The expected object + The list to be examined + The message to display in case of failure + + + + Asserts that an object is contained in a list. + + The expected object + The list to be examined + + + + Helper for Assert.AreEqual(double expected, double actual, ...) + allowing code generation to work consistently. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Gets the number of assertions executed so far and + resets the counter to zero. + + + + + AssertionHelper is an optional base class for user tests, + allowing the use of shorter names for constraints and + asserts and avoiding conflict with the definition of + , from which it inherits much of its + behavior, in certain mock object frameworks. + + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that fails if the actual + value matches the pattern supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + within a specified range. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. Works + identically to Assert.That. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. Works + identically to Assert.That. + + The actual value to test + A Constraint to be applied + The message to be displayed in case of failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. Works + identically to Assert.That. + + The actual value to test + A Constraint to be applied + The message to be displayed in case of failure + Arguments to use in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . Works Identically to + . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . Works Identically to + . + + The evaluated condition + The message to display if the condition is false + + + + Asserts that a condition is true. If the condition is false the method throws + an . Works Identically to . + + The evaluated condition + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + A Constraint expression to be applied + An ActualValueDelegate returning the value to be tested + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + A Constraint expression to be applied + An ActualValueDelegate returning the value to be tested + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an assertion exception on failure. + + The actual value to test + A Constraint to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Returns a ListMapper based on a collection. + + The original collection + + + + + Provides static methods to express the assumptions + that must be met for a test to give a meaningful + result. If an assumption is not met, the test + should produce an inconclusive result. + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + Arguments to be used in formatting the message + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + The message to display if the condition is false + + + + Asserts that a condition is true. If the condition is false the + method throws an . + + The evaluated condition + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + An ActualValueDelegate returning the value to be tested + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + An ActualValueDelegate returning the value to be tested + The message that will be displayed on failure + + + + Apply a constraint to an actual value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + An ActualValueDelegate returning the value to be tested + A Constraint expression to be applied + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + The message that will be displayed on failure + + + + Apply a constraint to a referenced value, succeeding if the constraint + is satisfied and throwing an InconclusiveException on failure. + + A Constraint expression to be applied + The actual value to test + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that the code represented by a delegate throws an exception + that satisfies the constraint provided. + + A TestDelegate to be executed + A ThrowsConstraint used in the test + + + + Waits for pending asynchronous operations to complete, if appropriate, + and returns a proper result of the invocation by unwrapping task results + + The raw result of the method invocation + The unwrapped result, if necessary + + + + A set of Assert methods operationg on one or more collections + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + IEnumerable containing objects to be considered + System.Type that all objects in collection must be instances of + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + IEnumerable containing objects to be considered + System.Type that all objects in collection must be instances of + The message that will be displayed on failure + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + IEnumerable containing objects to be considered + System.Type that all objects in collection must be instances of + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that all items contained in collection are not equal to null. + + IEnumerable containing objects to be considered + + + + Asserts that all items contained in collection are not equal to null. + + IEnumerable containing objects to be considered + The message that will be displayed on failure + + + + Asserts that all items contained in collection are not equal to null. + + IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + IEnumerable of objects to be considered + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + IEnumerable of objects to be considered + The message that will be displayed on failure + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are exactly equal. The collections must have the same count, + and contain the exact same objects in the same order. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + + + + Asserts that expected and actual are not exactly equal. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + + + + Asserts that expected and actual are not exactly equal. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The IComparer to use in comparing objects from each IEnumerable + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not equivalent. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + + + + Asserts that expected and actual are not equivalent. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are not equivalent. + + The first IEnumerable of objects to be considered + The second IEnumerable of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection contains actual as an item. + + IEnumerable of objects to be considered + Object to be found within collection + + + + Asserts that collection contains actual as an item. + + IEnumerable of objects to be considered + Object to be found within collection + The message that will be displayed on failure + + + + Asserts that collection contains actual as an item. + + IEnumerable of objects to be considered + Object to be found within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection does not contain actual as an item. + + IEnumerable of objects to be considered + Object that cannot exist within collection + + + + Asserts that collection does not contain actual as an item. + + IEnumerable of objects to be considered + Object that cannot exist within collection + The message that will be displayed on failure + + + + Asserts that collection does not contain actual as an item. + + IEnumerable of objects to be considered + Object that cannot exist within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that superset is not a subject of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + + + + Asserts that superset is not a subject of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + + + + Asserts that superset is not a subject of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that superset is a subset of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + + + + Asserts that superset is a subset of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + + + + Asserts that superset is a subset of subset. + + The IEnumerable superset to be considered + The IEnumerable subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + The message to be displayed on failure + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + A custom comparer to perform the comparisons + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + A custom comparer to perform the comparisons + The message to be displayed on failure + + + + Assert that an array, list or other collection is ordered + + An array, list or other collection implementing IEnumerable + A custom comparer to perform the comparisons + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Summary description for DirectoryAssert + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + We don't actually want any instances of this object, but some people + like to inherit from it to add other static methods. Hence, the + protected constructor disallows any instances of this object. + + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if directories are not equal + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + The message to display if directories are not equal + + + + Verifies that two directories are equal. Two directories are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + The message to display if directories are not equal + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory containing the value that is expected + A directory containing the actual value + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + The message to display if directories are equal + Arguments to be used in formatting the message + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + The message to display if directories are equal + + + + Asserts that two directories are not equal. If they are equal + an is thrown. + + A directory path string containing the value that is expected + A directory path string containing the actual value + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + The message to display if directories are not equal + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + The message to display if directories are not equal + + + + Asserts that the directory is empty. If it is not empty + an is thrown. + + A directory to search + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + The message to display if directories are not equal + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + The message to display if directories are not equal + Arguments to be used in formatting the message + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + The message to display if directories are not equal + + + + Asserts that the directory is not empty. If it is empty + an is thrown. + + A directory to search + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + Arguments to be used in formatting the message + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + Arguments to be used in formatting the message + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + + + + Asserts that path contains actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + Arguments to be used in formatting the message + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + Arguments to be used in formatting the message + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + The message to display if directory is not within the path + + + + Asserts that path does not contain actual as a subdirectory or + an is thrown. + + A directory to search + sub-directory asserted to exist under directory + + + + Summary description for FileAssert. + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + We don't actually want any instances of this object, but some people + like to inherit from it to add other static methods. Hence, the + protected constructor disallows any instances of this object. + + + + + Verifies that two Streams are equal. Two Streams are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The expected Stream + The actual Stream + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two Streams are equal. Two Streams are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The expected Stream + The actual Stream + The message to display if objects are not equal + + + + Verifies that two Streams are equal. Two Streams are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The expected Stream + The actual Stream + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if objects are not equal + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + A file containing the value that is expected + A file containing the actual value + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if objects are not equal + + + + Verifies that two files are equal. Two files are considered + equal if both are null, or if both have the same value byte for byte. + If they are not equal an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + + + + Asserts that two Streams are not equal. If they are equal + an is thrown. + + The expected Stream + The actual Stream + The message to be displayed when the two Stream are the same. + Arguments to be used in formatting the message + + + + Asserts that two Streams are not equal. If they are equal + an is thrown. + + The expected Stream + The actual Stream + The message to be displayed when the Streams are the same. + + + + Asserts that two Streams are not equal. If they are equal + an is thrown. + + The expected Stream + The actual Stream + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + A file containing the value that is expected + A file containing the actual value + The message to display if objects are not equal + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + A file containing the value that is expected + A file containing the actual value + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if Streams are not equal + Arguments to be used in formatting the message + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + The message to display if objects are not equal + + + + Asserts that two files are not equal. If they are equal + an is thrown. + + The path to a file containing the value that is expected + The path to a file containing the actual value + + + + GlobalSettings is a place for setting default values used + by the framework in performing asserts. + + + + + Default tolerance for floating point equality + + + + + Class used to guard against unexpected argument values + by throwing an appropriate exception. + + + + + Throws an exception if an argument is null + + The value to be tested + The name of the argument + + + + Throws an exception if a string argument is null or empty + + The value to be tested + The name of the argument + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + Interface implemented by a user fixture in order to + validate any expected exceptions. It is only called + for test methods marked with the ExpectedException + attribute. + + + + + Method to handle an expected exception + + The exception to be handled + + + + Helper class with properties and methods that supply + a number of constraints used in Asserts. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + within a specified range. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + The ITestCaseData interface is implemented by a class + that is able to return complete testcases for use by + a parameterized test method. + + NOTE: This interface is used in both the framework + and the core, even though that results in two different + types. However, sharing the source code guarantees that + the various implementations will be compatible and that + the core is able to reflect successfully over the + framework implementations of ITestCaseData. + + + + + Gets the argument list to be provided to the test + + + + + Gets the expected result + + + + + Indicates whether a result has been specified. + This is necessary because the result may be + null, so it's value cannot be checked. + + + + + Gets the expected exception Type + + + + + Gets the FullName of the expected exception + + + + + Gets the name to be used for the test + + + + + Gets the description of the test + + + + + Gets a value indicating whether this is ignored. + + true if ignored; otherwise, false. + + + + Gets a value indicating whether this is explicit. + + true if explicit; otherwise, false. + + + + Gets the ignore reason. + + The ignore reason. + + + + The Iz class is a synonym for Is intended for use in VB, + which regards Is as a keyword. + + + + + The List class is a helper class with properties and methods + that supply a number of constraints used with lists and collections. + + + + + List.Map returns a ListMapper, which can be used to map + the original collection to another collection. + + + + + + + ListMapper is used to transform a collection used as an actual argument + producing another collection to be used in the assertion. + + + + + Construct a ListMapper based on a collection + + The collection to be transformed + + + + Produces a collection containing all the values of a property + + The collection of property values + + + + + Randomizer returns a set of random values in a repeatable + way, to allow re-running of tests if necessary. + + + + + Get a randomizer for a particular member, returning + one that has already been created if it exists. + This ensures that the same values are generated + each time the tests are reloaded. + + + + + Get a randomizer for a particular parameter, returning + one that has already been created if it exists. + This ensures that the same values are generated + each time the tests are reloaded. + + + + + Construct a randomizer using a random seed + + + + + Construct a randomizer using a specified seed + + + + + Return an array of random doubles between 0.0 and 1.0. + + + + + + + Return an array of random doubles with values in a specified range. + + + + + Return an array of random ints with values in a specified range. + + + + + Get a random seed for use in creating a randomizer. + + + + + The SpecialValue enum is used to represent TestCase arguments + that cannot be used as arguments to an Attribute. + + + + + Null represents a null value, which cannot be used as an + argument to an attribute under .NET 1.x + + + + + Basic Asserts on strings. + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + + + + Asserts that a string is not found within another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string is found within another string. + + The expected string + The string to be examined + + + + Asserts that a string starts with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string starts with another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string starts with another string. + + The expected string + The string to be examined + + + + Asserts that a string does not start with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not start with another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string does not start with another string. + + The expected string + The string to be examined + + + + Asserts that a string ends with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string ends with another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string ends with another string. + + The expected string + The string to be examined + + + + Asserts that a string does not end with another string. + + The expected string + The string to be examined + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not end with another string. + + The expected string + The string to be examined + The message to display in case of failure + + + + Asserts that a string does not end with another string. + + The expected string + The string to be examined + + + + Asserts that two strings are equal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that two strings are equal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + + + + Asserts that two strings are equal, without regard to case. + + The expected string + The actual string + + + + Asserts that two strings are not equal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that two strings are Notequal, without regard to case. + + The expected string + The actual string + The message to display in case of failure + + + + Asserts that two strings are not equal, without regard to case. + + The expected string + The actual string + + + + Asserts that a string matches an expected regular expression pattern. + + The regex pattern to be matched + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string matches an expected regular expression pattern. + + The regex pattern to be matched + The actual string + The message to display in case of failure + + + + Asserts that a string matches an expected regular expression pattern. + + The regex pattern to be matched + The actual string + + + + Asserts that a string does not match an expected regular expression pattern. + + The regex pattern to be used + The actual string + The message to display in case of failure + Arguments used in formatting the message + + + + Asserts that a string does not match an expected regular expression pattern. + + The regex pattern to be used + The actual string + The message to display in case of failure + + + + Asserts that a string does not match an expected regular expression pattern. + + The regex pattern to be used + The actual string + + + + The TestCaseData class represents a set of arguments + and other parameter info to be used for a parameterized + test case. It provides a number of instance modifiers + for use in initializing the test case. + + Note: Instance modifiers are getters that return + the same instance after modifying it's state. + + + + + The argument list to be provided to the test + + + + + The expected result to be returned + + + + + Set to true if this has an expected result + + + + + The expected exception Type + + + + + The FullName of the expected exception + + + + + The name to be used for the test + + + + + The description of the test + + + + + A dictionary of properties, used to add information + to tests without requiring the class to change. + + + + + If true, indicates that the test case is to be ignored + + + + + If true, indicates that the test case is marked explicit + + + + + The reason for ignoring a test case + + + + + Initializes a new instance of the class. + + The arguments. + + + + Initializes a new instance of the class. + + The argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + + + + Initializes a new instance of the class. + + The first argument. + The second argument. + The third argument. + + + + Sets the expected result for the test + + The expected result + A modified TestCaseData + + + + Sets the expected exception type for the test + + Type of the expected exception. + The modified TestCaseData instance + + + + Sets the expected exception type for the test + + FullName of the expected exception. + The modified TestCaseData instance + + + + Sets the name of the test case + + The modified TestCaseData instance + + + + Sets the description for the test case + being constructed. + + The description. + The modified TestCaseData instance. + + + + Applies a category to the test + + + + + + + Applies a named property to the test + + + + + + + + Applies a named property to the test + + + + + + + + Applies a named property to the test + + + + + + + + Ignores this TestCase. + + + + + + Ignores this TestCase, specifying the reason. + + The reason. + + + + + Marks this TestCase as Explicit + + + + + + Marks this TestCase as Explicit, specifying the reason. + + The reason. + + + + + Gets the argument list to be provided to the test + + + + + Gets the expected result + + + + + Returns true if the result has been set + + + + + Gets the expected exception Type + + + + + Gets the FullName of the expected exception + + + + + Gets the name to be used for the test + + + + + Gets the description of the test + + + + + Gets a value indicating whether this is ignored. + + true if ignored; otherwise, false. + + + + Gets a value indicating whether this is explicit. + + true if explicit; otherwise, false. + + + + Gets the ignore reason. + + The ignore reason. + + + + Gets a list of categories associated with this test. + + + + + Gets the property dictionary for this test + + + + + Provide the context information of the current test + + + + + Constructs a TestContext using the provided context dictionary + + A context dictionary + + + + Get the current test context. This is created + as needed. The user may save the context for + use within a test, but it should not be used + outside the test for which it is created. + + + + + Gets a TestAdapter representing the currently executing test in this context. + + + + + Gets a ResultAdapter representing the current result for the test + executing in this context. + + + + + Gets the directory containing the current test assembly. + + + + + Gets the directory to be used for outputing files created + by this test run. + + + + + TestAdapter adapts a Test for consumption by + the user test code. + + + + + Constructs a TestAdapter for this context + + The context dictionary + + + + The name of the test. + + + + + The FullName of the test + + + + + The properties of the test. + + + + + ResultAdapter adapts a TestResult for consumption by + the user test code. + + + + + Construct a ResultAdapter for a context + + The context holding the result + + + + The TestState of current test. This maps to the ResultState + used in nunit.core and is subject to change in the future. + + + + + The TestStatus of current test. This enum will be used + in future versions of NUnit and so is to be preferred + to the TestState value. + + + + + Provides details about a test + + + + + Creates an instance of TestDetails + + The fixture that the test is a member of, if available. + The method that implements the test, if available. + The full name of the test. + A string representing the type of test, e.g. "Test Case". + Indicates if the test represents a suite of tests. + + + + The fixture that the test is a member of, if available. + + + + + The method that implements the test, if available. + + + + + The full name of the test. + + + + + A string representing the type of test, e.g. "Test Case". + + + + + Indicates if the test represents a suite of tests. + + + + + The ResultState enum indicates the result of running a test + + + + + The result is inconclusive + + + + + The test was not runnable. + + + + + The test has been skipped. + + + + + The test has been ignored. + + + + + The test succeeded + + + + + The test failed + + + + + The test encountered an unexpected exception + + + + + The test was cancelled by the user + + + + + The TestStatus enum indicates the result of running a test + + + + + The test was inconclusive + + + + + The test has skipped + + + + + The test succeeded + + + + + The test failed + + + + + Helper class with static methods used to supply constraints + that operate on strings. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that fails if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the Regex pattern supplied as an argument. + + + + + Returns a constraint that fails if the actual + value matches the pattern supplied as an argument. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + TextMessageWriter writes constraint descriptions and messages + in displayable form as a text stream. It tailors the display + of individual message components to form the standard message + format of NUnit assertion failure messages. + + + + + MessageWriter is the abstract base for classes that write + constraint descriptions and messages in some form. The + class has separate methods for writing various components + of a message, allowing implementations to tailor the + presentation as needed. + + + + + Construct a MessageWriter given a culture + + + + + Method to write single line message with optional args, usually + written to precede the general failure message. + + The message to be written + Any arguments used in formatting the message + + + + Method to write single line message with optional args, usually + written to precede the general failure message, at a givel + indentation level. + + The indentation level of the message + The message to be written + Any arguments used in formatting the message + + + + Display Expected and Actual lines for a constraint. This + is called by MessageWriter's default implementation of + WriteMessageTo and provides the generic two-line display. + + The constraint that failed + + + + Display Expected and Actual lines for given values. This + method may be called by constraints that need more control over + the display of actual and expected values than is provided + by the default implementation. + + The expected value + The actual value causing the failure + + + + Display Expected and Actual lines for given values, including + a tolerance value on the Expected line. + + The expected value + The actual value causing the failure + The tolerance within which the test was made + + + + Display the expected and actual string values on separate lines. + If the mismatch parameter is >=0, an additional line is displayed + line containing a caret that points to the mismatch point. + + The expected string value + The actual string value + The point at which the strings don't match or -1 + If true, case is ignored in locating the point where the strings differ + If true, the strings should be clipped to fit the line + + + + Writes the text for a connector. + + The connector. + + + + Writes the text for a predicate. + + The predicate. + + + + Writes the text for an expected value. + + The expected value. + + + + Writes the text for a modifier + + The modifier. + + + + Writes the text for an actual value. + + The actual value. + + + + Writes the text for a generalized value. + + The value. + + + + Writes the text for a collection value, + starting at a particular point, to a max length + + The collection containing elements to write. + The starting point of the elements to write + The maximum number of elements to write + + + + Abstract method to get the max line length + + + + + Prefix used for the expected value line of a message + + + + + Prefix used for the actual value line of a message + + + + + Length of a message prefix + + + + + Construct a TextMessageWriter + + + + + Construct a TextMessageWriter, specifying a user message + and optional formatting arguments. + + + + + + + Method to write single line message with optional args, usually + written to precede the general failure message, at a givel + indentation level. + + The indentation level of the message + The message to be written + Any arguments used in formatting the message + + + + Display Expected and Actual lines for a constraint. This + is called by MessageWriter's default implementation of + WriteMessageTo and provides the generic two-line display. + + The constraint that failed + + + + Display Expected and Actual lines for given values. This + method may be called by constraints that need more control over + the display of actual and expected values than is provided + by the default implementation. + + The expected value + The actual value causing the failure + + + + Display Expected and Actual lines for given values, including + a tolerance value on the expected line. + + The expected value + The actual value causing the failure + The tolerance within which the test was made + + + + Display the expected and actual string values on separate lines. + If the mismatch parameter is >=0, an additional line is displayed + line containing a caret that points to the mismatch point. + + The expected string value + The actual string value + The point at which the strings don't match or -1 + If true, case is ignored in string comparisons + If true, clip the strings to fit the max line length + + + + Writes the text for a connector. + + The connector. + + + + Writes the text for a predicate. + + The predicate. + + + + Write the text for a modifier. + + The modifier. + + + + Writes the text for an expected value. + + The expected value. + + + + Writes the text for an actual value. + + The actual value. + + + + Writes the text for a generalized value. + + The value. + + + + Writes the text for a collection value, + starting at a particular point, to a max length + + The collection containing elements to write. + The starting point of the elements to write + The maximum number of elements to write + + + + Write the generic 'Expected' line for a constraint + + The constraint that failed + + + + Write the generic 'Expected' line for a given value + + The expected value + + + + Write the generic 'Expected' line for a given value + and tolerance. + + The expected value + The tolerance within which the test was made + + + + Write the generic 'Actual' line for a constraint + + The constraint for which the actual value is to be written + + + + Write the generic 'Actual' line for a given value + + The actual value causing a failure + + + + Gets or sets the maximum line length for this writer + + + + + Helper class with properties and methods that supply + constraints that operate on exceptions. + + + + + Creates a constraint specifying the exact type of exception expected + + + + + Creates a constraint specifying the exact type of exception expected + + + + + Creates a constraint specifying the type of exception expected + + + + + Creates a constraint specifying the type of exception expected + + + + + Creates a constraint specifying an expected exception + + + + + Creates a constraint specifying an exception with a given InnerException + + + + + Creates a constraint specifying an expected TargetInvocationException + + + + + Creates a constraint specifying an expected TargetInvocationException + + + + + Creates a constraint specifying an expected TargetInvocationException + + + + + Creates a constraint specifying that no exception is thrown + + + + + Attribute used to apply a category to a test + + + + + The name of the category + + + + + Construct attribute for a given category based on + a name. The name may not contain the characters ',', + '+', '-' or '!'. However, this is not checked in the + constructor since it would cause an error to arise at + as the test was loaded without giving a clear indication + of where the problem is located. The error is handled + in NUnitFramework.cs by marking the test as not + runnable. + + The name of the category + + + + Protected constructor uses the Type name as the name + of the category. + + + + + The name of the category + + + + + Used to mark a field for use as a datapoint when executing a theory + within the same fixture that requires an argument of the field's Type. + + + + + Used to mark an array as containing a set of datapoints to be used + executing a theory within the same fixture that requires an argument + of the Type of the array elements. + + + + + Attribute used to provide descriptive text about a + test case or fixture. + + + + + Construct the attribute + + Text describing the test + + + + Gets the test description + + + + + Enumeration indicating how the expected message parameter is to be used + + + + Expect an exact match + + + Expect a message containing the parameter string + + + Match the regular expression provided as a parameter + + + Expect a message that starts with the parameter string + + + + ExpectedExceptionAttribute + + + + + + Constructor for a non-specific exception + + + + + Constructor for a given type of exception + + The type of the expected exception + + + + Constructor for a given exception name + + The full name of the expected exception + + + + Gets or sets the expected exception type + + + + + Gets or sets the full Type name of the expected exception + + + + + Gets or sets the expected message text + + + + + Gets or sets the user message displayed in case of failure + + + + + Gets or sets the type of match to be performed on the expected message + + + + + Gets the name of a method to be used as an exception handler + + + + + ExplicitAttribute marks a test or test fixture so that it will + only be run if explicitly executed from the gui or command line + or if it is included by use of a filter. The test will not be + run simply because an enclosing suite is run. + + + + + Default constructor + + + + + Constructor with a reason + + The reason test is marked explicit + + + + The reason test is marked explicit + + + + + Attribute used to mark a test that is to be ignored. + Ignored tests result in a warning message when the + tests are run. + + + + + Constructs the attribute without giving a reason + for ignoring the test. + + + + + Constructs the attribute giving a reason for ignoring the test + + The reason for ignoring the test + + + + The reason for ignoring a test + + + + + Abstract base for Attributes that are used to include tests + in the test run based on environmental settings. + + + + + Constructor with no included items specified, for use + with named property syntax. + + + + + Constructor taking one or more included items + + Comma-delimited list of included items + + + + Name of the item that is needed in order for + a test to run. Multiple itemss may be given, + separated by a comma. + + + + + Name of the item to be excluded. Multiple items + may be given, separated by a comma. + + + + + The reason for including or excluding the test + + + + + PlatformAttribute is used to mark a test fixture or an + individual method as applying to a particular platform only. + + + + + Constructor with no platforms specified, for use + with named property syntax. + + + + + Constructor taking one or more platforms + + Comma-deliminted list of platforms + + + + CultureAttribute is used to mark a test fixture or an + individual method as applying to a particular Culture only. + + + + + Constructor with no cultures specified, for use + with named property syntax. + + + + + Constructor taking one or more cultures + + Comma-deliminted list of cultures + + + + Marks a test to use a combinatorial join of any argument data + provided. NUnit will create a test case for every combination of + the arguments provided. This can result in a large number of test + cases and so should be used judiciously. This is the default join + type, so the attribute need not be used except as documentation. + + + + + PropertyAttribute is used to attach information to a test as a name/value pair.. + + + + + Construct a PropertyAttribute with a name and string value + + The name of the property + The property value + + + + Construct a PropertyAttribute with a name and int value + + The name of the property + The property value + + + + Construct a PropertyAttribute with a name and double value + + The name of the property + The property value + + + + Constructor for derived classes that set the + property dictionary directly. + + + + + Constructor for use by derived classes that use the + name of the type as the property name. Derived classes + must ensure that the Type of the property value is + a standard type supported by the BCL. Any custom + types will cause a serialization Exception when + in the client. + + + + + Gets the property dictionary for this attribute + + + + + Default constructor + + + + + Marks a test to use pairwise join of any argument data provided. + NUnit will attempt too excercise every pair of argument values at + least once, using as small a number of test cases as it can. With + only two arguments, this is the same as a combinatorial join. + + + + + Default constructor + + + + + Marks a test to use a sequential join of any argument data + provided. NUnit will use arguements for each parameter in + sequence, generating test cases up to the largest number + of argument values provided and using null for any arguments + for which it runs out of values. Normally, this should be + used with the same number of arguments for each parameter. + + + + + Default constructor + + + + + Summary description for MaxTimeAttribute. + + + + + Construct a MaxTimeAttribute, given a time in milliseconds. + + The maximum elapsed time in milliseconds + + + + RandomAttribute is used to supply a set of random values + to a single parameter of a parameterized test. + + + + + ValuesAttribute is used to provide literal arguments for + an individual parameter of a test. + + + + + Abstract base class for attributes that apply to parameters + and supply data for the parameter. + + + + + Gets the data to be provided to the specified parameter + + + + + The collection of data to be returned. Must + be set by any derived attribute classes. + We use an object[] so that the individual + elements may have their type changed in GetData + if necessary. + + + + + Construct with one argument + + + + + + Construct with two arguments + + + + + + + Construct with three arguments + + + + + + + + Construct with an array of arguments + + + + + + Get the collection of values to be used as arguments + + + + + Construct a set of doubles from 0.0 to 1.0, + specifying only the count. + + + + + + Construct a set of doubles from min to max + + + + + + + + Construct a set of ints from min to max + + + + + + + + Get the collection of values to be used as arguments + + + + + RangeAttribute is used to supply a range of values to an + individual parameter of a parameterized test. + + + + + Construct a range of ints using default step of 1 + + + + + + + Construct a range of ints specifying the step size + + + + + + + + Construct a range of longs + + + + + + + + Construct a range of doubles + + + + + + + + Construct a range of floats + + + + + + + + RepeatAttribute may be applied to test case in order + to run it multiple times. + + + + + Construct a RepeatAttribute + + The number of times to run the test + + + + RequiredAddinAttribute may be used to indicate the names of any addins + that must be present in order to run some or all of the tests in an + assembly. If the addin is not loaded, the entire assembly is marked + as NotRunnable. + + + + + Initializes a new instance of the class. + + The required addin. + + + + Gets the name of required addin. + + The required addin name. + + + + Summary description for SetCultureAttribute. + + + + + Construct given the name of a culture + + + + + + Summary description for SetUICultureAttribute. + + + + + Construct given the name of a culture + + + + + + SetUpAttribute is used in a TestFixture to identify a method + that is called immediately before each test is run. It is + also used in a SetUpFixture to identify the method that is + called once, before any of the subordinate tests are run. + + + + + Attribute used to mark a class that contains one-time SetUp + and/or TearDown methods that apply to all the tests in a + namespace or an assembly. + + + + + Attribute used to mark a static (shared in VB) property + that returns a list of tests. + + + + + Attribute used in a TestFixture to identify a method that is + called immediately after each test is run. It is also used + in a SetUpFixture to identify the method that is called once, + after all subordinate tests have run. In either case, the method + is guaranteed to be called, even if an exception is thrown. + + + + + Provide actions to execute before and after tests. + + + + + When implemented by an attribute, this interface implemented to provide actions to execute before and after tests. + + + + + Executed before each test is run + + Provides details about the test that is going to be run. + + + + Executed after each test is run + + Provides details about the test that has just been run. + + + + Provides the target for the action attribute + + The target for the action attribute + + + + Adding this attribute to a method within a + class makes the method callable from the NUnit test runner. There is a property + called Description which is optional which you can provide a more detailed test + description. This class cannot be inherited. + + + + [TestFixture] + public class Fixture + { + [Test] + public void MethodToTest() + {} + + [Test(Description = "more detailed description")] + publc void TestDescriptionMethod() + {} + } + + + + + + Descriptive text for this test + + + + + TestCaseAttribute is used to mark parameterized test cases + and provide them with their arguments. + + + + + Construct a TestCaseAttribute with a list of arguments. + This constructor is not CLS-Compliant + + + + + + Construct a TestCaseAttribute with a single argument + + + + + + Construct a TestCaseAttribute with a two arguments + + + + + + + Construct a TestCaseAttribute with a three arguments + + + + + + + + Gets the list of arguments to a test case + + + + + Gets or sets the expected result. Use + ExpectedResult by preference. + + The result. + + + + Gets or sets the expected result. + + The result. + + + + Gets a flag indicating whether an expected + result has been set. + + + + + Gets a list of categories associated with this test; + + + + + Gets or sets the category associated with this test. + May be a single category or a comma-separated list. + + + + + Gets or sets the expected exception. + + The expected exception. + + + + Gets or sets the name the expected exception. + + The expected name of the exception. + + + + Gets or sets the expected message of the expected exception + + The expected message of the exception. + + + + Gets or sets the type of match to be performed on the expected message + + + + + Gets or sets the description. + + The description. + + + + Gets or sets the name of the test. + + The name of the test. + + + + Gets or sets the ignored status of the test + + + + + Gets or sets the ignored status of the test + + + + + Gets or sets the explicit status of the test + + + + + Gets or sets the reason for not running the test + + + + + Gets or sets the reason for not running the test. + Set has the side effect of marking the test as ignored. + + The ignore reason. + + + + FactoryAttribute indicates the source to be used to + provide test cases for a test method. + + + + + Construct with the name of the data source, which must + be a property, field or method of the test class itself. + + An array of the names of the factories that will provide data + + + + Construct with a Type, which must implement IEnumerable + + The Type that will provide data + + + + Construct with a Type and name. + that don't support params arrays. + + The Type that will provide data + The name of the method, property or field that will provide data + + + + The name of a the method, property or fiend to be used as a source + + + + + A Type to be used as a source + + + + + Gets or sets the category associated with this test. + May be a single category or a comma-separated list. + + + + + [TestFixture] + public class ExampleClass + {} + + + + + Default constructor + + + + + Construct with a object[] representing a set of arguments. + In .NET 2.0, the arguments may later be separated into + type arguments and constructor arguments. + + + + + + Descriptive text for this fixture + + + + + Gets and sets the category for this fixture. + May be a comma-separated list of categories. + + + + + Gets a list of categories for this fixture + + + + + The arguments originally provided to the attribute + + + + + Gets or sets a value indicating whether this should be ignored. + + true if ignore; otherwise, false. + + + + Gets or sets the ignore reason. May set Ignored as a side effect. + + The ignore reason. + + + + Get or set the type arguments. If not set + explicitly, any leading arguments that are + Types are taken as type arguments. + + + + + Attribute used to identify a method that is + called before any tests in a fixture are run. + + + + + Attribute used to identify a method that is called after + all the tests in a fixture have run. The method is + guaranteed to be called, even if an exception is thrown. + + + + + Adding this attribute to a method within a + class makes the method callable from the NUnit test runner. There is a property + called Description which is optional which you can provide a more detailed test + description. This class cannot be inherited. + + + + [TestFixture] + public class Fixture + { + [Test] + public void MethodToTest() + {} + + [Test(Description = "more detailed description")] + publc void TestDescriptionMethod() + {} + } + + + + + + Used on a method, marks the test with a timeout value in milliseconds. + The test will be run in a separate thread and is cancelled if the timeout + is exceeded. Used on a method or assembly, sets the default timeout + for all contained test methods. + + + + + Construct a TimeoutAttribute given a time in milliseconds + + The timeout value in milliseconds + + + + Marks a test that must run in the STA, causing it + to run in a separate thread if necessary. + + On methods, you may also use STAThreadAttribute + to serve the same purpose. + + + + + Construct a RequiresSTAAttribute + + + + + Marks a test that must run in the MTA, causing it + to run in a separate thread if necessary. + + On methods, you may also use MTAThreadAttribute + to serve the same purpose. + + + + + Construct a RequiresMTAAttribute + + + + + Marks a test that must run on a separate thread. + + + + + Construct a RequiresThreadAttribute + + + + + Construct a RequiresThreadAttribute, specifying the apartment + + + + + ValueSourceAttribute indicates the source to be used to + provide data for one parameter of a test method. + + + + + Construct with the name of the factory - for use with languages + that don't support params arrays. + + The name of the data source to be used + + + + Construct with a Type and name - for use with languages + that don't support params arrays. + + The Type that will provide data + The name of the method, property or field that will provide data + + + + The name of a the method, property or fiend to be used as a source + + + + + A Type to be used as a source + + + + + AllItemsConstraint applies another constraint to each + item in a collection, succeeding if they all succeed. + + + + + Abstract base class used for prefixes + + + + + The Constraint class is the base of all built-in constraints + within NUnit. It provides the operator overloads used to combine + constraints. + + + + + The IConstraintExpression interface is implemented by all + complete and resolvable constraints and expressions. + + + + + Return the top-level constraint for this expression + + + + + + Static UnsetObject used to detect derived constraints + failing to set the actual value. + + + + + The actual value being tested against a constraint + + + + + The display name of this Constraint for use by ToString() + + + + + Argument fields used by ToString(); + + + + + The builder holding this constraint + + + + + Construct a constraint with no arguments + + + + + Construct a constraint with one argument + + + + + Construct a constraint with two arguments + + + + + Sets the ConstraintBuilder holding this constraint + + + + + Write the failure message to the MessageWriter provided + as an argument. The default implementation simply passes + the constraint and the actual value to the writer, which + then displays the constraint description and the value. + + Constraints that need to provide additional details, + such as where the error occured can override this. + + The MessageWriter on which to display the message + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Test whether the constraint is satisfied by an + ActualValueDelegate that returns the value to be tested. + The default implementation simply evaluates the delegate + but derived classes may override it to provide for delayed + processing. + + An + True for success, false for failure + + + + Test whether the constraint is satisfied by a given reference. + The default implementation simply dereferences the value but + derived classes may override it to provide for delayed processing. + + A reference to the value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Default override of ToString returns the constraint DisplayName + followed by any arguments within angle brackets. + + + + + + Returns the string representation of this constraint + + + + + This operator creates a constraint that is satisfied only if both + argument constraints are satisfied. + + + + + This operator creates a constraint that is satisfied if either + of the argument constraints is satisfied. + + + + + This operator creates a constraint that is satisfied if the + argument constraint is not satisfied. + + + + + Returns a DelayedConstraint with the specified delay time. + + The delay in milliseconds. + + + + + Returns a DelayedConstraint with the specified delay time + and polling interval. + + The delay in milliseconds. + The interval at which to test the constraint. + + + + + The display name of this Constraint for use by ToString(). + The default value is the name of the constraint with + trailing "Constraint" removed. Derived classes may set + this to another name in their constructors. + + + + + Returns a ConstraintExpression by appending And + to the current constraint. + + + + + Returns a ConstraintExpression by appending And + to the current constraint. + + + + + Returns a ConstraintExpression by appending Or + to the current constraint. + + + + + Class used to detect any derived constraints + that fail to set the actual value in their + Matches override. + + + + + The base constraint + + + + + Construct given a base constraint + + + + + + Construct an AllItemsConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + failing if any item fails. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + AndConstraint succeeds only if both members succeed. + + + + + BinaryConstraint is the abstract base of all constraints + that combine two other constraints in some fashion. + + + + + The first constraint being combined + + + + + The second constraint being combined + + + + + Construct a BinaryConstraint from two other constraints + + The first constraint + The second constraint + + + + Create an AndConstraint from two other constraints + + The first constraint + The second constraint + + + + Apply both member constraints to an actual value, succeeding + succeeding only if both of them succeed. + + The actual value + True if the constraints both succeeded + + + + Write a description for this contraint to a MessageWriter + + The MessageWriter to receive the description + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + AssignableFromConstraint is used to test that an object + can be assigned from a given Type. + + + + + TypeConstraint is the abstract base for constraints + that take a Type as their expected value. + + + + + The expected Type used by the constraint + + + + + Construct a TypeConstraint for a given Type + + + + + + Write the actual value for a failing constraint test to a + MessageWriter. TypeConstraints override this method to write + the name of the type. + + The writer on which the actual value is displayed + + + + Construct an AssignableFromConstraint for the type provided + + + + + + Test whether an object can be assigned from the specified type + + The object to be tested + True if the object can be assigned a value of the expected Type, otherwise false. + + + + Write a description of this constraint to a MessageWriter + + The MessageWriter to use + + + + AssignableToConstraint is used to test that an object + can be assigned to a given Type. + + + + + Construct an AssignableToConstraint for the type provided + + + + + + Test whether an object can be assigned to the specified type + + The object to be tested + True if the object can be assigned a value of the expected Type, otherwise false. + + + + Write a description of this constraint to a MessageWriter + + The MessageWriter to use + + + + AttributeConstraint tests that a specified attribute is present + on a Type or other provider and that the value of the attribute + satisfies some other constraint. + + + + + Constructs an AttributeConstraint for a specified attriute + Type and base constraint. + + + + + + + Determines whether the Type or other provider has the + expected attribute and if its value matches the + additional constraint specified. + + + + + Writes a description of the attribute to the specified writer. + + + + + Writes the actual value supplied to the specified writer. + + + + + Returns a string representation of the constraint. + + + + + AttributeExistsConstraint tests for the presence of a + specified attribute on a Type. + + + + + Constructs an AttributeExistsConstraint for a specific attribute Type + + + + + + Tests whether the object provides the expected attribute. + + A Type, MethodInfo, or other ICustomAttributeProvider + True if the expected attribute is present, otherwise false + + + + Writes the description of the constraint to the specified writer + + + + + BasicConstraint is the abstract base for constraints that + perform a simple comparison to a constant value. + + + + + Initializes a new instance of the class. + + The expected. + The description. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + BinarySerializableConstraint tests whether + an object is serializable in binary format. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Returns the string representation + + + + + CollectionConstraint is the abstract base class for + constraints that operate on collections. + + + + + Construct an empty CollectionConstraint + + + + + Construct a CollectionConstraint + + + + + + Determines whether the specified enumerable is empty. + + The enumerable. + + true if the specified enumerable is empty; otherwise, false. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Protected method to be implemented by derived classes + + + + + + + CollectionContainsConstraint is used to test whether a collection + contains an expected object as a member. + + + + + CollectionItemsEqualConstraint is the abstract base class for all + collection constraints that apply some notion of item equality + as a part of their operation. + + + + + Construct an empty CollectionConstraint + + + + + Construct a CollectionConstraint + + + + + + Flag the constraint to use the supplied EqualityAdapter. + NOTE: For internal use only. + + The EqualityAdapter to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied Comparison object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Compares two collection members for equality + + + + + Return a new CollectionTally for use in making tests + + The collection to be included in the tally + + + + Flag the constraint to ignore case and return self. + + + + + Construct a CollectionContainsConstraint + + + + + + Test whether the expected item is contained in the collection + + + + + + + Write a descripton of the constraint to a MessageWriter + + + + + + CollectionEquivalentCOnstraint is used to determine whether two + collections are equivalent. + + + + + Construct a CollectionEquivalentConstraint + + + + + + Test whether two collections are equivalent + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + CollectionOrderedConstraint is used to test whether a collection is ordered. + + + + + Construct a CollectionOrderedConstraint + + + + + Modifies the constraint to use an IComparer and returns self. + + + + + Modifies the constraint to use an IComparer<T> and returns self. + + + + + Modifies the constraint to use a Comparison<T> and returns self. + + + + + Modifies the constraint to test ordering by the value of + a specified property and returns self. + + + + + Test whether the collection is ordered + + + + + + + Write a description of the constraint to a MessageWriter + + + + + + Returns the string representation of the constraint. + + + + + + If used performs a reverse comparison + + + + + CollectionSubsetConstraint is used to determine whether + one collection is a subset of another + + + + + Construct a CollectionSubsetConstraint + + The collection that the actual value is expected to be a subset of + + + + Test whether the actual collection is a subset of + the expected collection provided. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + CollectionTally counts (tallies) the number of + occurences of each object in one or more enumerations. + + + + + Construct a CollectionTally object from a comparer and a collection + + + + + Try to remove an object from the tally + + The object to remove + True if successful, false if the object was not found + + + + Try to remove a set of objects from the tally + + The objects to remove + True if successful, false if any object was not found + + + + The number of objects remaining in the tally + + + + + ComparisonAdapter class centralizes all comparisons of + values in NUnit, adapting to the use of any provided + IComparer, IComparer<T> or Comparison<T> + + + + + Returns a ComparisonAdapter that wraps an IComparer + + + + + Returns a ComparisonAdapter that wraps an IComparer<T> + + + + + Returns a ComparisonAdapter that wraps a Comparison<T> + + + + + Compares two objects + + + + + Gets the default ComparisonAdapter, which wraps an + NUnitComparer object. + + + + + Construct a ComparisonAdapter for an IComparer + + + + + Compares two objects + + + + + + + + Construct a default ComparisonAdapter + + + + + ComparisonAdapter<T> extends ComparisonAdapter and + allows use of an IComparer<T> or Comparison<T> + to actually perform the comparison. + + + + + Construct a ComparisonAdapter for an IComparer<T> + + + + + Compare a Type T to an object + + + + + Construct a ComparisonAdapter for a Comparison<T> + + + + + Compare a Type T to an object + + + + + Abstract base class for constraints that compare values to + determine if one is greater than, equal to or less than + the other. This class supplies the Using modifiers. + + + + + ComparisonAdapter to be used in making the comparison + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + + + + Modifies the constraint to use an IComparer and returns self + + + + + Modifies the constraint to use an IComparer<T> and returns self + + + + + Modifies the constraint to use a Comparison<T> and returns self + + + + + Delegate used to delay evaluation of the actual value + to be used in evaluating a constraint + + + + + ConstraintBuilder maintains the stacks that are used in + processing a ConstraintExpression. An OperatorStack + is used to hold operators that are waiting for their + operands to be reognized. a ConstraintStack holds + input constraints as well as the results of each + operator applied. + + + + + Initializes a new instance of the class. + + + + + Appends the specified operator to the expression by first + reducing the operator stack and then pushing the new + operator on the stack. + + The operator to push. + + + + Appends the specified constraint to the expresson by pushing + it on the constraint stack. + + The constraint to push. + + + + Sets the top operator right context. + + The right context. + + + + Reduces the operator stack until the topmost item + precedence is greater than or equal to the target precedence. + + The target precedence. + + + + Resolves this instance, returning a Constraint. If the builder + is not currently in a resolvable state, an exception is thrown. + + The resolved constraint + + + + Gets a value indicating whether this instance is resolvable. + + + true if this instance is resolvable; otherwise, false. + + + + + OperatorStack is a type-safe stack for holding ConstraintOperators + + + + + Initializes a new instance of the class. + + The builder. + + + + Pushes the specified operator onto the stack. + + The op. + + + + Pops the topmost operator from the stack. + + + + + + Gets a value indicating whether this is empty. + + true if empty; otherwise, false. + + + + Gets the topmost operator without modifying the stack. + + The top. + + + + ConstraintStack is a type-safe stack for holding Constraints + + + + + Initializes a new instance of the class. + + The builder. + + + + Pushes the specified constraint. As a side effect, + the constraint's builder field is set to the + ConstraintBuilder owning this stack. + + The constraint. + + + + Pops this topmost constrait from the stack. + As a side effect, the constraint's builder + field is set to null. + + + + + + Gets a value indicating whether this is empty. + + true if empty; otherwise, false. + + + + Gets the topmost constraint without modifying the stack. + + The topmost constraint + + + + ConstraintExpression represents a compound constraint in the + process of being constructed from a series of syntactic elements. + + Individual elements are appended to the expression as they are + reognized. Once an actual Constraint is appended, the expression + returns a resolvable Constraint. + + + + + ConstraintExpressionBase is the abstract base class for the + ConstraintExpression class, which represents a + compound constraint in the process of being constructed + from a series of syntactic elements. + + NOTE: ConstraintExpressionBase is separate because the + ConstraintExpression class was generated in earlier + versions of NUnit. The two classes may be combined + in a future version. + + + + + The ConstraintBuilder holding the elements recognized so far + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the + class passing in a ConstraintBuilder, which may be pre-populated. + + The builder. + + + + Returns a string representation of the expression as it + currently stands. This should only be used for testing, + since it has the side-effect of resolving the expression. + + + + + + Appends an operator to the expression and returns the + resulting expression itself. + + + + + Appends a self-resolving operator to the expression and + returns a new ResolvableConstraintExpression. + + + + + Appends a constraint to the expression and returns that + constraint, which is associated with the current state + of the expression being built. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the + class passing in a ConstraintBuilder, which may be pre-populated. + + The builder. + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding only if a specified number of them succeed. + + + + + Returns a new PropertyConstraintExpression, which will either + test for the existence of the named property on the object + being tested or apply any following constraint to that property. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns a new AttributeConstraint checking for the + presence of a particular attribute on an object. + + + + + Returns the constraint provided as an argument - used to allow custom + custom constraints to easily participate in the syntax. + + + + + Returns the constraint provided as an argument - used to allow custom + custom constraints to easily participate in the syntax. + + + + + Returns a constraint that tests two items for equality + + + + + Returns a constraint that tests that two references are the same object + + + + + Returns a constraint that tests whether the + actual value is greater than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is greater than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the + actual value is less than or equal to the suppled argument + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual + value is of the exact type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is of the type supplied as an argument or a derived type. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is assignable from the type supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a collection containing the same elements as the + collection supplied as an argument. + + + + + Returns a constraint that tests whether the actual value + is a subset of the collection supplied as an argument. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new CollectionContainsConstraint checking for the + presence of a particular object in the collection. + + + + + Returns a new ContainsConstraint. This constraint + will, in turn, make use of the appropriate second-level + constraint, depending on the type of the actual argument. + This overload is only used if the item sought is a string, + since any other type implies that we are looking for a + collection member. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value contains the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value starts with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value ends with the substring supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that succeeds if the actual + value matches the regular expression supplied as an argument. + + + + + Returns a constraint that tests whether the path provided + is the same as an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the path provided + is the same path or under an expected path after canonicalization. + + + + + Returns a constraint that tests whether the actual value falls + within a specified range. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression that negates any + following constraint. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them succeed. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if at least one of them succeeds. + + + + + Returns a ConstraintExpression, which will apply + the following constraint to all members of a collection, + succeeding if all of them fail. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Length property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Count property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the Message property of the object being tested. + + + + + Returns a new ConstraintExpression, which will apply the following + constraint to the InnerException property of the object being tested. + + + + + With is currently a NOP - reserved for future use. + + + + + Returns a constraint that tests for null + + + + + Returns a constraint that tests for True + + + + + Returns a constraint that tests for False + + + + + Returns a constraint that tests for a positive value + + + + + Returns a constraint that tests for a negative value + + + + + Returns a constraint that tests for NaN + + + + + Returns a constraint that tests for empty + + + + + Returns a constraint that tests whether a collection + contains all unique items. + + + + + Returns a constraint that tests whether an object graph is serializable in binary format. + + + + + Returns a constraint that tests whether an object graph is serializable in xml format. + + + + + Returns a constraint that tests whether a collection is ordered + + + + + ContainsConstraint tests a whether a string contains a substring + or a collection contains an object. It postpones the decision of + which test to use until the type of the actual argument is known. + This allows testing whether a string is contained in a collection + or as a substring of another string using the same syntax. + + + + + Initializes a new instance of the class. + + The expected. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied Comparison object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to ignore case and return self. + + + + + Applies a delay to the match so that a match can be evaluated in the future. + + + + + Creates a new DelayedConstraint + + The inner constraint two decorate + The time interval after which the match is performed + If the value of is less than 0 + + + + Creates a new DelayedConstraint + + The inner constraint two decorate + The time interval after which the match is performed + The time interval used for polling + If the value of is less than 0 + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for if the base constraint fails, false if it succeeds + + + + Test whether the constraint is satisfied by a delegate + + The delegate whose value is to be tested + True for if the base constraint fails, false if it succeeds + + + + Test whether the constraint is satisfied by a given reference. + Overridden to wait for the specified delay period before + calling the base constraint with the dereferenced value. + + A reference to the value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a MessageWriter. + + The writer on which the actual value is displayed + + + + Returns the string representation of the constraint. + + + + + EmptyCollectionConstraint tests whether a collection is empty. + + + + + Check that the collection is empty + + + + + + + Write the constraint description to a MessageWriter + + + + + + EmptyConstraint tests a whether a string or collection is empty, + postponing the decision about which test is applied until the + type of the actual argument is known. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + EmptyDirectoryConstraint is used to test that a directory is empty + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + EmptyStringConstraint tests whether a string is empty. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + EndsWithConstraint can test whether a string ends + with an expected substring. + + + + + StringConstraint is the abstract base for constraints + that operate on strings. It supports the IgnoreCase + modifier for string operations. + + + + + The expected value + + + + + Indicates whether tests should be case-insensitive + + + + + Constructs a StringConstraint given an expected value + + The expected value + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Test whether the constraint is satisfied by a given string + + The string to be tested + True for success, false for failure + + + + Modify the constraint to ignore case in matching. + + + + + Initializes a new instance of the class. + + The expected string + + + + Test whether the constraint is matched by the actual value. + This is a template method, which calls the IsMatch method + of the derived class. + + + + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + EqualConstraint is able to compare an actual value with the + expected value provided in its constructor. Two objects are + considered equal if both are null, or if both have the same + value. NUnit has special semantics for some object types. + + + + + If true, strings in error messages will be clipped + + + + + NUnitEqualityComparer used to test equality. + + + + + Initializes a new instance of the class. + + The expected value. + + + + Flag the constraint to use a tolerance when determining equality. + + Tolerance value to be used + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied Comparison object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Flag the constraint to use the supplied IEqualityComparer object. + + The IComparer object to use. + Self. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write a failure message. Overridden to provide custom + failure messages for EqualConstraint. + + The MessageWriter to write to + + + + Write description of this constraint + + The MessageWriter to write to + + + + Display the failure information for two collections that did not match. + + The MessageWriter on which to display + The expected collection. + The actual collection + The depth of this failure in a set of nested collections + + + + Displays a single line showing the types and sizes of the expected + and actual enumerations, collections or arrays. If both are identical, + the value is only shown once. + + The MessageWriter on which to display + The expected collection or array + The actual collection or array + The indentation level for the message line + + + + Displays a single line showing the point in the expected and actual + arrays at which the comparison failed. If the arrays have different + structures or dimensions, both values are shown. + + The MessageWriter on which to display + The expected array + The actual array + Index of the failure point in the underlying collections + The indentation level for the message line + + + + Display the failure information for two IEnumerables that did not match. + + The MessageWriter on which to display + The expected enumeration. + The actual enumeration + The depth of this failure in a set of nested collections + + + + Flag the constraint to ignore case and return self. + + + + + Flag the constraint to suppress string clipping + and return self. + + + + + Flag the constraint to compare arrays as collections + and return self. + + + + + Switches the .Within() modifier to interpret its tolerance as + a distance in representable values (see remarks). + + Self. + + Ulp stands for "unit in the last place" and describes the minimum + amount a given value can change. For any integers, an ulp is 1 whole + digit. For floating point values, the accuracy of which is better + for smaller numbers and worse for larger numbers, an ulp depends + on the size of the number. Using ulps for comparison of floating + point results instead of fixed tolerances is safer because it will + automatically compensate for the added inaccuracy of larger numbers. + + + + + Switches the .Within() modifier to interpret its tolerance as + a percentage that the actual values is allowed to deviate from + the expected value. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in days. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in hours. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in minutes. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in seconds. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in milliseconds. + + Self + + + + Causes the tolerance to be interpreted as a TimeSpan in clock ticks. + + Self + + + + EqualityAdapter class handles all equality comparisons + that use an IEqualityComparer, IEqualityComparer<T> + or a ComparisonAdapter. + + + + + Compares two objects, returning true if they are equal + + + + + Returns true if the two objects can be compared by this adapter. + The base adapter cannot handle IEnumerables except for strings. + + + + + Returns an EqualityAdapter that wraps an IComparer. + + + + + Returns an EqualityAdapter that wraps an IEqualityComparer. + + + + + Returns an EqualityAdapter that wraps an IEqualityComparer<T>. + + + + + Returns an EqualityAdapter that wraps an IComparer<T>. + + + + + Returns an EqualityAdapter that wraps a Comparison<T>. + + + + + EqualityAdapter that wraps an IComparer. + + + + + Returns true if the two objects can be compared by this adapter. + Generic adapter requires objects of the specified type. + + + + + EqualityAdapter that wraps an IComparer. + + + + + EqualityAdapterList represents a list of EqualityAdapters + in a common class across platforms. + + + + + ExactCountConstraint applies another constraint to each + item in a collection, succeeding only if a specified + number of items succeed. + + + + + Construct an ExactCountConstraint on top of an existing constraint + + + + + + + Apply the item constraint to each item in the collection, + succeeding only if the expected number of items pass. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + ExactTypeConstraint is used to test that an object + is of the exact type provided in the constructor + + + + + Construct an ExactTypeConstraint for a given Type + + The expected Type. + + + + Test that an object is of the exact type specified + + The actual value. + True if the tested object is of the exact type provided, otherwise false. + + + + Write the description of this constraint to a MessageWriter + + The MessageWriter to use + + + + ExceptionTypeConstraint is a special version of ExactTypeConstraint + used to provided detailed info about the exception thrown in + an error message. + + + + + Constructs an ExceptionTypeConstraint + + + + + Write the actual value for a failing constraint test to a + MessageWriter. Overriden to write additional information + in the case of an Exception. + + The MessageWriter to use + + + + FailurePoint class represents one point of failure + in an equality test. + + + + + The location of the failure + + + + + The expected value + + + + + The actual value + + + + + Indicates whether the expected value is valid + + + + + Indicates whether the actual value is valid + + + + + FailurePointList represents a set of FailurePoints + in a cross-platform way. + + + + + FalseConstraint tests that the actual value is false + + + + + Initializes a new instance of the class. + + + + Helper routines for working with floating point numbers + + + The floating point comparison code is based on this excellent article: + http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm + + + "ULP" means Unit in the Last Place and in the context of this library refers to + the distance between two adjacent floating point numbers. IEEE floating point + numbers can only represent a finite subset of natural numbers, with greater + accuracy for smaller numbers and lower accuracy for very large numbers. + + + If a comparison is allowed "2 ulps" of deviation, that means the values are + allowed to deviate by up to 2 adjacent floating point values, which might be + as low as 0.0000001 for small numbers or as high as 10.0 for large numbers. + + + + + Compares two floating point values for equality + First floating point value to be compared + Second floating point value t be compared + + Maximum number of representable floating point values that are allowed to + be between the left and the right floating point values + + True if both numbers are equal or close to being equal + + + Floating point values can only represent a finite subset of natural numbers. + For example, the values 2.00000000 and 2.00000024 can be stored in a float, + but nothing inbetween them. + + + This comparison will count how many possible floating point values are between + the left and the right number. If the number of possible values between both + numbers is less than or equal to maxUlps, then the numbers are considered as + being equal. + + + Implementation partially follows the code outlined here: + http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ + + + + + Compares two double precision floating point values for equality + First double precision floating point value to be compared + Second double precision floating point value t be compared + + Maximum number of representable double precision floating point values that are + allowed to be between the left and the right double precision floating point values + + True if both numbers are equal or close to being equal + + + Double precision floating point values can only represent a limited series of + natural numbers. For example, the values 2.0000000000000000 and 2.0000000000000004 + can be stored in a double, but nothing inbetween them. + + + This comparison will count how many possible double precision floating point + values are between the left and the right number. If the number of possible + values between both numbers is less than or equal to maxUlps, then the numbers + are considered as being equal. + + + Implementation partially follows the code outlined here: + http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ + + + + + + Reinterprets the memory contents of a floating point value as an integer value + + + Floating point value whose memory contents to reinterpret + + + The memory contents of the floating point value interpreted as an integer + + + + + Reinterprets the memory contents of a double precision floating point + value as an integer value + + + Double precision floating point value whose memory contents to reinterpret + + + The memory contents of the double precision floating point value + interpreted as an integer + + + + + Reinterprets the memory contents of an integer as a floating point value + + Integer value whose memory contents to reinterpret + + The memory contents of the integer value interpreted as a floating point value + + + + + Reinterprets the memory contents of an integer value as a double precision + floating point value + + Integer whose memory contents to reinterpret + + The memory contents of the integer interpreted as a double precision + floating point value + + + + Union of a floating point variable and an integer + + + The union's value as a floating point variable + + + The union's value as an integer + + + The union's value as an unsigned integer + + + Union of a double precision floating point variable and a long + + + The union's value as a double precision floating point variable + + + The union's value as a long + + + The union's value as an unsigned long + + + + Tests whether a value is greater than the value supplied to its constructor + + + + + The value against which a comparison is to be made + + + + + Initializes a new instance of the class. + + The expected value. + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Tests whether a value is greater than or equal to the value supplied to its constructor + + + + + The value against which a comparison is to be made + + + + + Initializes a new instance of the class. + + The expected value. + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + InstanceOfTypeConstraint is used to test that an object + is of the same type provided or derived from it. + + + + + Construct an InstanceOfTypeConstraint for the type provided + + The expected Type + + + + Test whether an object is of the specified type or a derived type + + The object to be tested + True if the object is of the provided type or derives from it, otherwise false. + + + + Write a description of this constraint to a MessageWriter + + The MessageWriter to use + + + + Tests whether a value is less than the value supplied to its constructor + + + + + The value against which a comparison is to be made + + + + + Initializes a new instance of the class. + + The expected value. + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Tests whether a value is less than or equal to the value supplied to its constructor + + + + + The value against which a comparison is to be made + + + + + Initializes a new instance of the class. + + The expected value. + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Static methods used in creating messages + + + + + Static string used when strings are clipped + + + + + Returns the representation of a type as used in NUnitLite. + This is the same as Type.ToString() except for arrays, + which are displayed with their declared sizes. + + + + + + + Converts any control characters in a string + to their escaped representation. + + The string to be converted + The converted string + + + + Return the a string representation for a set of indices into an array + + Array of indices for which a string is needed + + + + Get an array of indices representing the point in a enumerable, + collection or array corresponding to a single int index into the + collection. + + The collection to which the indices apply + Index in the collection + Array of indices + + + + Clip a string to a given length, starting at a particular offset, returning the clipped + string with ellipses representing the removed parts + + The string to be clipped + The maximum permitted length of the result string + The point at which to start clipping + The clipped string + + + + Clip the expected and actual strings in a coordinated fashion, + so that they may be displayed together. + + + + + + + + + Shows the position two strings start to differ. Comparison + starts at the start index. + + The expected string + The actual string + The index in the strings at which comparison should start + Boolean indicating whether case should be ignored + -1 if no mismatch found, or the index where mismatch found + + + + NaNConstraint tests that the actual value is a double or float NaN + + + + + Test that the actual value is an NaN + + + + + + + Write the constraint description to a specified writer + + + + + + NoItemConstraint applies another constraint to each + item in a collection, failing if any of them succeeds. + + + + + Construct a NoItemConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + failing if any item fails. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + NotConstraint negates the effect of some other constraint + + + + + Initializes a new instance of the class. + + The base constraint to be negated. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for if the base constraint fails, false if it succeeds + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a MessageWriter. + + The writer on which the actual value is displayed + + + + NullConstraint tests that the actual value is null + + + + + Initializes a new instance of the class. + + + + + NullEmptyStringConstraint tests whether a string is either null or empty. + + + + + Constructs a new NullOrEmptyStringConstraint + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + The Numerics class contains common operations on numeric values. + + + + + Checks the type of the object, returning true if + the object is a numeric type. + + The object to check + true if the object is a numeric type + + + + Checks the type of the object, returning true if + the object is a floating point numeric type. + + The object to check + true if the object is a floating point numeric type + + + + Checks the type of the object, returning true if + the object is a fixed point numeric type. + + The object to check + true if the object is a fixed point numeric type + + + + Test two numeric values for equality, performing the usual numeric + conversions and using a provided or default tolerance. If the tolerance + provided is Empty, this method may set it to a default tolerance. + + The expected value + The actual value + A reference to the tolerance in effect + True if the values are equal + + + + Compare two numeric values, performing the usual numeric conversions. + + The expected value + The actual value + The relationship of the values to each other + + + + NUnitComparer encapsulates NUnit's default behavior + in comparing two objects. + + + + + Compares two objects + + + + + + + + Returns the default NUnitComparer. + + + + + Generic version of NUnitComparer + + + + + + Compare two objects of the same type + + + + + NUnitEqualityComparer encapsulates NUnit's handling of + equality tests between objects. + + + + + + + + + + Compares two objects for equality within a tolerance + + The first object to compare + The second object to compare + The tolerance to use in the comparison + + + + + If true, all string comparisons will ignore case + + + + + If true, arrays will be treated as collections, allowing + those of different dimensions to be compared + + + + + Comparison objects used in comparisons for some constraints. + + + + + List of points at which a failure occured. + + + + + RecursionDetector used to check for recursion when + evaluating self-referencing enumerables. + + + + + Compares two objects for equality within a tolerance, setting + the tolerance to the actual tolerance used if an empty + tolerance is supplied. + + + + + Helper method to compare two arrays + + + + + Method to compare two DirectoryInfo objects + + first directory to compare + second directory to compare + true if equivalent, false if not + + + + Returns the default NUnitEqualityComparer + + + + + Gets and sets a flag indicating whether case should + be ignored in determining equality. + + + + + Gets and sets a flag indicating that arrays should be + compared as collections, without regard to their shape. + + + + + Gets the list of external comparers to be used to + test for equality. They are applied to members of + collections, in place of NUnit's own logic. + + + + + Gets the list of failure points for the last Match performed. + The list consists of objects to be interpreted by the caller. + This generally means that the caller may only make use of + objects it has placed on the list at a particular depthy. + + + + + RecursionDetector detects when a comparison + between two enumerables has reached a point + where the same objects that were previously + compared are again being compared. This allows + the caller to stop the comparison if desired. + + + + + Check whether two objects have previously + been compared, returning true if they have. + The two objects are remembered, so that a + second call will always return true. + + + + + OrConstraint succeeds if either member succeeds + + + + + Create an OrConstraint from two other constraints + + The first constraint + The second constraint + + + + Apply the member constraints to an actual value, succeeding + succeeding as soon as one of them succeeds. + + The actual value + True if either constraint succeeded + + + + Write a description for this contraint to a MessageWriter + + The MessageWriter to receive the description + + + + PathConstraint serves as the abstract base of constraints + that operate on paths and provides several helper methods. + + + + + The expected path used in the constraint + + + + + Flag indicating whether a caseInsensitive comparison should be made + + + + + Construct a PathConstraint for a give expected path + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Returns true if the expected path and actual path match + + + + + Returns the string representation of this constraint + + + + + Transform the provided path to its canonical form so that it + may be more easily be compared with other paths. + + The original path + The path in canonical form + + + + Test whether one path in canonical form is under another. + + The first path - supposed to be the parent path + The second path - supposed to be the child path + Indicates whether case should be ignored + + + + + Modifies the current instance to be case-insensitve + and returns it. + + + + + Modifies the current instance to be case-sensitve + and returns it. + + + + + Predicate constraint wraps a Predicate in a constraint, + returning success if the predicate is true. + + + + + Construct a PredicateConstraint from a predicate + + + + + Determines whether the predicate succeeds when applied + to the actual value. + + + + + Writes the description to a MessageWriter + + + + + PropertyConstraint extracts a named property and uses + its value as the actual value for a chained constraint. + + + + + Initializes a new instance of the class. + + The name. + The constraint to apply to the property. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Returns the string representation of the constraint. + + + + + + PropertyExistsConstraint tests that a named property + exists on the object provided through Match. + + Originally, PropertyConstraint provided this feature + in addition to making optional tests on the vaue + of the property. The two constraints are now separate. + + + + + Initializes a new instance of the class. + + The name of the property. + + + + Test whether the property exists for a given object + + The object to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. + + The writer on which the actual value is displayed + + + + Returns the string representation of the constraint. + + + + + + RangeConstraint tests whether two values are within a + specified range. + + + + + Initializes a new instance of the class. + + From. + To. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + RegexConstraint can test whether a string matches + the pattern provided. + + + + + Initializes a new instance of the class. + + The pattern. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + ResolvableConstraintExpression is used to represent a compound + constraint being constructed at a point where the last operator + may either terminate the expression or may have additional + qualifying constraints added to it. + + It is used, for example, for a Property element or for + an Exception element, either of which may be optionally + followed by constraints that apply to the property or + exception. + + + + + Create a new instance of ResolvableConstraintExpression + + + + + Create a new instance of ResolvableConstraintExpression, + passing in a pre-populated ConstraintBuilder. + + + + + Resolve the current expression to a Constraint + + + + + This operator creates a constraint that is satisfied only if both + argument constraints are satisfied. + + + + + This operator creates a constraint that is satisfied only if both + argument constraints are satisfied. + + + + + This operator creates a constraint that is satisfied only if both + argument constraints are satisfied. + + + + + This operator creates a constraint that is satisfied if either + of the argument constraints is satisfied. + + + + + This operator creates a constraint that is satisfied if either + of the argument constraints is satisfied. + + + + + This operator creates a constraint that is satisfied if either + of the argument constraints is satisfied. + + + + + This operator creates a constraint that is satisfied if the + argument constraint is not satisfied. + + + + + Appends an And Operator to the expression + + + + + Appends an Or operator to the expression. + + + + + ReusableConstraint wraps a constraint expression after + resolving it so that it can be reused consistently. + + + + + Construct a ReusableConstraint from a constraint expression + + The expression to be resolved and reused + + + + Converts a constraint to a ReusableConstraint + + The constraint to be converted + A ReusableConstraint + + + + Returns the string representation of the constraint. + + A string representing the constraint + + + + Resolves the ReusableConstraint by returning the constraint + that it originally wrapped. + + A resolved constraint + + + + SameAsConstraint tests whether an object is identical to + the object passed to its constructor + + + + + Initializes a new instance of the class. + + The expected object. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Summary description for SamePathConstraint. + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The expected path + The actual path + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + SamePathOrUnderConstraint tests that one path is under another + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The expected path + The actual path + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + SomeItemsConstraint applies another constraint to each + item in a collection, succeeding if any of them succeeds. + + + + + Construct a SomeItemsConstraint on top of an existing constraint + + + + + + Apply the item constraint to each item in the collection, + succeeding if any item succeeds. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + StartsWithConstraint can test whether a string starts + with an expected substring. + + + + + Initializes a new instance of the class. + + The expected string + + + + Test whether the constraint is matched by the actual value. + This is a template method, which calls the IsMatch method + of the derived class. + + + + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + SubPathConstraint tests that the actual path is under the expected path + + + + + Initializes a new instance of the class. + + The expected path + + + + Test whether the constraint is satisfied by a given value + + The expected path + The actual path + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + SubstringConstraint can test whether a string contains + the expected substring. + + + + + Initializes a new instance of the class. + + The expected. + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + ThrowsConstraint is used to test the exception thrown by + a delegate by applying a constraint to it. + + + + + Initializes a new instance of the class, + using a constraint to be applied to the exception. + + A constraint to apply to the caught exception. + + + + Executes the code of the delegate and captures any exception. + If a non-null base constraint was provided, it applies that + constraint to the exception. + + A delegate representing the code to be tested + True if an exception is thrown and the constraint succeeds, otherwise false + + + + Converts an ActualValueDelegate to a TestDelegate + before calling the primary overload. + + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Returns the string representation of this constraint + + + + + Get the actual exception thrown - used by Assert.Throws. + + + + + ThrowsNothingConstraint tests that a delegate does not + throw an exception. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True if no exception is thrown, otherwise false + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. Overridden in ThrowsNothingConstraint to write + information about the exception that was actually caught. + + The writer on which the actual value is displayed + + + + The Tolerance class generalizes the notion of a tolerance + within which an equality test succeeds. Normally, it is + used with numeric types, but it can be used with any + type that supports taking a difference between two + objects and comparing that difference to a value. + + + + + Constructs a linear tolerance of a specdified amount + + + + + Constructs a tolerance given an amount and ToleranceMode + + + + + Tests that the current Tolerance is linear with a + numeric value, throwing an exception if it is not. + + + + + Returns an empty Tolerance object, equivalent to + specifying no tolerance. In most cases, it results + in an exact match but for floats and doubles a + default tolerance may be used. + + + + + Returns a zero Tolerance object, equivalent to + specifying an exact match. + + + + + Gets the ToleranceMode for the current Tolerance + + + + + Gets the value of the current Tolerance instance. + + + + + Returns a new tolerance, using the current amount as a percentage. + + + + + Returns a new tolerance, using the current amount in Ulps. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of days. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of hours. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of minutes. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of seconds. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of milliseconds. + + + + + Returns a new tolerance with a TimeSpan as the amount, using + the current amount as a number of clock ticks. + + + + + Returns true if the current tolerance is empty. + + + + + Modes in which the tolerance value for a comparison can be interpreted. + + + + + The tolerance was created with a value, without specifying + how the value would be used. This is used to prevent setting + the mode more than once and is generally changed to Linear + upon execution of the test. + + + + + The tolerance is used as a numeric range within which + two compared values are considered to be equal. + + + + + Interprets the tolerance as the percentage by which + the two compared values my deviate from each other. + + + + + Compares two values based in their distance in + representable numbers. + + + + + TrueConstraint tests that the actual value is true + + + + + Initializes a new instance of the class. + + + + + UniqueItemsConstraint tests whether all the items in a + collection are unique. + + + + + Check that all items are unique. + + + + + + + Write a description of this constraint to a MessageWriter + + + + + + XmlSerializableConstraint tests whether + an object is serializable in XML format. + + + + + Test whether the constraint is satisfied by a given value + + The value to be tested + True for success, false for failure + + + + Write the constraint description to a MessageWriter + + The writer on which the description is displayed + + + + Write the actual value for a failing constraint test to a + MessageWriter. The default implementation simply writes + the raw value of actual, leaving it to the writer to + perform any formatting. + + The writer on which the actual value is displayed + + + + Returns the string representation of this constraint + + + + + Represents a constraint that succeeds if all the + members of a collection match a base constraint. + + + + + Abstract base for operators that indicate how to + apply a constraint to items in a collection. + + + + + PrefixOperator takes a single constraint and modifies + it's action in some way. + + + + + The ConstraintOperator class is used internally by a + ConstraintBuilder to represent an operator that + modifies or combines constraints. + + Constraint operators use left and right precedence + values to determine whether the top operator on the + stack should be reduced before pushing a new operator. + + + + + The precedence value used when the operator + is about to be pushed to the stack. + + + + + The precedence value used when the operator + is on the top of the stack. + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + The syntax element preceding this operator + + + + + The syntax element folowing this operator + + + + + The precedence value used when the operator + is about to be pushed to the stack. + + + + + The precedence value used when the operator + is on the top of the stack. + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Returns the constraint created by applying this + prefix to another constraint. + + + + + + + Constructs a CollectionOperator + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + they all succeed. + + + + + Operator that requires both it's arguments to succeed + + + + + Abstract base class for all binary operators + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Abstract method that produces a constraint by applying + the operator to its left and right constraint arguments. + + + + + Gets the left precedence of the operator + + + + + Gets the right precedence of the operator + + + + + Construct an AndOperator + + + + + Apply the operator to produce an AndConstraint + + + + + Operator that tests for the presence of a particular attribute + on a type and optionally applies further tests to the attribute. + + + + + Abstract base class for operators that are able to reduce to a + constraint whether or not another syntactic element follows. + + + + + Construct an AttributeOperator for a particular Type + + The Type of attribute tested + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + Represents a constraint that succeeds if the specified + count of members of a collection match a base constraint. + + + + + Construct an ExactCountOperator for a specified count + + The expected count + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + none of them succeed. + + + + + Represents a constraint that succeeds if none of the + members of a collection match a base constraint. + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + none of them succeed. + + + + + Negates the test of the constraint it wraps. + + + + + Constructs a new NotOperator + + + + + Returns a NotConstraint applied to its argument. + + + + + Operator that requires at least one of it's arguments to succeed + + + + + Construct an OrOperator + + + + + Apply the operator to produce an OrConstraint + + + + + Operator used to test for the presence of a named Property + on an object and optionally apply further tests to the + value of that property. + + + + + Constructs a PropOperator for a particular named property + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + + Gets the name of the property to which the operator applies + + + + + Represents a constraint that succeeds if any of the + members of a collection match a base constraint. + + + + + Returns a constraint that will apply the argument + to the members of a collection, succeeding if + any of them succeed. + + + + + Operator that tests that an exception is thrown and + optionally applies further tests to the exception. + + + + + Construct a ThrowsOperator + + + + + Reduce produces a constraint from the operator and + any arguments. It takes the arguments from the constraint + stack and pushes the resulting constraint on it. + + + + + Represents a constraint that simply wraps the + constraint provided as an argument, without any + further functionality, but which modifes the + order of evaluation because of its precedence. + + + + + Constructor for the WithOperator + + + + + Returns a constraint that wraps its argument + + + + + Thrown when an assertion failed. + + + + The error message that explains + the reason for the exception + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Thrown when an assertion failed. + + + + + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Thrown when a test executes inconclusively. + + + + The error message that explains + the reason for the exception + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + Thrown when an assertion failed. + + + + + + + The error message that explains + the reason for the exception + The exception that caused the + current exception + + + + Serialization Constructor + + + + + + + + + + + Compares two objects of a given Type for equality within a tolerance + + The first object to compare + The second object to compare + The tolerance to use in the comparison + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/license.txt b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/license.txt new file mode 100644 index 00000000000..b12903afb5e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages/NUnit.2.6.3/license.txt @@ -0,0 +1,15 @@ +Copyright © 2002-2013 Charlie Poole +Copyright © 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov +Copyright © 2000-2002 Philip A. Craig + +This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment (see the following) in the product documentation is required. + +Portions Copyright © 2002-2013 Charlie Poole or Copyright © 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov or Copyright © 2000-2002 Philip A. Craig + +2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config b/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config new file mode 100644 index 00000000000..ba8d0d576a8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 0adcbe7031d..a95f5f7a960 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -420,10 +420,10 @@ public class ApiClient { throw new ApiException(500, "unknown method type " + method); } - if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } - else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { + else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if(response.hasEntity()) { return (String) response.getEntity(String.class); } @@ -444,7 +444,7 @@ public class ApiClient { } } throw new ApiException( - response.getClientResponseStatus().getStatusCode(), + response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index c102cf00b51..bc793fd41ee 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -322,7 +322,7 @@ public class PetApi { } try { - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); if(response != null){ return (Pet) apiClient.deserialize(response, "", Pet.class); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index ddd0e1038c0..cf7ace02309 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index f4f6ea8538a..b6766d8d13f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class PetApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class PetApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return PetApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -68,6 +68,7 @@ class PetApi { * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePet($body) { @@ -80,11 +81,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); @@ -103,14 +104,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -121,6 +129,7 @@ class PetApi { * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPet($body) { @@ -133,11 +142,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); @@ -156,14 +165,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -174,6 +190,7 @@ class PetApi { * * @param string[] $status Status values that need to be considered for filter (required) * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status) { @@ -186,15 +203,15 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($status !== null) { - $queryParams['status'] = $this->apiClient->toQueryValue($status); + $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); } @@ -208,20 +225,33 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet[]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); return $responseObject; + } /** @@ -231,6 +261,7 @@ class PetApi { * * @param string[] $tags Tags to filter by (required) * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTags($tags) { @@ -243,15 +274,15 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($tags !== null) { - $queryParams['tags'] = $this->apiClient->toQueryValue($tags); + $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); } @@ -265,20 +296,33 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet[]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); return $responseObject; + } /** @@ -288,6 +332,7 @@ class PetApi { * * @param int $pet_id ID of pet that needs to be fetched (required) * @return \Swagger\Client\Model\Pet + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { @@ -305,18 +350,19 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } @@ -328,20 +374,40 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } + + //TODO support oauth + - // authentication setting, if any - $authSettings = array('api_key', 'petstore_auth'); - + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet'); return $responseObject; + } /** @@ -353,6 +419,7 @@ class PetApi { * @param string $name Updated name of the pet (required) * @param string $status Updated status of the pet (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name, $status) { @@ -370,25 +437,26 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/x-www-form-urlencoded')); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } // form params if ($name !== null) { - $formParams['name'] = $this->apiClient->toFormValue($name); + $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); }// form params if ($status !== null) { - $formParams['status'] = $this->apiClient->toFormValue($status); + $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } @@ -399,14 +467,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -418,6 +493,7 @@ class PetApi { * @param string $api_key (required) * @param int $pet_id Pet id to delete (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($api_key, $pet_id) { @@ -435,21 +511,22 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // header params if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); + $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); } // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } @@ -461,14 +538,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -481,6 +565,7 @@ class PetApi { * @param string $additional_metadata Additional data to pass to server (required) * @param string $file file to upload (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata, $file) { @@ -498,25 +583,26 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('multipart/form-data')); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } // form params if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata); + $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); }// form params if ($file !== null) { - $formParams['file'] = '@' . $this->apiClient->toFormValue($file); + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } @@ -527,16 +613,22 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 07a922aab0a..237ba3f1acf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class StoreApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class StoreApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return StoreApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -67,6 +67,7 @@ class StoreApi { * Returns pet inventories by status * * @return map[string,int] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { @@ -79,11 +80,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -98,20 +99,37 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('api_key'); - + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'map[string,int]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'map[string,int]'); return $responseObject; + } /** @@ -121,6 +139,7 @@ class StoreApi { * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrder($body) { @@ -133,11 +152,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -156,20 +175,30 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Order'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); return $responseObject; + } /** @@ -179,6 +208,7 @@ class StoreApi { * * @param string $order_id ID of pet that needs to be fetched (required) * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { @@ -196,18 +226,19 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($order_id !== null) { $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); } @@ -219,20 +250,30 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Order'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); return $responseObject; + } /** @@ -242,6 +283,7 @@ class StoreApi { * * @param string $order_id ID of the order that needs to be deleted (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { @@ -259,18 +301,19 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($order_id !== null) { $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); } @@ -282,16 +325,19 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index f4d35a3a7a0..1d0765bbb81 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class UserApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class UserApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return UserApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -68,6 +68,7 @@ class UserApi { * * @param \Swagger\Client\Model\User $body Created user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUser($body) { @@ -80,11 +81,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -103,14 +104,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -121,6 +126,7 @@ class UserApi { * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInput($body) { @@ -133,11 +139,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -156,14 +162,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -174,6 +184,7 @@ class UserApi { * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInput($body) { @@ -186,11 +197,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -209,14 +220,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -228,6 +243,7 @@ class UserApi { * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) * @return string + * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUser($username, $password) { @@ -240,18 +256,18 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($username !== null) { - $queryParams['username'] = $this->apiClient->toQueryValue($username); + $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); }// query params if($password !== null) { - $queryParams['password'] = $this->apiClient->toQueryValue($password); + $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); } @@ -265,20 +281,30 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'string'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'string'); return $responseObject; + } /** @@ -287,6 +313,7 @@ class UserApi { * Logs out current logged in user session * * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { @@ -299,11 +326,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -318,14 +345,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -336,6 +367,7 @@ class UserApi { * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @return \Swagger\Client\Model\User + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { @@ -353,18 +385,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } @@ -376,20 +409,30 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\User'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\User'); return $responseObject; + } /** @@ -400,6 +443,7 @@ class UserApi { * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { @@ -417,18 +461,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } // body params @@ -444,14 +489,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -462,6 +511,7 @@ class UserApi { * * @param string $username The name that needs to be deleted (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { @@ -479,18 +529,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } @@ -502,16 +553,19 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index bb5229fb170..66204f0c4f3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -25,146 +25,60 @@ class ApiClient { public static $PUT = "PUT"; public static $DELETE = "DELETE"; - /** @var string[] Array of default headers where the key is the header name and the value is the header value */ - private $default_header = array(); + /** @var Configuration */ + protected $config; - /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curl_timeout = 0; - - /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $user_agent = "PHP-Swagger"; + /** @var ObjectSerializer */ + protected $serializer; /** - * @param string $host Base url of the API server (optional) + * @param Configuration $config config for this ApiClient */ - function __construct($host = null) { - if ($host === null) { - $this->host = 'http://petstore.swagger.io/v2'; - } else { - $this->host = $host; + function __construct(Configuration $config = null) { + if ($config == null) { + $config = Configuration::getDefaultConfiguration(); } + + $this->config = $config; + $this->serializer = new ObjectSerializer(); } /** - * add default header - * - * @param string $header_name header name (e.g. Token) - * @param string $header_value header value (e.g. 1z8wp3) + * get the config + * @return Configuration */ - public function addDefaultHeader($header_name, $header_value) { - if (!is_string($header_name)) - throw new \InvalidArgumentException('Header name must be a string.'); - - $this->default_header[$header_name] = $header_value; + public function getConfig() { + return $this->config; } /** - * get the default header - * - * @return array default header + * get the serializer + * @return ObjectSerializer */ - public function getDefaultHeader() { - return $this->default_header; + public function getSerializer() { + return $this->serializer; } - /** - * delete the default header based on header name - * - * @param string $header_name header name (e.g. Token) - */ - public function deleteDefaultHeader($header_name) { - unset($this->default_header[$header_name]); - } - - /** - * set the user agent of the api client - * - * @param string $user_agent the user agent of the api client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) - throw new \InvalidArgumentException('User-agent must be a string.'); - - $this->user_agent= $user_agent; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - - $this->curl_timeout = $seconds; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } - - /** * Get API key (with prefix if set) - * @param string key name + * @param string $apiKey name of apikey * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; + $prefix = $this->config->getApiKeyPrefix($apiKey); + $apiKey = $this->config->getApiKey($apiKey); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; } else { - return; + $keyWithPrefix = $apiKey; } - } - /** - * update hearder and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; - - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - - case 'api_key': - $headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key'); - - break; - - case 'petstore_auth': - - //TODO support oauth - break; - - default: - //TODO show warning about security definition not found - } - } + return $keyWithPrefix; } /** @@ -173,18 +87,15 @@ class ApiClient { * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header + * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { $headers = array(); - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # construct the http header - $headerParams = array_merge((array)$this->default_header, (array)$headerParams); + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -195,15 +106,15 @@ class ApiClient { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); + $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - $url = $this->host . $resourcePath; + $url = $this->config->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -232,14 +143,14 @@ class ApiClient { curl_setopt($curl, CURLOPT_URL, $url); // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } @@ -255,8 +166,8 @@ class ApiClient { $response_info = curl_getinfo($curl); // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } // Handle the response @@ -274,153 +185,13 @@ class ApiClient { return $data; } - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public function toPathValue($value) { - return rawurlencode($this->toString($value)); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $this->toString($object); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public function toHeaderValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public function toFormValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = $this->deserialize($value, $subClass); - } - } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { - $subClass = substr($class, 0, -2); - $values = array(); - foreach ($data as $key => $value) { - $values[] = $this->deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = $this->deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - /* * return the header 'Accept' based on an array of Accept provided * - * @param array[string] $accept Array of header + * @param string[] $accept Array of header * @return string Accept (e.g. application/json) */ - public function selectHeaderAccept($accept) { + public static function selectHeaderAccept($accept) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return NULL; } elseif (preg_grep("/application\/json/i", $accept)) { @@ -433,10 +204,10 @@ class ApiClient { /* * return the content type based on an array of content-type provided * - * @param array[string] content_type_array Array fo content-type + * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ - public function selectHeaderContentType($content_type) { + public static function selectHeaderContentType($content_type) { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; } elseif (preg_grep("/application\/json/i", $content_type)) { @@ -445,6 +216,4 @@ class ApiClient { return implode(',', $content_type); } } - } - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 5f3b1812261..51774137aed 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -22,15 +22,20 @@ use \Exception; class ApiException extends Exception { /** @var string The HTTP body of the server response. */ - protected $response_body; + protected $responseBody; /** @var string[] The HTTP header of the server response. */ - protected $response_headers; + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_headers = $responseHeaders; - $this->response_body = $responseBody; + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; } /** @@ -39,7 +44,7 @@ class ApiException extends Exception { * @return string HTTP response header */ public function getResponseHeaders() { - return $this->response_headers; + return $this->responseHeaders; } /** @@ -48,7 +53,18 @@ class ApiException extends Exception { * @return string HTTP response body */ public function getResponseBody() { - return $this->response_body; + return $this->responseBody; } + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index e6381781bb0..a407fe4dd49 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -17,37 +17,250 @@ namespace Swagger\Client; -use \Swagger\Client\ApiClient; - class Configuration { + private static $defaultConfiguration = null; + /** @var string[] Associate array to store API key(s) */ - public static $apiKey = array(); + protected $apiKeys = array(); /** string[] Associate array to store API prefix (e.g. Bearer) */ - public static $apiKeyPrefix = array(); + protected $apiKeyPrefixes = array(); /** @var string Username for HTTP basic authentication */ - public static $username = ''; + protected $username = ''; /** @var string Password for HTTP basic authentication */ - public static $password = ''; + protected $password = ''; /** @var \Swagger\Client\ApiClient The default instance of ApiClient */ - public static $apiClient; + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; /** @var bool Debug switch (default set to false) */ - public static $debug = false; + protected $debug = false; /** @var string Debug file location (log to STDOUT by default) */ - public static $debug_file = 'php://output'; + protected $debugFile = 'php://output'; - /* - * manually initalize ApiClient + /** + * @param string $key + * @param string $value + * @return Configuration */ - public static function init() { - if (self::$apiClient === null) - self::$apiClient = new ApiClient(); + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; } + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + public function setCurlTimeout($seconds) { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + } + + $this->curlTimeout = $seconds; + return $this; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; + } + + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 750a8fee5df..75aaf2eeead 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -38,21 +38,69 @@ class Category implements ArrayAccess { 'id' => 'id', 'name' => 'name' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $name */ - public $name; + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->name = @$data["name"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 64552afb763..c7a433c3d8c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -46,37 +46,165 @@ class Order implements ArrayAccess { 'status' => 'status', 'complete' => 'complete' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'pet_id' => 'setPetId', + 'quantity' => 'setQuantity', + 'ship_date' => 'setShipDate', + 'status' => 'setStatus', + 'complete' => 'setComplete' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'pet_id' => 'getPetId', + 'quantity' => 'getQuantity', + 'ship_date' => 'getShipDate', + 'status' => 'getStatus', + 'complete' => 'getComplete' + ); + /** @var int $id */ - public $id; + protected $id; /** @var int $pet_id */ - public $pet_id; + protected $pet_id; /** @var int $quantity */ - public $quantity; + protected $quantity; /** @var \DateTime $ship_date */ - public $ship_date; + protected $ship_date; /** @var string $status Order Status */ - public $status; + protected $status; /** @var bool $complete */ - public $complete; + protected $complete; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->pet_id = $data["pet_id"]; + $this->quantity = $data["quantity"]; + $this->ship_date = $data["ship_date"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->pet_id = @$data["pet_id"]; - $this->quantity = @$data["quantity"]; - $this->ship_date = @$data["ship_date"]; - $this->status = @$data["status"]; - $this->complete = @$data["complete"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get pet_id + * @return int + */ + public function getPetId() { + return $this->pet_id; + } + + /** + * set pet_id + * @param int $pet_id + * @return $this + */ + public function setPetId($pet_id) { + $this->pet_id = $pet_id; + return $this; + } + + /** + * get quantity + * @return int + */ + public function getQuantity() { + return $this->quantity; + } + + /** + * set quantity + * @param int $quantity + * @return $this + */ + public function setQuantity($quantity) { + $this->quantity = $quantity; + return $this; + } + + /** + * get ship_date + * @return \DateTime + */ + public function getShipDate() { + return $this->ship_date; + } + + /** + * set ship_date + * @param \DateTime $ship_date + * @return $this + */ + public function setShipDate($ship_date) { + $this->ship_date = $ship_date; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + + /** + * get complete + * @return bool + */ + public function getComplete() { + return $this->complete; + } + + /** + * set complete + * @param bool $complete + * @return $this + */ + public function setComplete($complete) { + $this->complete = $complete; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index ef2a4c76a0d..cbe27e1fce9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -46,37 +46,165 @@ class Pet implements ArrayAccess { 'tags' => 'tags', 'status' => 'status' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'category' => 'setCategory', + 'name' => 'setName', + 'photo_urls' => 'setPhotoUrls', + 'tags' => 'setTags', + 'status' => 'setStatus' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'category' => 'getCategory', + 'name' => 'getName', + 'photo_urls' => 'getPhotoUrls', + 'tags' => 'getTags', + 'status' => 'getStatus' + ); + /** @var int $id */ - public $id; + protected $id; /** @var \Swagger\Client\Model\Category $category */ - public $category; + protected $category; /** @var string $name */ - public $name; + protected $name; /** @var string[] $photo_urls */ - public $photo_urls; + protected $photo_urls; /** @var \Swagger\Client\Model\Tag[] $tags */ - public $tags; + protected $tags; /** @var string $status pet status in the store */ - public $status; + protected $status; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photo_urls = $data["photo_urls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->category = @$data["category"]; - $this->name = @$data["name"]; - $this->photo_urls = @$data["photo_urls"]; - $this->tags = @$data["tags"]; - $this->status = @$data["status"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get category + * @return \Swagger\Client\Model\Category + */ + public function getCategory() { + return $this->category; + } + + /** + * set category + * @param \Swagger\Client\Model\Category $category + * @return $this + */ + public function setCategory($category) { + $this->category = $category; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + + /** + * get photo_urls + * @return string[] + */ + public function getPhotoUrls() { + return $this->photo_urls; + } + + /** + * set photo_urls + * @param string[] $photo_urls + * @return $this + */ + public function setPhotoUrls($photo_urls) { + $this->photo_urls = $photo_urls; + return $this; + } + + /** + * get tags + * @return \Swagger\Client\Model\Tag[] + */ + public function getTags() { + return $this->tags; + } + + /** + * set tags + * @param \Swagger\Client\Model\Tag[] $tags + * @return $this + */ + public function setTags($tags) { + $this->tags = $tags; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 5959cb20a6a..3fd785f001b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -38,21 +38,69 @@ class Tag implements ArrayAccess { 'id' => 'id', 'name' => 'name' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $name */ - public $name; + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->name = @$data["name"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 1bfb7f332db..2bb31056bde 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -50,45 +50,213 @@ class User implements ArrayAccess { 'phone' => 'phone', 'user_status' => 'userStatus' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'username' => 'setUsername', + 'first_name' => 'setFirstName', + 'last_name' => 'setLastName', + 'email' => 'setEmail', + 'password' => 'setPassword', + 'phone' => 'setPhone', + 'user_status' => 'setUserStatus' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'username' => 'getUsername', + 'first_name' => 'getFirstName', + 'last_name' => 'getLastName', + 'email' => 'getEmail', + 'password' => 'getPassword', + 'phone' => 'getPhone', + 'user_status' => 'getUserStatus' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $username */ - public $username; + protected $username; /** @var string $first_name */ - public $first_name; + protected $first_name; /** @var string $last_name */ - public $last_name; + protected $last_name; /** @var string $email */ - public $email; + protected $email; /** @var string $password */ - public $password; + protected $password; /** @var string $phone */ - public $phone; + protected $phone; /** @var int $user_status User Status */ - public $user_status; + protected $user_status; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->first_name = $data["first_name"]; + $this->last_name = $data["last_name"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->user_status = $data["user_status"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->username = @$data["username"]; - $this->first_name = @$data["first_name"]; - $this->last_name = @$data["last_name"]; - $this->email = @$data["email"]; - $this->password = @$data["password"]; - $this->phone = @$data["phone"]; - $this->user_status = @$data["user_status"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get username + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * set username + * @param string $username + * @return $this + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * get first_name + * @return string + */ + public function getFirstName() { + return $this->first_name; + } + + /** + * set first_name + * @param string $first_name + * @return $this + */ + public function setFirstName($first_name) { + $this->first_name = $first_name; + return $this; + } + + /** + * get last_name + * @return string + */ + public function getLastName() { + return $this->last_name; + } + + /** + * set last_name + * @param string $last_name + * @return $this + */ + public function setLastName($last_name) { + $this->last_name = $last_name; + return $this; + } + + /** + * get email + * @return string + */ + public function getEmail() { + return $this->email; + } + + /** + * set email + * @param string $email + * @return $this + */ + public function setEmail($email) { + $this->email = $email; + return $this; + } + + /** + * get password + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * set password + * @param string $password + * @return $this + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * get phone + * @return string + */ + public function getPhone() { + return $this->phone; + } + + /** + * set phone + * @param string $phone + * @return $this + */ + public function setPhone($phone) { + $this->phone = $phone; + return $this; + } + + /** + * get user_status + * @return int + */ + public function getUserStatus() { + return $this->user_status; + } + + /** + * set user_status + * @param int $user_status + * @return $this + */ + public function setUserStatus($user_status) { + $this->user_status = $user_status; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php new file mode 100644 index 00000000000..802a49bc01a --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -0,0 +1,151 @@ +format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public function toPathValue($value) { + return rawurlencode($this->toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return $this->toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value a string which will be part of the header + * @return string the header string + */ + public function toHeaderValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the form parameter + * @return string the form string + */ + public function toFormValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the parameter + * @return string the header string + */ + public function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + public function deserialize($data, $class) { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = $this->deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); + $values = array(); + foreach ($data as $key => $value) { + $values[] = $this->deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter($this->deserialize($propertyValue, $type)); + } + } + $deserialized = $instance; + } + + return $deserialized; + } +} \ No newline at end of file diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 131a79dba92..3ac28772291 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -22,19 +22,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // new pet $new_pet_id = 10005; $new_pet = new Swagger\Client\Model\Pet; - $new_pet->id = $new_pet_id; - $new_pet->name = "PHP Unit Test"; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); // new tag $tag= new Swagger\Client\Model\Tag; - $tag->id = $new_pet_id; // use the same id as pet - $tag->name = "test php tag"; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); // new category $category = new Swagger\Client\Model\Category; - $category->id = $new_pet_id; // use the same id as pet - $category->name = "test php category"; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); - $new_pet->tags = array($tag); - $new_pet->category = $category; + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); $pet_api = new Swagger\Client\Api\PetAPI(); // add a new pet (model) @@ -56,65 +56,53 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); // test addDefaultHeader and getDefaultHeader - $api_client->addDefaultHeader('test1', 'value1'); - $api_client->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->getDefaultHeader(); + $api_client->getConfig()->addDefaultHeader('test1', 'value1'); + $api_client->getConfig()->addDefaultHeader('test2', 200); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertSame('value1', $defaultHeader['test1']); $this->assertSame(200, $defaultHeader['test2']); // test deleteDefaultHeader - $api_client->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getDefaultHeader(); + $api_client->getConfig()->deleteDefaultHeader('test2'); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api = new Swagger\Client\Api\PetAPI(); $pet_api2 = new Swagger\Client\Api\PetAPI(); $apiClient3 = new Swagger\Client\ApiClient(); - $apiClient3->setUserAgent = 'api client 3'; + $apiClient3->getConfig()->setUserAgent('api client 3'); $apiClient4 = new Swagger\Client\ApiClient(); - $apiClient4->setUserAgent = 'api client 4'; + $apiClient4->getConfig()->setUserAgent('api client 4'); $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); - // same default api client - $this->assertSame($pet_api->getApiClient(), $pet_api2->getApiClient()); - // confirm using the default api client in the Configuration - $this->assertSame($pet_api->getApiClient(), Swagger\Client\Configuration::$apiClient); // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); - // customized pet api not using the default (configuration) api client - $this->assertNotEquals($pet_api3->getApiClient(), Swagger\Client\Configuration::$apiClient); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // both pet api and pet api2 share the same api client and confirm using timeout value - $pet_api->getApiClient()->setTimeout(999); - $this->assertSame(999, $pet_api2->getApiClient()->getTimeout()); - } // test getPetById with a Pet object (id 10005) public function testGetPetById() { // initialize the API client without host - $api_client = new Swagger\Client\ApiClient(); - Swagger\Client\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->name, 'PHP Unit Test'); - $this->assertSame($response->category->id, $pet_id); - $this->assertSame($response->category->name, 'test php category'); - $this->assertSame($response->tags[0]->id, $pet_id); - $this->assertSame($response->tags[0]->name, 'test php tag'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); } // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); @@ -133,30 +121,32 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new Swagger\Client\Api\PetAPI($api_client); // create updated pet object $updated_pet = new Swagger\Client\Model\Pet; - $updated_pet->id = $pet_id; - $updated_pet->name = 'updatePet'; // new name - $updated_pet->status = 'pending'; // new status + $updated_pet->setId($pet_id); + $updated_pet->setName('updatePet'); // new name + $updated_pet->setStatus('pending'); // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) $this->assertSame($update_response, NULL); // verify updated Pet $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->status, 'pending'); - $this->assertSame($response->name, 'updatePet'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getStatus(), 'pending'); + $this->assertSame($response->getName(), 'updatePet'); } // test updatePet and verify by the "id" of the response public function testUpdatePetWithForm() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new Swagger\Client\Api\PetAPI($api_client); // update Pet (form) @@ -164,20 +154,21 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // return nothing (void) $this->assertSame($update_response, NULL); $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->name, 'update pet with form'); - $this->assertSame($response->status, 'sold'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form'); + $this->assertSame($response->getStatus(), 'sold'); } // test addPet and verify by the "id" and "name" of the response public function testAddPet() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $new_pet_id = 10001; $new_pet = new Swagger\Client\Model\Pet; - $new_pet->id = $new_pet_id; - $new_pet->name = "PHP Unit Test"; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); @@ -185,15 +176,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($add_response, NULL); // verify added Pet $response = $pet_api->getPetById($new_pet_id); - $this->assertSame($response->id, $new_pet_id); - $this->assertSame($response->name, 'PHP Unit Test'); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); } // test upload file public function testUploadFile() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // upload file $pet_id = 10001; @@ -206,7 +198,9 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $api_client = new Swagger\Client\APIClient('http://petstore.swagger.io/v2'); + $config = new Swagger\Client\Configuration(); + $config->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\APIClient($config); $store_api = new Swagger\Client\Api\StoreAPI($api_client); // get inventory $get_response = $store_api->getInventory(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index a92149fbaf3..05bd873c993 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -1,6 +1,6 @@ setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $store_api = new Swagger\Client\Api\StoreAPI($api_client); // get inventory $get_response = $store_api->getInventory(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 181e8a1249e..3efce8b08ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -1,6 +1,6 @@ setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $user_api = new Swagger\Client\Api\UserApi($api_client); // login $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); diff --git a/samples/client/petstore/python/SwaggerPetstore-python/Makefile b/samples/client/petstore/python/Makefile similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/Makefile rename to samples/client/petstore/python/Makefile diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/README.md similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/README.md rename to samples/client/petstore/python/README.md diff --git a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt b/samples/client/petstore/python/dev-requirements.txt similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt rename to samples/client/petstore/python/dev-requirements.txt diff --git a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml b/samples/client/petstore/python/pom.xml similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/pom.xml rename to samples/client/petstore/python/pom.xml diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg b/samples/client/petstore/python/setup.cfg similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/setup.cfg rename to samples/client/petstore/python/setup.cfg diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.py b/samples/client/petstore/python/setup.py similarity index 92% rename from samples/client/petstore/python/SwaggerPetstore-python/setup.py rename to samples/client/petstore/python/setup.py index fbd738be680..4232c3992b9 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -1,6 +1,9 @@ import sys from setuptools import setup, find_packages +NAME = "swagger_client" +VERSION = "1.0.0" + # To install the library, open a Terminal shell, then run this @@ -15,8 +18,8 @@ from setuptools import setup, find_packages REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] setup( - name="SwaggerPetstore", - version="1.0.0", + name=NAME, + version=VERSION, description="Swagger Petstore", author_email="apiteam@swagger.io", url="", diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py rename to samples/client/petstore/python/swagger_client/__init__.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py rename to samples/client/petstore/python/swagger_client/api_client.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py rename to samples/client/petstore/python/swagger_client/apis/__init__.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py rename to samples/client/petstore/python/swagger_client/apis/pet_api.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py rename to samples/client/petstore/python/swagger_client/apis/store_api.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py rename to samples/client/petstore/python/swagger_client/apis/user_api.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py rename to samples/client/petstore/python/swagger_client/configuration.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py b/samples/client/petstore/python/swagger_client/models/__init__.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py rename to samples/client/petstore/python/swagger_client/models/__init__.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py rename to samples/client/petstore/python/swagger_client/models/category.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py rename to samples/client/petstore/python/swagger_client/models/order.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py rename to samples/client/petstore/python/swagger_client/models/pet.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py rename to samples/client/petstore/python/swagger_client/models/tag.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py rename to samples/client/petstore/python/swagger_client/models/user.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/swagger_client/rest.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py rename to samples/client/petstore/python/swagger_client/rest.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/testfiles/foo.png b/samples/client/petstore/python/testfiles/foo.png similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/testfiles/foo.png rename to samples/client/petstore/python/testfiles/foo.png diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/__init__.py b/samples/client/petstore/python/tests/__init__.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/tests/__init__.py rename to samples/client/petstore/python/tests/__init__.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/tests/test_api_client.py similarity index 84% rename from samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py rename to samples/client/petstore/python/tests/test_api_client.py index 42d838417fd..d932006c052 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py +++ b/samples/client/petstore/python/tests/test_api_client.py @@ -11,8 +11,8 @@ import os import time import unittest -import SwaggerPetstore -import SwaggerPetstore.configuration +import swagger_client +import swagger_client.configuration HOST = 'http://petstore.swagger.io/v2' @@ -20,20 +20,20 @@ HOST = 'http://petstore.swagger.io/v2' class ApiClientTests(unittest.TestCase): def setUp(self): - self.api_client = SwaggerPetstore.ApiClient(HOST) + self.api_client = swagger_client.ApiClient(HOST) def test_configuration(self): - SwaggerPetstore.configuration.api_key['api_key'] = '123456' - SwaggerPetstore.configuration.api_key_prefix['api_key'] = 'PREFIX' - SwaggerPetstore.configuration.username = 'test_username' - SwaggerPetstore.configuration.password = 'test_password' + swagger_client.configuration.api_key['api_key'] = '123456' + swagger_client.configuration.api_key_prefix['api_key'] = 'PREFIX' + swagger_client.configuration.username = 'test_username' + swagger_client.configuration.password = 'test_password' header_params = {'test1': 'value1'} query_params = {'test2': 'value2'} auth_settings = ['api_key', 'unknown'] # test prefix - self.assertEqual('PREFIX', SwaggerPetstore.configuration.api_key_prefix['api_key']) + self.assertEqual('PREFIX', swagger_client.configuration.api_key_prefix['api_key']) # update parameters based on auth setting self.api_client.update_params_for_auth(header_params, query_params, auth_settings) @@ -44,8 +44,8 @@ class ApiClientTests(unittest.TestCase): self.assertEqual(query_params['test2'], 'value2') # test basic auth - self.assertEqual('test_username', SwaggerPetstore.configuration.username) - self.assertEqual('test_password', SwaggerPetstore.configuration.password) + self.assertEqual('test_username', swagger_client.configuration.username) + self.assertEqual('test_password', swagger_client.configuration.password) def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] @@ -114,7 +114,7 @@ class ApiClientTests(unittest.TestCase): data = self.api_client.deserialize(json, 'dict(str, Pet)') self.assertTrue(isinstance(data, dict)) - self.assertTrue(isinstance(data['pet'], SwaggerPetstore.Pet)) + self.assertTrue(isinstance(data['pet'], swagger_client.Pet)) # dict(str, int) json = { @@ -128,6 +128,3 @@ class ApiClientTests(unittest.TestCase): def test_deserialize_to_object(self): data = self.api_client.deserialize("", "object") self.assertTrue(type(data) == object) - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py similarity index 85% rename from samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py rename to samples/client/petstore/python/tests/test_api_exception.py index d1b786241e8..f3d00cb10dc 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd SwaggerPetstore-python +$ cd swagger_client-python $ nosetests -v """ @@ -11,25 +11,25 @@ import os import time import unittest -import SwaggerPetstore -from SwaggerPetstore.rest import ApiException +import swagger_client +from swagger_client.rest import ApiException class ApiExceptionTests(unittest.TestCase): def setUp(self): - self.api_client = SwaggerPetstore.ApiClient() - self.pet_api = SwaggerPetstore.PetApi(self.api_client) + self.api_client = swagger_client.ApiClient() + self.pet_api = swagger_client.PetApi(self.api_client) self.setUpModels() def setUpModels(self): - self.category = SwaggerPetstore.Category() + self.category = swagger_client.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = SwaggerPetstore.Tag() + self.tag = swagger_client.Tag() self.tag.id = int(time.time()) self.tag.name = "blank" - self.pet = SwaggerPetstore.Pet() + self.pet = swagger_client.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py similarity index 84% rename from samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py rename to samples/client/petstore/python/tests/test_pet_api.py index 3bf18607729..5397c0b50ef 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd SwaggerPetstore-python +$ cd swagger_client-python $ nosetests -v """ @@ -11,8 +11,8 @@ import os import time import unittest -import SwaggerPetstore -from SwaggerPetstore.rest import ApiException +import swagger_client +from swagger_client.rest import ApiException HOST = 'http://petstore.swagger.io/v2' @@ -20,8 +20,8 @@ HOST = 'http://petstore.swagger.io/v2' class PetApiTests(unittest.TestCase): def setUp(self): - self.api_client = SwaggerPetstore.ApiClient(HOST) - self.pet_api = SwaggerPetstore.PetApi(self.api_client) + self.api_client = swagger_client.ApiClient(HOST) + self.pet_api = swagger_client.PetApi(self.api_client) self.setUpModels() self.setUpFiles() @@ -30,13 +30,13 @@ class PetApiTests(unittest.TestCase): time.sleep(1) def setUpModels(self): - self.category = SwaggerPetstore.Category() + self.category = swagger_client.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = SwaggerPetstore.Tag() + self.tag = swagger_client.Tag() self.tag.id = int(time.time()) self.tag.name = "blank" - self.pet = SwaggerPetstore.Pet() + self.pet = swagger_client.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] @@ -50,22 +50,22 @@ class PetApiTests(unittest.TestCase): self.foo = os.path.join(self.test_file_dir, "foo.png") def test_create_api_instance(self): - pet_api = SwaggerPetstore.PetApi() - pet_api2 = SwaggerPetstore.PetApi() - api_client3 = SwaggerPetstore.ApiClient() + pet_api = swagger_client.PetApi() + pet_api2 = swagger_client.PetApi() + api_client3 = swagger_client.ApiClient() api_client3.user_agent = 'api client 3' - api_client4 = SwaggerPetstore.ApiClient() + api_client4 = swagger_client.ApiClient() api_client4.user_agent = 'api client 4' - pet_api3 = SwaggerPetstore.PetApi(api_client3) + pet_api3 = swagger_client.PetApi(api_client3) # same default api client self.assertEqual(pet_api.api_client, pet_api2.api_client) # confirm using the default api client in the config module - self.assertEqual(pet_api.api_client, SwaggerPetstore.configuration.api_client) + self.assertEqual(pet_api.api_client, swagger_client.configuration.api_client) # 2 different api clients are not the same self.assertNotEqual(api_client3, api_client4) # customized pet api not using the default api client - self.assertNotEqual(pet_api3.api_client, SwaggerPetstore.configuration.api_client) + self.assertNotEqual(pet_api3.api_client, swagger_client.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tox.ini b/samples/client/petstore/python/tox.ini similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/tox.ini rename to samples/client/petstore/python/tox.ini diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index 7e56a41c890..9f39f4e45ce 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -72,6 +72,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.9.1 add_sources @@ -208,7 +209,7 @@ 2.10.4 1.2 2.2 - 1.7 + 1.19 1.5.0 1.0.5 1.0.0 @@ -216,6 +217,8 @@ 4.8.1 3.1.5 - 2.1.3 + 2.2.4 + + UTF-8 diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index 91ab98471e9..1f9d3c012d5 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -141,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } case _ => null } - response.getClientResponseStatus().getStatusCode() match { + response.getStatusInfo().getStatusCode() match { case 204 => "" case code: Int if (Range(200, 299).contains(code)) => { response.hasEntity() match { @@ -155,7 +155,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, case false => "no data" } throw new ApiException( - response.getClientResponseStatus().getStatusCode(), + response.getStatusInfo().getStatusCode(), entity) } } @@ -172,7 +172,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, } } } - + def newClient(host: String): Client = asyncHttpClient match { case true => { import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig @@ -200,4 +200,3 @@ object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, authPreemptive = false) class ApiException(val code: Int, msg: String) extends RuntimeException(msg) - diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala index 430f6a3659c..30dc8750976 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -1,7 +1,5 @@ package io.swagger.client.model -import io.swagger.client.model.Category -import io.swagger.client.model.Tag diff --git a/samples/client/petstore/silex/silex/.htaccess b/samples/client/petstore/silex/silex/.htaccess deleted file mode 100644 index e47b5fb8a0c..00000000000 --- a/samples/client/petstore/silex/silex/.htaccess +++ /dev/null @@ -1,5 +0,0 @@ - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] - \ No newline at end of file diff --git a/samples/client/petstore/silex/silex/README.md b/samples/client/petstore/silex/silex/README.md deleted file mode 100644 index 9f35636b3f8..00000000000 --- a/samples/client/petstore/silex/silex/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Swagger generated server - -## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a PHP server. - -This example uses the [Silex](http://silex.sensiolabs.org/) micro-framework. To see how to make this your own, please take a look at the template here: - -[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/silex/) diff --git a/samples/client/petstore/silex/silex/composer.json b/samples/client/petstore/silex/silex/composer.json deleted file mode 100644 index 466cd3fbc77..00000000000 --- a/samples/client/petstore/silex/silex/composer.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "require": { - "silex/silex": "~1.2" - } -} \ No newline at end of file diff --git a/samples/client/petstore/silex/silex/index.php b/samples/client/petstore/silex/silex/index.php deleted file mode 100644 index 1526f3cb8f3..00000000000 --- a/samples/client/petstore/silex/silex/index.php +++ /dev/null @@ -1,184 +0,0 @@ -POST('/user', function(Application $app, Request $request) { - - - return new Response('How about implementing createUser as a POST method ?'); - }); - - - -$app->POST('/user/createWithArray', function(Application $app, Request $request) { - - - return new Response('How about implementing createUsersWithArrayInput as a POST method ?'); - }); - - - -$app->POST('/user/createWithList', function(Application $app, Request $request) { - - - return new Response('How about implementing createUsersWithListInput as a POST method ?'); - }); - - - -$app->GET('/user/login', function(Application $app, Request $request) { - $username = $request->get('username'); $password = $request->get('password'); - - return new Response('How about implementing loginUser as a GET method ?'); - }); - - - -$app->GET('/user/logout', function(Application $app, Request $request) { - - - return new Response('How about implementing logoutUser as a GET method ?'); - }); - - - -$app->GET('/user/{username}', function(Application $app, Request $request, $username) { - - - return new Response('How about implementing getUserByName as a GET method ?'); - }); - - - -$app->PUT('/user/{username}', function(Application $app, Request $request, $username) { - - - return new Response('How about implementing updateUser as a PUT method ?'); - }); - - - -$app->DELETE('/user/{username}', function(Application $app, Request $request, $username) { - - - return new Response('How about implementing deleteUser as a DELETE method ?'); - }); - - - - - - - -$app->PUT('/pet', function(Application $app, Request $request) { - - - return new Response('How about implementing updatePet as a PUT method ?'); - }); - - - -$app->POST('/pet', function(Application $app, Request $request) { - - - return new Response('How about implementing addPet as a POST method ?'); - }); - - - -$app->GET('/pet/findByStatus', function(Application $app, Request $request) { - $status = $request->get('status'); - - return new Response('How about implementing findPetsByStatus as a GET method ?'); - }); - - - -$app->GET('/pet/findByTags', function(Application $app, Request $request) { - $tags = $request->get('tags'); - - return new Response('How about implementing findPetsByTags as a GET method ?'); - }); - - - -$app->GET('/pet/{petId}', function(Application $app, Request $request, $pet_id) { - - - return new Response('How about implementing getPetById as a GET method ?'); - }); - - - -$app->POST('/pet/{petId}', function(Application $app, Request $request, $pet_id) { - - $name = $request->get('name'); $status = $request->get('status'); - return new Response('How about implementing updatePetWithForm as a POST method ?'); - }); - - - -$app->DELETE('/pet/{petId}', function(Application $app, Request $request, $pet_id) { - - - return new Response('How about implementing deletePet as a DELETE method ?'); - }); - - - -$app->POST('/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) { - - $additional_metadata = $request->get('additional_metadata'); $file = $request->get('file'); - return new Response('How about implementing uploadFile as a POST method ?'); - }); - - - - - - - -$app->GET('/store/inventory', function(Application $app, Request $request) { - - - return new Response('How about implementing getInventory as a GET method ?'); - }); - - - -$app->POST('/store/order', function(Application $app, Request $request) { - - - return new Response('How about implementing placeOrder as a POST method ?'); - }); - - - -$app->GET('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { - - - return new Response('How about implementing getOrderById as a GET method ?'); - }); - - - -$app->DELETE('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { - - - return new Response('How about implementing deleteOrder as a DELETE method ?'); - }); - - - - - -$app->run(); diff --git a/samples/client/petstore/typescript-angular/api/Category.ts b/samples/client/petstore/typescript-angular/api/Category.ts new file mode 100644 index 00000000000..e4a3caa208e --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/Category.ts @@ -0,0 +1,13 @@ +/// + +module api { + 'use strict'; + + export class Category { + + id: number; + + name: string; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/Order.ts b/samples/client/petstore/typescript-angular/api/Order.ts new file mode 100644 index 00000000000..3f37c608758 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/Order.ts @@ -0,0 +1,32 @@ +/// + +module api { + 'use strict'; + + export class Order { + + id: number; + + petId: number; + + quantity: number; + + shipDate: DateTime; + + /** + * Order Status + */ + status: Order.StatusEnum; + + complete: boolean; + } + + export module Order { + + export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered', + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/Pet.ts b/samples/client/petstore/typescript-angular/api/Pet.ts new file mode 100644 index 00000000000..c34be9c3dbc --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/Pet.ts @@ -0,0 +1,32 @@ +/// + +module api { + 'use strict'; + + export class Pet { + + id: number; + + category: Category; + + name: string; + + photoUrls: Array; + + tags: Array; + + /** + * pet status in the store + */ + status: Pet.StatusEnum; + } + + export module Pet { + + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold', + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/PetApi.ts b/samples/client/petstore/typescript-angular/api/PetApi.ts new file mode 100644 index 00000000000..d294cfbebbc --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/PetApi.ts @@ -0,0 +1,282 @@ +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +module api { + 'use strict'; + + + export class PetApi { + private basePath = 'http://petstore.swagger.io/v2'; + + static $inject: string[] = ['$http']; + + constructor(private $http: ng.IHttpService, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public updatePet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/pet'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'PUT', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public addPet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/pet'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public findPetsByStatus (status: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + var path = this.basePath + '/pet/findByStatus'; + + var queryParameters: any = {}; + var headers: any = {}; + + if (status !== undefined) { + queryParameters['status'] = status; + } + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public findPetsByTags (tags: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + var path = this.basePath + '/pet/findByTags'; + + var queryParameters: any = {}; + var headers: any = {}; + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + var path = this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public updatePetWithForm (petId: string, name: string, status: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public deletePet (apiKey: string, petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + + headerParams['apiKey'] = apiKey; + var httpRequestParams: any = { + method: 'DELETE', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public uploadFile (petId: number, additionalMetadata: string, file: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/pet/{petId}/uploadImage'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + } + + angular.module('api_PetApi', ['$http']) + .service('PetApi', PetApi); +} diff --git a/samples/client/petstore/typescript-angular/api/StoreApi.ts b/samples/client/petstore/typescript-angular/api/StoreApi.ts new file mode 100644 index 00000000000..e8c85b00c45 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/StoreApi.ts @@ -0,0 +1,151 @@ +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +module api { + 'use strict'; + + + export class StoreApi { + private basePath = 'http://petstore.swagger.io/v2'; + + static $inject: string[] = ['$http']; + + constructor(private $http: ng.IHttpService, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public getInventory ( extraHttpRequestParams?: any ) : ng.IHttpPromise> { + var path = this.basePath + '/store/inventory'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public placeOrder (body: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + var path = this.basePath + '/store/order'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + var path = this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + + + var httpRequestParams: any = { + method: 'DELETE', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + } + + angular.module('api_StoreApi', ['$http']) + .service('StoreApi', StoreApi); +} diff --git a/samples/client/petstore/typescript-angular/api/Tag.ts b/samples/client/petstore/typescript-angular/api/Tag.ts new file mode 100644 index 00000000000..33f0ffaa1e2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/Tag.ts @@ -0,0 +1,13 @@ +/// + +module api { + 'use strict'; + + export class Tag { + + id: number; + + name: string; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/User.ts b/samples/client/petstore/typescript-angular/api/User.ts new file mode 100644 index 00000000000..57385044943 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/User.ts @@ -0,0 +1,28 @@ +/// + +module api { + 'use strict'; + + export class User { + + id: number; + + username: string; + + firstName: string; + + lastName: string; + + email: string; + + password: string; + + phone: string; + + /** + * User Status + */ + userStatus: number; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/UserApi.ts b/samples/client/petstore/typescript-angular/api/UserApi.ts new file mode 100644 index 00000000000..40d82f73852 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/UserApi.ts @@ -0,0 +1,277 @@ +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +module api { + 'use strict'; + + + export class UserApi { + private basePath = 'http://petstore.swagger.io/v2'; + + static $inject: string[] = ['$http']; + + constructor(private $http: ng.IHttpService, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + public createUser (body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public createUsersWithArrayInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user/createWithArray'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public createUsersWithListInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user/createWithList'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'POST', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public loginUser (username: string, password: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + var path = this.basePath + '/user/login'; + + var queryParameters: any = {}; + var headers: any = {}; + + if (username !== undefined) { + queryParameters['username'] = username; + }if (password !== undefined) { + queryParameters['password'] = password; + } + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public logoutUser ( extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user/logout'; + + var queryParameters: any = {}; + var headers: any = {}; + + + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + var path = this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + + + var httpRequestParams: any = { + method: 'GET', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public updateUser (username: string, body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + + + var httpRequestParams: any = { + method: 'PUT', + url: path, + json: true, + data: body, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + var path = this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headers: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + + + + var httpRequestParams: any = { + method: 'DELETE', + url: path, + json: true, + + params: queryParameters, + headers: headers + }; + + if (extraHttpRequestParams) { + for (var k in extraHttpRequestParams){ + if (extraHttpRequestParams.hasOwnProperty(k)) { + httpRequestParams[k] = extraHttpRequestParams[k]; + } + } + } + + return this.$http(httpRequestParams); + } + + } + + angular.module('api_UserApi', ['$http']) + .service('UserApi', UserApi); +} diff --git a/samples/client/petstore/typescript-angular/api/api.d.ts b/samples/client/petstore/typescript-angular/api/api.d.ts new file mode 100644 index 00000000000..19c60623dc9 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/api.d.ts @@ -0,0 +1,9 @@ +/// +/// +/// +/// +/// + +/// +/// +/// diff --git a/samples/client/petstore/typescript-node/api/PetApi.ts b/samples/client/petstore/typescript-node/api/PetApi.ts new file mode 100644 index 00000000000..02605f2c8a8 --- /dev/null +++ b/samples/client/petstore/typescript-node/api/PetApi.ts @@ -0,0 +1,378 @@ +/* tslint:disable:no-unused-variable */ + +export class PetApi { + private basePath = 'http://petstore.swagger.io/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + + public updatePet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'PUT', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public addPet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public findPetsByStatus (status: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByStatus'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + if (status !== undefined) { + queryParameters['status'] = status; + } + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public findPetsByTags (tags: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByTags'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public getPetById (petId: number ) : Promise<{ response: http.ClientResponse; body: Pet; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + + path = path.replace('{' + 'petId' + '}', String(petId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public updatePetWithForm (petId: string, name: string, status: string ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + + path = path.replace('{' + 'petId' + '}', String(petId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public deletePet (apiKey: string, petId: number ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + + path = path.replace('{' + 'petId' + '}', String(petId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + + + + headerParams['apiKey'] = apiKey; + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public uploadFile (petId: number, additionalMetadata: string, file: file ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; + + + path = path.replace('{' + 'petId' + '}', String(petId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + +} diff --git a/samples/client/petstore/typescript-node/api/StoreApi.ts b/samples/client/petstore/typescript-node/api/StoreApi.ts new file mode 100644 index 00000000000..71cfe106fca --- /dev/null +++ b/samples/client/petstore/typescript-node/api/StoreApi.ts @@ -0,0 +1,192 @@ +/* tslint:disable:no-unused-variable */ + +export class StoreApi { + private basePath = 'http://petstore.swagger.io/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + + public getInventory ( ) : Promise<{ response: http.ClientResponse; body: map; }> { + var path = this.url + this.basePath + '/store/inventory'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public placeOrder (body: Order ) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public getOrderById (orderId: string ) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public deleteOrder (orderId: string ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + +} diff --git a/samples/client/petstore/typescript-node/api/UserApi.ts b/samples/client/petstore/typescript-node/api/UserApi.ts new file mode 100644 index 00000000000..ca6fd41c593 --- /dev/null +++ b/samples/client/petstore/typescript-node/api/UserApi.ts @@ -0,0 +1,372 @@ +/* tslint:disable:no-unused-variable */ + +export class UserApi { + private basePath = 'http://petstore.swagger.io/v2'; + + constructor(private url: string, private username: string, private password: string, basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + + public createUser (body: User ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public createUsersWithArrayInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithArray'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public createUsersWithListInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithList'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'POST', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public loginUser (username: string, password: string ) : Promise<{ response: http.ClientResponse; body: string; }> { + var path = this.url + this.basePath + '/user/login'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + if (username !== undefined) { + queryParameters['username'] = username; + } + if (password !== undefined) { + queryParameters['password'] = password; + } + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public logoutUser ( ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/logout'; + + + + var queryParameters: any = {}; + var headers: any = {}; + + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public getUserByName (username: string ) : Promise<{ response: http.ClientResponse; body: User; }> { + var path = this.url + this.basePath + '/user/{username}'; + + + path = path.replace('{' + 'username' + '}', String(username)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + + request({ + method: 'GET', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public updateUser (username: string, body: User ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + + path = path.replace('{' + 'username' + '}', String(username)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'PUT', + qs: queryParameters, + uri: path, + json: true, + body: body, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + + public deleteUser (username: string ) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + + path = path.replace('{' + 'username' + '}', String(username)); + + + var queryParameters: any = {}; + var headers: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + + + + + + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + request({ + method: 'DELETE', + qs: queryParameters, + uri: path, + json: true, + + auth: { + username: this.username, password: this.password + } + }, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + +} diff --git a/samples/client/petstore/typescript-node/model/Category.ts b/samples/client/petstore/typescript-node/model/Category.ts new file mode 100644 index 00000000000..fc4b2874e93 --- /dev/null +++ b/samples/client/petstore/typescript-node/model/Category.ts @@ -0,0 +1,7 @@ +export class Category { + + id: number; + + name: string; +} + diff --git a/samples/client/petstore/typescript-node/model/Order.ts b/samples/client/petstore/typescript-node/model/Order.ts new file mode 100644 index 00000000000..b46ad4570a0 --- /dev/null +++ b/samples/client/petstore/typescript-node/model/Order.ts @@ -0,0 +1,26 @@ +export class Order { + + id: number; + + petId: number; + + quantity: number; + + shipDate: DateTime; + + /** + * Order Status + */ + status: Order.StatusEnum; + + complete: boolean; +} + +export module Order { + + export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered', + } +} diff --git a/samples/client/petstore/typescript-node/model/Pet.ts b/samples/client/petstore/typescript-node/model/Pet.ts new file mode 100644 index 00000000000..4a3faa129ed --- /dev/null +++ b/samples/client/petstore/typescript-node/model/Pet.ts @@ -0,0 +1,26 @@ +export class Pet { + + id: number; + + category: Category; + + name: string; + + photoUrls: Array; + + tags: Array; + + /** + * pet status in the store + */ + status: Pet.StatusEnum; +} + +export module Pet { + + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold', + } +} diff --git a/samples/client/petstore/typescript-node/model/Tag.ts b/samples/client/petstore/typescript-node/model/Tag.ts new file mode 100644 index 00000000000..6ae0d4ef576 --- /dev/null +++ b/samples/client/petstore/typescript-node/model/Tag.ts @@ -0,0 +1,7 @@ +export class Tag { + + id: number; + + name: string; +} + diff --git a/samples/client/petstore/typescript-node/model/User.ts b/samples/client/petstore/typescript-node/model/User.ts new file mode 100644 index 00000000000..fee31563d13 --- /dev/null +++ b/samples/client/petstore/typescript-node/model/User.ts @@ -0,0 +1,22 @@ +export class User { + + id: number; + + username: string; + + firstName: string; + + lastName: string; + + email: string; + + password: string; + + phone: string; + + /** + * User Status + */ + userStatus: number; +} + diff --git a/samples/client/petstore/silex/SwaggerServer/.htaccess b/samples/server/petstore/silex/SwaggerServer/.htaccess similarity index 100% rename from samples/client/petstore/silex/SwaggerServer/.htaccess rename to samples/server/petstore/silex/SwaggerServer/.htaccess diff --git a/samples/client/petstore/silex/SwaggerServer/README.md b/samples/server/petstore/silex/SwaggerServer/README.md similarity index 100% rename from samples/client/petstore/silex/SwaggerServer/README.md rename to samples/server/petstore/silex/SwaggerServer/README.md diff --git a/samples/client/petstore/silex/SwaggerServer/composer.json b/samples/server/petstore/silex/SwaggerServer/composer.json similarity index 100% rename from samples/client/petstore/silex/SwaggerServer/composer.json rename to samples/server/petstore/silex/SwaggerServer/composer.json diff --git a/samples/client/petstore/silex/SwaggerServer/index.php b/samples/server/petstore/silex/SwaggerServer/index.php similarity index 100% rename from samples/client/petstore/silex/SwaggerServer/index.php rename to samples/server/petstore/silex/SwaggerServer/index.php diff --git a/samples/server/petstore/sinatra/Gemfile b/samples/server/petstore/sinatra/Gemfile new file mode 100644 index 00000000000..be9c3168ea6 --- /dev/null +++ b/samples/server/petstore/sinatra/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +gem "sinatra" +gem "sinatra-cross_origin" \ No newline at end of file diff --git a/samples/server/petstore/sinatra/Gemfile.lock b/samples/server/petstore/sinatra/Gemfile.lock new file mode 100644 index 00000000000..3b7c05b4083 --- /dev/null +++ b/samples/server/petstore/sinatra/Gemfile.lock @@ -0,0 +1,19 @@ +GEM + remote: https://rubygems.org/ + specs: + rack (1.6.4) + rack-protection (1.5.3) + rack + sinatra (1.4.6) + rack (~> 1.4) + rack-protection (~> 1.4) + tilt (>= 1.3, < 3) + sinatra-cross_origin (0.3.2) + tilt (2.0.1) + +PLATFORMS + ruby + +DEPENDENCIES + sinatra + sinatra-cross_origin diff --git a/samples/server/petstore/sinatra/README.md b/samples/server/petstore/sinatra/README.md new file mode 100644 index 00000000000..c5b8cfffe77 --- /dev/null +++ b/samples/server/petstore/sinatra/README.md @@ -0,0 +1,29 @@ +# Swagger for Sinatra + +## Overview +This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find +out more about both the spec and the framework at http://swagger.io. For more information about +Wordnik's APIs, please visit http://developer.wordnik.com. + +## Prerequisites +You need to install ruby 1.9.3 and the following gems: + +``` +sinatra +sinatra-cross_origin +``` + +## Getting started +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +rackup -p 4567 config.ru +``` + +In your [swagger ui](https://github.com/swagger-api/swagger-ui), put in the following URL: + +``` +http://localhost:4567/resources.json +``` + +Voila! diff --git a/samples/server/petstore/sinatra/api/pet_api.rb b/samples/server/petstore/sinatra/api/pet_api.rb new file mode 100644 index 00000000000..2fdc1f2a6e6 --- /dev/null +++ b/samples/server/petstore/sinatra/api/pet_api.rb @@ -0,0 +1,231 @@ +require 'json' + + +MyApp.add_route('PUT', '/pet', { + "resourcePath" => "/Pet", + "summary" => "Update an existing pet", + "nickname" => "update_pet", + "responseClass" => "void", + "endpoint" => "/pet", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "Pet object that needs to be added to the store", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/pet', { + "resourcePath" => "/Pet", + "summary" => "Add a new pet to the store", + "nickname" => "add_pet", + "responseClass" => "void", + "endpoint" => "/pet", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "Pet object that needs to be added to the store", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/pet/findByStatus', { + "resourcePath" => "/Pet", + "summary" => "Finds Pets by status", + "nickname" => "find_pets_by_status", + "responseClass" => "array[Pet]", + "endpoint" => "/pet/findByStatus", + "notes" => "Multiple status values can be provided with comma seperated strings", + "parameters" => [ + + { + "name" => "status", + "description" => "Status values that need to be considered for filter", + "dataType" => "", + "paramType" => "query", + "allowMultiple" => , + "allowableValues" => "", + "defaultValue" => available + }, + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/pet/findByTags', { + "resourcePath" => "/Pet", + "summary" => "Finds Pets by tags", + "nickname" => "find_pets_by_tags", + "responseClass" => "array[Pet]", + "endpoint" => "/pet/findByTags", + "notes" => "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "parameters" => [ + + { + "name" => "tags", + "description" => "Tags to filter by", + "dataType" => "", + "paramType" => "query", + "allowMultiple" => , + "allowableValues" => "", + + }, + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/pet/{petId}', { + "resourcePath" => "/Pet", + "summary" => "Find pet by ID", + "nickname" => "get_pet_by_id", + "responseClass" => "Pet", + "endpoint" => "/pet/{petId}", + "notes" => "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "parameters" => [ + + + { + "name" => "pet_id", + "description" => "ID of pet that needs to be fetched", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/pet/{petId}', { + "resourcePath" => "/Pet", + "summary" => "Updates a pet in the store with form data", + "nickname" => "update_pet_with_form", + "responseClass" => "void", + "endpoint" => "/pet/{petId}", + "notes" => "", + "parameters" => [ + + + { + "name" => "pet_id", + "description" => "ID of pet that needs to be updated", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('DELETE', '/pet/{petId}', { + "resourcePath" => "/Pet", + "summary" => "Deletes a pet", + "nickname" => "delete_pet", + "responseClass" => "void", + "endpoint" => "/pet/{petId}", + "notes" => "", + "parameters" => [ + + + { + "name" => "pet_id", + "description" => "Pet id to delete", + "dataType" => "", + "paramType" => "path", + }, + + + { + "name" => "api_key", + "description" => "", + "dataType" => "", + "paramType" => "header", + }, + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/pet/{petId}/uploadImage', { + "resourcePath" => "/Pet", + "summary" => "uploads an image", + "nickname" => "upload_file", + "responseClass" => "void", + "endpoint" => "/pet/{petId}/uploadImage", + "notes" => "", + "parameters" => [ + + + { + "name" => "pet_id", + "description" => "ID of pet to update", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + diff --git a/samples/server/petstore/sinatra/api/store_api.rb b/samples/server/petstore/sinatra/api/store_api.rb new file mode 100644 index 00000000000..245ae23bff7 --- /dev/null +++ b/samples/server/petstore/sinatra/api/store_api.rb @@ -0,0 +1,103 @@ +require 'json' + + +MyApp.add_route('GET', '/store/inventory', { + "resourcePath" => "/Store", + "summary" => "Returns pet inventories by status", + "nickname" => "get_inventory", + "responseClass" => "map[string,int]", + "endpoint" => "/store/inventory", + "notes" => "Returns a map of status codes to quantities", + "parameters" => [ + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/store/order', { + "resourcePath" => "/Store", + "summary" => "Place an order for a pet", + "nickname" => "place_order", + "responseClass" => "Order", + "endpoint" => "/store/order", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "order placed for purchasing the pet", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/store/order/{orderId}', { + "resourcePath" => "/Store", + "summary" => "Find purchase order by ID", + "nickname" => "get_order_by_id", + "responseClass" => "Order", + "endpoint" => "/store/order/{orderId}", + "notes" => "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "parameters" => [ + + + { + "name" => "order_id", + "description" => "ID of pet that needs to be fetched", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('DELETE', '/store/order/{orderId}', { + "resourcePath" => "/Store", + "summary" => "Delete purchase order by ID", + "nickname" => "delete_order", + "responseClass" => "void", + "endpoint" => "/store/order/{orderId}", + "notes" => "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "parameters" => [ + + + { + "name" => "order_id", + "description" => "ID of the order that needs to be deleted", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + diff --git a/samples/server/petstore/sinatra/api/user_api.rb b/samples/server/petstore/sinatra/api/user_api.rb new file mode 100644 index 00000000000..8cbd49d72a0 --- /dev/null +++ b/samples/server/petstore/sinatra/api/user_api.rb @@ -0,0 +1,231 @@ +require 'json' + + +MyApp.add_route('POST', '/user', { + "resourcePath" => "/User", + "summary" => "Create user", + "nickname" => "create_user", + "responseClass" => "void", + "endpoint" => "/user", + "notes" => "This can only be done by the logged in user.", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "Created user object", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/user/createWithArray', { + "resourcePath" => "/User", + "summary" => "Creates list of users with given input array", + "nickname" => "create_users_with_array_input", + "responseClass" => "void", + "endpoint" => "/user/createWithArray", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "List of user object", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/user/createWithList', { + "resourcePath" => "/User", + "summary" => "Creates list of users with given input array", + "nickname" => "create_users_with_list_input", + "responseClass" => "void", + "endpoint" => "/user/createWithList", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "List of user object", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/user/login', { + "resourcePath" => "/User", + "summary" => "Logs user into the system", + "nickname" => "login_user", + "responseClass" => "string", + "endpoint" => "/user/login", + "notes" => "", + "parameters" => [ + + { + "name" => "username", + "description" => "The user name for login", + "dataType" => "", + "paramType" => "query", + "allowMultiple" => , + "allowableValues" => "", + + }, + + { + "name" => "password", + "description" => "The password for login in clear text", + "dataType" => "", + "paramType" => "query", + "allowMultiple" => , + "allowableValues" => "", + + }, + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/user/logout', { + "resourcePath" => "/User", + "summary" => "Logs out current logged in user session", + "nickname" => "logout_user", + "responseClass" => "void", + "endpoint" => "/user/logout", + "notes" => "", + "parameters" => [ + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/user/{username}', { + "resourcePath" => "/User", + "summary" => "Get user by user name", + "nickname" => "get_user_by_name", + "responseClass" => "User", + "endpoint" => "/user/{username}", + "notes" => "", + "parameters" => [ + + + { + "name" => "username", + "description" => "The name that needs to be fetched. Use user1 for testing. ", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('PUT', '/user/{username}', { + "resourcePath" => "/User", + "summary" => "Updated user", + "nickname" => "update_user", + "responseClass" => "void", + "endpoint" => "/user/{username}", + "notes" => "This can only be done by the logged in user.", + "parameters" => [ + + + { + "name" => "username", + "description" => "name that need to be deleted", + "dataType" => "", + "paramType" => "path", + }, + + + + { + "name" => "body", + "description" => "Updated user object", + "dataType" => "", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('DELETE', '/user/{username}', { + "resourcePath" => "/User", + "summary" => "Delete user", + "nickname" => "delete_user", + "responseClass" => "void", + "endpoint" => "/user/{username}", + "notes" => "This can only be done by the logged in user.", + "parameters" => [ + + + { + "name" => "username", + "description" => "The name that needs to be deleted", + "dataType" => "", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + diff --git a/samples/server/petstore/sinatra/config.ru b/samples/server/petstore/sinatra/config.ru new file mode 100644 index 00000000000..395d0587123 --- /dev/null +++ b/samples/server/petstore/sinatra/config.ru @@ -0,0 +1,2 @@ +require './my_app' +run MyApp diff --git a/samples/server/petstore/sinatra/lib/swaggering.rb b/samples/server/petstore/sinatra/lib/swaggering.rb new file mode 100644 index 00000000000..79aca1da2c9 --- /dev/null +++ b/samples/server/petstore/sinatra/lib/swaggering.rb @@ -0,0 +1,154 @@ +require 'json' +require 'sinatra/base' +require 'sinatra/cross_origin' + +class Configuration + attr_accessor :base_path, :api_version, :swagger_version, :format_specifier + + def initialize + @api_version = '1.0' + @base_path = 'http://localhost:4567' + @swagger_version = '1.1' + @format_specifier = ".json" + end +end + +class Swaggering < Sinatra::Base + register Sinatra::CrossOrigin + + @@routes = {} + @@configuration = Configuration.new + + attr_accessor :configuration + + def self.configure + get("/resources" + @@configuration.format_specifier) { + cross_origin + Swaggering.to_resource_listing + } + @@configuration ||= Configuration.new + yield(@@configuration) if block_given? + end + + def self.add_route(method, path, swag={}, opts={}, &block) + fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + + accepted = case method + when 'get' + get(fullPath, opts, &block) + true + when 'post' + post(fullPath, opts, &block) + true + when 'delete' + delete(fullPath, opts, &block) + true + when 'put' + put(fullPath, opts, &block) + true + else + false + end + + if accepted then + resourcePath = swag["resourcePath"].to_s + ops = @@routes[resourcePath] + if ops.nil? + ops = Array.new + @@routes.merge!(resourcePath => ops) + + get(resourcePath + @@configuration.format_specifier) do + cross_origin + Swaggering.to_api(resourcePath) + end + end + + swag.merge!("httpMethod" => method.to_s.upcase) + ops.push(swag) + end + end + + def self.to_resource_listing + apis = Array.new + (@@routes.keys).each do |key| + api = { + "path" => (key + ".{format}"), + "description" => "no description" + } + apis.push api + end + + resource = { + "apiVersion" => @@configuration.api_version, + "swaggerVersion" => @@configuration.swagger_version, + "apis" => apis + } + + resource.to_json + end + + def self.to_api(resourcePath) + apis = {} + models = [] + + @@routes[resourcePath].each do |route| + endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2') + path = (resourcePath + ".{format}" + endpoint) + api = apis[path] + if api.nil? + api = {"path" => path, "description" => "description", "operations" => []} + apis.merge!(path => api) + end + + parameters = route["parameters"] + + unless parameters.nil? then + parameters.each do |param| + av_string = param["allowableValues"] + unless av_string.nil? + if av_string.count('[') > 0 + pattern = /^([A-Z]*)\[(.*)\]/ + match = pattern.match av_string + case match.to_a[1] + when "LIST" + allowables = match.to_a[2].split(',') + param["allowableValues"] = { + "valueType" => "LIST", + "values" => allowables + } + when "RANGE" + allowables = match.to_a[2].split(',') + param["allowableValues"] = { + "valueType" => "RANGE", + "min" => allowables[0], + "max" => allowables[1] + } + end + end + end + end + end + + op = { + "httpMethod" => route["httpMethod"], + "description" => route["summary"], + "responseClass" => route["responseClass"], + "notes" => route["notes"], + "nickname" => route["nickname"], + "summary" => route["summary"], + "parameters" => route["parameters"] + } + api["operations"].push(op) + end + + api_listing = { + "apiVersion" => @@configuration.api_version, + "swaggerVersion" => @@configuration.swagger_version, + "basePath" => @@configuration.base_path, + "resourcePath" => resourcePath, + "apis" => apis.values, + "models" => models + } + api_listing.to_json + end +end diff --git a/samples/server/petstore/sinatra/my_app.rb b/samples/server/petstore/sinatra/my_app.rb new file mode 100644 index 00000000000..4e692eb53bc --- /dev/null +++ b/samples/server/petstore/sinatra/my_app.rb @@ -0,0 +1,9 @@ +require './lib/swaggering' + +# only need to extend if you want special configuration! +class MyApp < Swaggering + self.configure do |config| + config.api_version = '0.2' + end +end +