prep for swagger-1.2 support

This commit is contained in:
Tony Tam 2013-08-08 12:13:08 -07:00
parent 1a1bfd2c7c
commit 7f73007ec4
13 changed files with 249 additions and 171 deletions

View File

@ -208,11 +208,11 @@ class Codegen(config: CodegenConfig) {
var paramList = new ListBuffer[HashMap[String, AnyRef]] var paramList = new ListBuffer[HashMap[String, AnyRef]]
var errorList = new ListBuffer[HashMap[String, AnyRef]] var errorList = new ListBuffer[HashMap[String, AnyRef]]
if (operation.errorResponses != null) { if (operation.responseMessages != null) {
operation.errorResponses.foreach(param => { operation.responseMessages.foreach(param => {
val params = new HashMap[String, AnyRef] val params = new HashMap[String, AnyRef]
params += "code" -> param.code.toString() params += "code" -> param.code.toString()
params += "reason" -> param.reason params += "reason" -> param.message
params += "hasMore" -> "true" params += "hasMore" -> "true"
errorList += params errorList += params
}) })
@ -224,7 +224,7 @@ class Codegen(config: CodegenConfig) {
val params = new HashMap[String, AnyRef] val params = new HashMap[String, AnyRef]
params += (param.paramType + "Parameter") -> "true" params += (param.paramType + "Parameter") -> "true"
params += "type" -> param.paramType params += "type" -> param.paramType
params += "defaultValue" -> config.toDefaultValue(param.dataType, param.defaultValue) params += "defaultValue" -> config.toDefaultValue(param.dataType, param.defaultValue.getOrElse(""))
params += "dataType" -> config.toDeclaredType(param.dataType) params += "dataType" -> config.toDeclaredType(param.dataType)
params += "swaggerDataType" -> param.dataType params += "swaggerDataType" -> param.dataType
params += "description" -> param.description params += "description" -> param.description
@ -336,7 +336,7 @@ class Codegen(config: CodegenConfig) {
"notes" -> operation.notes, "notes" -> operation.notes,
"deprecated" -> operation.`deprecated`, "deprecated" -> operation.`deprecated`,
"bodyParam" -> bodyParam, "bodyParam" -> bodyParam,
"emptyBodyParam" -> (if (writeMethods contains operation.httpMethod.toUpperCase) "{}" else ""), "emptyBodyParam" -> (if (writeMethods contains operation.method.toUpperCase) "{}" else ""),
"allParams" -> sp, "allParams" -> sp,
"bodyParams" -> bodyParams.toList, "bodyParams" -> bodyParams.toList,
"pathParams" -> pathParams.toList, "pathParams" -> pathParams.toList,
@ -344,8 +344,8 @@ class Codegen(config: CodegenConfig) {
"headerParams" -> headerParams.toList, "headerParams" -> headerParams.toList,
"requiredParams" -> requiredParams.toList, "requiredParams" -> requiredParams.toList,
"errorList" -> errorList, "errorList" -> errorList,
"httpMethod" -> operation.httpMethod.toUpperCase, "httpMethod" -> operation.method.toUpperCase,
operation.httpMethod.toLowerCase -> "true") operation.method.toLowerCase -> "true")
if (requiredParams.size > 0) properties += "requiredParamCount" -> requiredParams.size.toString if (requiredParams.size > 0) properties += "requiredParamCount" -> requiredParams.size.toString
operation.responseClass.indexOf("[") match { operation.responseClass.indexOf("[") match {
case -1 => { case -1 => {

View File

@ -19,9 +19,7 @@ package com.wordnik.swagger.codegen
trait PathUtil { trait PathUtil {
def getResourcePath(host: String) = { def getResourcePath(host: String) = {
System.getProperty("fileMap") match { System.getProperty("fileMap") match {
case s: String => { case s: String => s
s + "/resources.json"
}
case _ => host case _ => host
} }
} }

View File

@ -24,7 +24,7 @@ import scala.collection.JavaConversions._
object Validator extends PathUtil { object Validator extends PathUtil {
def main(args: Array[String]) { def main(args: Array[String]) {
if(args.length == 0) { if(args.length == 0) {
throw new RuntimeException("Need url to resources.json as argument. You can also specify VM Argument -DfileMap=/path/to/folder/containing.resources.json/") throw new RuntimeException("Need url to Resource Listing as argument. You can also specify VM Argument -DfileMap=/path/to/resourceListing")
} }
val host = args(0) val host = args(0)
val apiKey = { val apiKey = {

View File

@ -19,7 +19,7 @@ object SwaggerSerializers {
new AllowableValuesSerializer + new AllowableValuesSerializer +
new ParameterSerializer + new ParameterSerializer +
new OperationSerializer + new OperationSerializer +
new ErrorResponseSerializer + new ResponseMessageSerializer +
new ApiDescriptionSerializer + new ApiDescriptionSerializer +
new ApiListingReferenceSerializer + new ApiListingReferenceSerializer +
new ResourceListingSerializer + new ResourceListingSerializer +
@ -52,8 +52,14 @@ object SwaggerSerializers {
!!(json, RESOURCE, "resourcePath", "missing recommended field", WARNING) !!(json, RESOURCE, "resourcePath", "missing recommended field", WARNING)
"" ""
}), }),
(json \ "produces").extract[List[String]],
(json \ "consumes").extract[List[String]],
(json \ "protocols").extract[List[String]],
(json \ "authorizations").extract[List[String]],
(json \ "apis").extract[List[ApiDescription]], (json \ "apis").extract[List[ApiDescription]],
(json \ "models").extractOpt[Map[String, Model]] (json \ "models").extractOpt[Map[String, Model]],
(json \ "description").extractOpt[String],
(json \ "position").extractOrElse(0)
) )
}, { }, {
case x: ApiListing => case x: ApiListing =>
@ -117,7 +123,7 @@ object SwaggerSerializers {
!!(json, RESOURCE, "path", "missing required field", ERROR) !!(json, RESOURCE, "path", "missing required field", ERROR)
"" ""
}), }),
(json \ "description").extractOrElse("") (json \ "description").extractOpt[String]
) )
}, { }, {
case x: ApiListingReference => case x: ApiListingReference =>
@ -135,7 +141,7 @@ object SwaggerSerializers {
!!(json, RESOURCE_LISTING, "path", "missing required field", ERROR) !!(json, RESOURCE_LISTING, "path", "missing required field", ERROR)
"" ""
}), }),
(json \ "description").extractOrElse(""), (json \ "description").extractOpt[String],
(json \ "operations").extract[List[Operation]] (json \ "operations").extract[List[Operation]]
) )
}, { }, {
@ -152,30 +158,37 @@ object SwaggerSerializers {
} }
)) ))
class ErrorResponseSerializer extends CustomSerializer[ErrorResponse](formats => ({ class ResponseMessageSerializer extends CustomSerializer[ResponseMessage](formats => ({
case json => case json =>
implicit val fmts: Formats = formats implicit val fmts: Formats = formats
ErrorResponse( ResponseMessage(
(json \ "code").extractOrElse({ (json \ "code").extractOrElse({
!!(json, ERROR, "code", "missing required field", ERROR) !!(json, ERROR, "code", "missing required field", ERROR)
0 0
}), }),
(json \ "message").extractOrElse({
(json \ "reason").extractOrElse({ (json \ "reason").extractOrElse({
!!(json, ERROR, "reason", "missing required field", ERROR) !!(json, ERROR, "reason", "missing required field", ERROR)
"" ""
}) })
})
) )
}, { }, {
case x: ErrorResponse => case x: ResponseMessage =>
implicit val fmts = formats implicit val fmts = formats
("code" -> x.code) ~ ("code" -> x.code) ~
("reason" -> x.reason) ("message" -> x.message)
} }
)) ))
class OperationSerializer extends CustomSerializer[Operation](formats => ({ class OperationSerializer extends CustomSerializer[Operation](formats => ({
case json => case json =>
implicit val fmts: Formats = formats implicit val fmts: Formats = formats
val responses = ((json \ "responseMessages").extract[List[ResponseMessage]]) match {
case e: List[ResponseMessage] if (e.size > 0) => e
case _ => (json \ "errorResponses").extract[List[ResponseMessage]]
}
Operation( Operation(
(json \ "httpMethod").extractOrElse( (json \ "httpMethod").extractOrElse(
(json \ "method").extractOrElse({ (json \ "method").extractOrElse({
@ -193,22 +206,27 @@ object SwaggerSerializers {
!!(json, OPERATION, "nickname", "missing required field", ERROR) !!(json, OPERATION, "nickname", "missing required field", ERROR)
"" ""
}), }),
(json \ "position").extractOrElse(0),
(json \ "produces").extract[List[String]],
(json \ "consumes").extract[List[String]],
(json \ "protocols").extract[List[String]],
(json \ "authorizations").extract[List[String]],
(json \ "parameters").extract[List[Parameter]], (json \ "parameters").extract[List[Parameter]],
(json \ "errorResponses").extract[List[ErrorResponse]], responses,
(json \ "deprecated").extractOpt[String] (json \ "deprecated").extractOpt[String]
) )
}, { }, {
case x: Operation => case x: Operation =>
implicit val fmts = formats implicit val fmts = formats
("method" -> x.httpMethod) ~ ("method" -> x.method) ~
("summary" -> x.summary) ~ ("summary" -> x.summary) ~
("notes" -> x.notes) ~ ("notes" -> x.notes) ~
("responseClass" -> x.responseClass) ~ ("responseClass" -> x.responseClass) ~
("nickname" -> x.nickname) ~ ("nickname" -> x.nickname) ~
("parameters" -> Extraction.decompose(x.parameters)) ~ ("parameters" -> Extraction.decompose(x.parameters)) ~
("errorResponses" -> { ("responseMessages" -> {
x.errorResponses match { x.responseMessages match {
case e: List[ErrorResponse] if(e.size > 0) => Extraction.decompose(e) case e: List[ResponseMessage] if(e.size > 0) => Extraction.decompose(e)
case _ => JNothing case _ => JNothing
} }
}) ~ }) ~
@ -224,16 +242,13 @@ object SwaggerSerializers {
!!(json, OPERATION_PARAM, "reason", "missing parameter name", WARNING) !!(json, OPERATION_PARAM, "reason", "missing parameter name", WARNING)
"" ""
}), }),
(json \ "description").extractOrElse({ (json \ "description").extractOpt[String],
!!(json, OPERATION_PARAM, "description", "missing recommended field", WARNING)
""
}),
(json \ "defaultValue") match { (json \ "defaultValue") match {
case e:JInt => e.num.toString case e:JInt => Some(e.num.toString)
case e:JBool => e.value.toString case e:JBool => Some(e.value.toString)
case e:JString => e.s case e:JString => Some(e.s)
case e:JDouble => e.num.toString case e:JDouble => Some(e.num.toString)
case _ => "" case _ => None
}, },
(json \ "required") match { (json \ "required") match {
case e:JString => e.s.toBoolean case e:JString => e.s.toBoolean
@ -262,7 +277,7 @@ object SwaggerSerializers {
("dataType" -> x.dataType) ~ ("dataType" -> x.dataType) ~
("allowableValues" -> { ("allowableValues" -> {
x.allowableValues match { x.allowableValues match {
case Any => JNothing // don't serialize when not a concrete type case AnyAllowableValues => JNothing // don't serialize when not a concrete type
case e:AllowableValues => Extraction.decompose(x.allowableValues) case e:AllowableValues => Extraction.decompose(x.allowableValues)
case _ => JNothing case _ => JNothing
} }
@ -290,6 +305,7 @@ object SwaggerSerializers {
"" ""
}), }),
(json \ "name").extractOrElse(""), (json \ "name").extractOrElse(""),
(json \ "id").extractOrElse(""),
output, output,
(json \ "description").extractOpt[String] (json \ "description").extractOpt[String]
) )
@ -312,7 +328,8 @@ object SwaggerSerializers {
implicit val fmts: Formats = formats implicit val fmts: Formats = formats
ModelProperty( ModelProperty(
`type` = (json \ "type").extractOrElse(""), `type` = (json \ "type").extractOrElse(""),
(json \ "required") match { `qualifiedType` = (json \ "type").extractOrElse(""),
required = (json \ "required") match {
case e:JString => e.s.toBoolean case e:JString => e.s.toBoolean
case e:JBool => e.value case e:JBool => e.value
case _ => false case _ => false
@ -334,7 +351,7 @@ object SwaggerSerializers {
("description" -> x.description) ~ ("description" -> x.description) ~
("allowableValues" -> { ("allowableValues" -> {
x.allowableValues match { x.allowableValues match {
case Any => JNothing // don't serialize when not a concrete type case AnyAllowableValues => JNothing // don't serialize when not a concrete type
case e:AllowableValues => Extraction.decompose(x.allowableValues) case e:AllowableValues => Extraction.decompose(x.allowableValues)
case _ => JNothing case _ => JNothing
} }
@ -383,7 +400,7 @@ object SwaggerSerializers {
} }
case JString(x) if x.equalsIgnoreCase("range") => case JString(x) if x.equalsIgnoreCase("range") =>
AllowableRangeValues((json \ "min").extract[String], (json \ "max").extract[String]) AllowableRangeValues((json \ "min").extract[String], (json \ "max").extract[String])
case _ => Any case _ => AnyAllowableValues
} }
}, { }, {
case AllowableListValues(values, "LIST") => case AllowableListValues(values, "LIST") =>

View File

@ -22,66 +22,98 @@ case class ResourceListing(
apiVersion: String, apiVersion: String,
swaggerVersion: String, swaggerVersion: String,
basePath: String, basePath: String,
apis: List[ApiListingReference] = List()) apis: List[ApiListingReference] = List(),
authorizations: List[AuthorizationType] = List(),
info: Option[ApiInfo] = None)
case class ApiListingReference(path:String, description: String) case class ApiInfo(
title: String,
description: String,
termsOfServiceUrl: String,
contact: String,
license: String,
licenseUrl: String)
case class LoginEndpoint(url: String)
case class TokenRequestEndpoint(url: String, clientIdName: String, clientSecretName: String)
case class TokenEndpoint(url: String, tokenName: String)
case class ApiListingReference(path:String, description: Option[String], position: Int = 0)
trait AllowableValues trait AllowableValues
case object Any extends AllowableValues case object AnyAllowableValues extends AllowableValues
case class AllowableListValues (values: List[String] = List(), valueType: String = "LIST") extends AllowableValues case class AllowableListValues (values: List[String] = List(), valueType: String = "LIST") extends AllowableValues
case class AllowableRangeValues(min: String, max: String) extends AllowableValues case class AllowableRangeValues(min: String, max: String) extends AllowableValues
case class Model( case class Model(
var id: String, var id: String,
var name: String, var name: String,
qualifiedType: String,
var properties: LinkedHashMap[String, ModelProperty], var properties: LinkedHashMap[String, ModelProperty],
description: Option[String] = None) description: Option[String] = None,
baseModel: Option[String] = None,
discriminator: Option[String] = None)
case class ModelProperty( case class ModelProperty(
var `type`: String, var `type`: String,
qualifiedType: String,
position: Int = 0,
required: Boolean = false, required: Boolean = false,
description: Option[String] = None, description: Option[String] = None,
allowableValues: AllowableValues = Any, allowableValues: AllowableValues = AnyAllowableValues,
var items: Option[ModelRef] = None) var items: Option[ModelRef] = None)
case class ModelRef( case class ModelRef(
`type`: String, `type`: String,
ref: Option[String] = None) ref: Option[String] = None,
qualifiedType: Option[String] = None)
case class ApiListing ( case class ApiListing (
apiVersion: String, apiVersion: String,
swaggerVersion: String, swaggerVersion: String,
basePath: String, basePath: String,
var resourcePath: String, var resourcePath: String,
var produces: List[String] = List.empty,
var consumes: List[String] = List.empty,
var protocols: List[String] = List.empty,
var authorizations: List[String] = List.empty,
apis: List[ApiDescription] = List(), apis: List[ApiDescription] = List(),
models: Option[Map[String, Model]] = None) models: Option[Map[String, Model]] = None,
description: Option[String] = None,
position: Int = 0)
case class ApiDescription ( case class ApiDescription (
path: String, path: String,
description: String, description: Option[String],
operations: List[Operation] = List()) operations: List[Operation] = List())
case class Operation ( case class Operation (
httpMethod: String, method: String,
summary: String, summary: String,
notes: String, notes: String,
var responseClass: String, var responseClass: String,
nickname: String, nickname: String,
position: Int,
var produces: List[String] = List.empty,
var consumes: List[String] = List.empty,
var protocols: List[String] = List.empty,
var authorizations: List[String] = List.empty,
parameters: List[Parameter] = List.empty, parameters: List[Parameter] = List.empty,
errorResponses: List[ErrorResponse] = List.empty, responseMessages: List[ResponseMessage] = List.empty,
`deprecated`: Option[String] = None) `deprecated`: Option[String] = None)
case class Parameter ( case class Parameter (
name: String, name: String,
description: String, description: Option[String],
defaultValue: String, defaultValue: Option[String],
required: Boolean, required: Boolean,
allowMultiple: Boolean, allowMultiple: Boolean,
var dataType: String, var dataType: String,
allowableValues: AllowableValues = Any, allowableValues: AllowableValues = AnyAllowableValues,
paramType: String) paramType: String,
paramAccess: Option[String] = None)
case class ErrorResponse ( case class ResponseMessage (
code: Int, code: Int,
reason: String) message: String,
responseModel: Option[String] = None)

View File

@ -64,12 +64,12 @@ class BasicGeneratorTest extends FlatSpec with ShouldMatchers {
// pick apart the /store/order api // pick apart the /store/order api
val orderApi = operations("/store.{format}/order") val orderApi = operations("/store.{format}/order")
orderApi.httpMethod should be ("POST") orderApi.method should be ("POST")
orderApi.summary should be ("Place an order for a pet") orderApi.summary should be ("Place an order for a pet")
orderApi.responseClass should be ("void") orderApi.responseClass should be ("void")
orderApi.nickname should be ("placeOrder") orderApi.nickname should be ("placeOrder")
orderApi.parameters.size should be (1) orderApi.parameters.size should be (1)
orderApi.errorResponses.size should be (1) orderApi.responseMessages.size should be (1)
} }
it should "verify ops are grouped by path correctly" in { it should "verify ops are grouped by path correctly" in {
@ -91,7 +91,7 @@ class BasicGeneratorTest extends FlatSpec with ShouldMatchers {
// 2 operations // 2 operations
orderOperations.size should be (2) orderOperations.size should be (2)
(orderOperations.map(m => m.httpMethod).toSet & Set("GET", "DELETE")).size should be (2) (orderOperations.map(m => m.method).toSet & Set("GET", "DELETE")).size should be (2)
(orderOperations.map(m => m.nickname).toSet & Set("getOrderById", "deleteOrder")).size should be (2) (orderOperations.map(m => m.nickname).toSet & Set("getOrderById", "deleteOrder")).size should be (2)
} }
@ -134,14 +134,15 @@ class BasicGeneratorTest extends FlatSpec with ShouldMatchers {
def sampleModel = { def sampleModel = {
Model( Model(
"SampleObject",
"SampleObject", "SampleObject",
"SampleObject", "SampleObject",
LinkedHashMap( LinkedHashMap(
"stringValue" -> ModelProperty("string"), "stringValue" -> ModelProperty("string", "java.lang.String"),
"intValue" -> ModelProperty("int"), "intValue" -> ModelProperty("int", "int"),
"longValue" -> ModelProperty("long"), "longValue" -> ModelProperty("long", "long"),
"floatValue" -> ModelProperty("float"), "floatValue" -> ModelProperty("float", "float"),
"doubleValue" -> ModelProperty("double")), "doubleValue" -> ModelProperty("double", "double")),
Some("a sample object")) Some("a sample object"))
} }
} }

View File

@ -100,7 +100,7 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
"double" -> ("Double", "null"), "double" -> ("Double", "null"),
"object" -> ("Object", "null")) "object" -> ("Object", "null"))
expected.map(e => { expected.map(e => {
val model = ModelProperty(e._1) val model = ModelProperty(e._1, "nothing")
config.toDeclaration(model) should be (e._2) config.toDeclaration(model) should be (e._2)
}) })
} }
@ -128,7 +128,8 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of strings" in { it should "create a declaration with a List of strings" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "string"))) items=Some(ModelRef(`type`= "string")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List<String>") m._1 should be ("List<String>")
@ -140,7 +141,8 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of ints" in { it should "create a declaration with a List of ints" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "int"))) items=Some(ModelRef(`type`= "int")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List<Integer>") m._1 should be ("List<Integer>")
@ -152,7 +154,8 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of floats" in { it should "create a declaration with a List of floats" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "float"))) items=Some(ModelRef(`type`= "float")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List<Float>") m._1 should be ("List<Float>")
@ -164,7 +167,8 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of doubles" in { it should "create a declaration with a List of doubles" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "double"))) items=Some(ModelRef(`type`= "double")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List<Double>") m._1 should be ("List<Double>")
@ -176,7 +180,8 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of complex objects" in { it should "create a declaration with a List of complex objects" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "User"))) items=Some(ModelRef(`type`= "User")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List<User>") m._1 should be ("List<User>")

View File

@ -100,7 +100,7 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
"double" -> ("NSNumber*", "null"), "double" -> ("NSNumber*", "null"),
"object" -> ("NSObject*", "null")) "object" -> ("NSObject*", "null"))
expected.map(e => { expected.map(e => {
val model = ModelProperty(e._1) val model = ModelProperty(e._1, "nothing")
config.toDeclaration(model) should be (e._2) config.toDeclaration(model) should be (e._2)
}) })
} }
@ -125,7 +125,8 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of strings" in { it should "create a declaration with a List of strings" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "string"))) items=Some(ModelRef(`type`= "string")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("NSArray*") m._1 should be ("NSArray*")
@ -137,7 +138,8 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of ints" in { it should "create a declaration with a List of ints" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "int"))) items=Some(ModelRef(`type`= "int")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("NSArray*") m._1 should be ("NSArray*")
@ -149,7 +151,8 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of floats" in { it should "create a declaration with a List of floats" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "float"))) items=Some(ModelRef(`type`= "float")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("NSArray*") m._1 should be ("NSArray*")
@ -161,7 +164,8 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of doubles" in { it should "create a declaration with a List of doubles" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "double"))) items=Some(ModelRef(`type`= "double")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("NSArray*") m._1 should be ("NSArray*")
@ -173,7 +177,8 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of complex objects" in { it should "create a declaration with a List of complex objects" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "User"))) items=Some(ModelRef(`type`= "User")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("NSArray*") m._1 should be ("NSArray*")
@ -187,7 +192,7 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/{petId}").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/{petId}").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
m("path") should be ("http://my.api.com/api") m("path") should be ("http://my.api.com/api")
@ -216,7 +221,7 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
m("path") should be ("http://my.api.com/api") m("path") should be ("http://my.api.com/api")
@ -252,7 +257,7 @@ class BasicObjcGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
val allModels = new HashMap[String, Model] val allModels = new HashMap[String, Model]

View File

@ -100,7 +100,7 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
"double" -> ("Double", "0.0"), "double" -> ("Double", "0.0"),
"object" -> ("Any", "_")) "object" -> ("Any", "_"))
expected.map(e => { expected.map(e => {
val model = ModelProperty(e._1) val model = ModelProperty(e._1, "nothing")
config.toDeclaration(model) should be (e._2) config.toDeclaration(model) should be (e._2)
}) })
} }
@ -125,7 +125,8 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of strings" in { it should "create a declaration with a List of strings" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "string"))) items=Some(ModelRef(`type`= "string")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List[String]") m._1 should be ("List[String]")
@ -137,7 +138,8 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of ints" in { it should "create a declaration with a List of ints" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "int"))) items=Some(ModelRef(`type`= "int")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List[Int]") m._1 should be ("List[Int]")
@ -149,7 +151,8 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of floats" in { it should "create a declaration with a List of floats" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "float"))) items=Some(ModelRef(`type`= "float")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List[Float]") m._1 should be ("List[Float]")
@ -161,7 +164,8 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of doubles" in { it should "create a declaration with a List of doubles" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "nothing",
items=Some(ModelRef(`type`= "double"))) items=Some(ModelRef(`type`= "double")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List[Double]") m._1 should be ("List[Double]")
@ -173,7 +177,8 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
*/ */
it should "create a declaration with a List of complex objects" in { it should "create a declaration with a List of complex objects" in {
val property = ModelProperty( val property = ModelProperty(
"Array", `type` = "Array",
qualifiedType = "Array",
items = Some(ModelRef(`type`= "User"))) items = Some(ModelRef(`type`= "User")))
val m = config.toDeclaration(property) val m = config.toDeclaration(property)
m._1 should be ("List[User]") m._1 should be ("List[User]")
@ -187,7 +192,7 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
m("path") should be ("http://my.api.com/api") m("path") should be ("http://my.api.com/api")
@ -222,7 +227,7 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByStatus").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByStatus").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
m("path") should be ("http://my.api.com/api") m("path") should be ("http://my.api.com/api")
@ -262,7 +267,7 @@ class BasicScalaGeneratorTest extends FlatSpec with ShouldMatchers {
val petApi = apis.filter(doc => doc.resourcePath == "/pet").head val petApi = apis.filter(doc => doc.resourcePath == "/pet").head
val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head
val operation = endpoint.operations.filter(op => op.httpMethod == "GET").head val operation = endpoint.operations.filter(op => op.method == "GET").head
val m = codegen.apiToMap("http://my.api.com/api", operation) val m = codegen.apiToMap("http://my.api.com/api", operation)
val allModels = new HashMap[String, Model] val allModels = new HashMap[String, Model]

View File

@ -83,7 +83,7 @@ class ApiListingReferenceValidationTest extends FlatSpec with ShouldMatchers {
""" """
parse(jsonString).extract[ApiListingReference] match { parse(jsonString).extract[ApiListingReference] match {
case p: ApiListingReference => { case p: ApiListingReference => {
p.description should be ("the description") p.description should be (Some("the description"))
} }
case _ => fail("wrong type returned, should be ApiListingReference") case _ => fail("wrong type returned, should be ApiListingReference")
} }
@ -91,7 +91,7 @@ class ApiListingReferenceValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize an ApiListingReference" in { it should "serialize an ApiListingReference" in {
val l = ApiListingReference("/foo/bar", "the description") val l = ApiListingReference("/foo/bar", Some("the description"))
write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") write(l) should be ("""{"path":"/foo/bar","description":"the description"}""")
} }
} }
@ -183,36 +183,41 @@ class OperationValidationTest extends FlatSpec with ShouldMatchers {
"the notes", "the notes",
"string", "string",
"getMeSomeStrings", "getMeSomeStrings",
List(Parameter("id", "the id", "-1", false, true, "string", AllowableListValues(List("a","b","c")), "query")) 0,
List.empty,
List.empty,
List.empty,
List.empty,
List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query"))
) )
write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""") write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""")
} }
} }
@RunWith(classOf[JUnitRunner]) @RunWith(classOf[JUnitRunner])
class ErrorResponseValidationTest extends FlatSpec with ShouldMatchers { class ResponseMessageValidationTest extends FlatSpec with ShouldMatchers {
implicit val formats = SwaggerSerializers.formats implicit val formats = SwaggerSerializers.formats
it should "deserialize an ErrorResponse" in { it should "deserialize an ResponseMessage" in {
val jsonString = """ val jsonString = """
{ {
"code":101, "code":101,
"reason":"the reason" "reason":"the message"
} }
""" """
val json = parse(jsonString) val json = parse(jsonString)
json.extract[ErrorResponse] match { json.extract[ResponseMessage] match {
case p: ErrorResponse => { case p: ResponseMessage => {
p.code should be (101) p.code should be (101)
p.reason should be ("the reason") p.message should be ("the message")
} }
case _ => fail("wrong type returned, should be ErrorResponse") case _ => fail("wrong type returned, should be ResponseMessage")
} }
} }
it should "serialize an operation" in { it should "serialize an operation" in {
val l = ErrorResponse(101, "the reason") val l = ResponseMessage(101, "the message")
write(l) should be ("""{"code":101,"reason":"the reason"}""") write(l) should be ("""{"code":101,"message":"the message"}""")
} }
} }
@ -243,8 +248,8 @@ class ParameterValidationTest extends FlatSpec with ShouldMatchers {
json.extract[Parameter] match { json.extract[Parameter] match {
case p: Parameter => { case p: Parameter => {
p.name should be ("includeDuplicates") p.name should be ("includeDuplicates")
p.description should be ("Show duplicate examples from different sources") p.description should be (Some("Show duplicate examples from different sources"))
p.defaultValue should be ("false") p.defaultValue should be (Some("false"))
p.required should be (false) p.required should be (false)
p.allowMultiple should be (false) p.allowMultiple should be (false)
p.dataType should be ("string") p.dataType should be ("string")
@ -270,8 +275,8 @@ class ParameterValidationTest extends FlatSpec with ShouldMatchers {
json.extract[Parameter] match { json.extract[Parameter] match {
case p: Parameter => { case p: Parameter => {
p.name should be ("name") p.name should be ("name")
p.description should be ("description") p.description should be (Some("description"))
p.defaultValue should be ("tony") p.defaultValue should be (Some("tony"))
p.required should be (false) p.required should be (false)
p.allowMultiple should be (true) p.allowMultiple should be (true)
p.dataType should be ("string") p.dataType should be ("string")
@ -282,7 +287,7 @@ class ParameterValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a parameter" in { it should "serialize a parameter" in {
val l = Parameter("name", "description", "tony", false, true, "string", Any, "query") val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query")
write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""") write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""")
} }
} }
@ -359,7 +364,7 @@ class ModelValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model" in { it should "serialize a model" in {
val ref = Model("Foo", "Bar", (LinkedHashMap("s" -> ModelProperty("string", true, Some("a string"))))) val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string")))))
write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""") write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""")
} }
} }
@ -434,7 +439,7 @@ class ModelPropertyValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property with allowable values and ref" in { it should "serialize a model property with allowable values and ref" in {
val p = ModelProperty("string", false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar"))))
write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""") write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""")
} }
@ -466,7 +471,7 @@ class ModelPropertyValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property with allowable values" in { it should "serialize a model property with allowable values" in {
val p = ModelProperty("string", false, Some("nice"), AllowableListValues(List("a","b"))) val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")))
write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""") write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""")
} }
@ -490,7 +495,7 @@ class ModelPropertyValidationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property" in { it should "serialize a model property" in {
val p = ModelProperty("string", false, Some("nice")) val p = ModelProperty("string", "string", 0, false, Some("nice"))
write(p) should be ("""{"type":"string","required":false,"description":"nice"}""") write(p) should be ("""{"type":"string","required":false,"description":"nice"}""")
} }
} }

View File

@ -39,7 +39,7 @@ class ResourceListingSerializersTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize an ApiListingReference with no apis" in { it should "serialize an ApiListingReference with no apis" in {
val l = ApiListingReference("/foo/bar", "the description") val l = ApiListingReference("/foo/bar", Some("the description"))
write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") write(l) should be ("""{"path":"/foo/bar","description":"the description"}""")
} }
@ -73,7 +73,7 @@ class ResourceListingSerializersTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize an ApiListingReference" in { it should "serialize an ApiListingReference" in {
val l = ApiListingReference("/foo/bar", "the description") val l = ApiListingReference("/foo/bar", Some("the description"))
write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") write(l) should be ("""{"path":"/foo/bar","description":"the description"}""")
} }
} }
@ -93,14 +93,14 @@ class ApiListingReferenceSerializersTest extends FlatSpec with ShouldMatchers {
json.extract[ApiListingReference] match { json.extract[ApiListingReference] match {
case p: ApiListingReference => { case p: ApiListingReference => {
p.path should be ("/foo/bar") p.path should be ("/foo/bar")
p.description should be ("the description") p.description should be (Some("the description"))
} }
case _ => fail("wrong type returned, should be ApiListingReference") case _ => fail("wrong type returned, should be ApiListingReference")
} }
} }
it should "serialize an ApiListingReference" in { it should "serialize an ApiListingReference" in {
val l = ApiListingReference("/foo/bar", "the description") val l = ApiListingReference("/foo/bar", Some("the description"))
write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") write(l) should be ("""{"path":"/foo/bar","description":"the description"}""")
} }
} }
@ -120,7 +120,7 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers {
json.extract[ApiDescription] match { json.extract[ApiDescription] match {
case p: ApiDescription => { case p: ApiDescription => {
p.path should be ("/foo/bar") p.path should be ("/foo/bar")
p.description should be ("the description") p.description should be (Some("the description"))
p.operations.size should be (0) p.operations.size should be (0)
} }
case _ => fail("wrong type returned, should be ApiDescription") case _ => fail("wrong type returned, should be ApiDescription")
@ -128,7 +128,7 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize an ApiDescription with no operations" in { it should "serialize an ApiDescription with no operations" in {
val l = ApiDescription("/foo/bar", "the description") val l = ApiDescription("/foo/bar", Some("the description"))
write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") write(l) should be ("""{"path":"/foo/bar","description":"the description"}""")
} }
@ -167,10 +167,10 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers {
json.extract[ApiDescription] match { json.extract[ApiDescription] match {
case p: ApiDescription => { case p: ApiDescription => {
p.path should be ("/foo/bar") p.path should be ("/foo/bar")
p.description should be ("the description") p.description should be (Some("the description"))
p.operations.size should be (1) p.operations.size should be (1)
p.operations.foreach(op => { p.operations.foreach(op => {
op.httpMethod should be ("GET") op.method should be ("GET")
op.summary should be ("the summary") op.summary should be ("the summary")
op.notes should be ("the notes") op.notes should be ("the notes")
op.responseClass should be ("string") op.responseClass should be ("string")
@ -179,8 +179,8 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers {
op.parameters.foreach(m => { op.parameters.foreach(m => {
m.name should be ("id") m.name should be ("id")
m.description should be ("the id") m.description should be (Some("the id"))
m.defaultValue should be ("-1") m.defaultValue should be (Some("-1"))
m.required should be (false) m.required should be (false)
m.allowMultiple should be (true) m.allowMultiple should be (true)
m.dataType should be ("string") m.dataType should be ("string")
@ -195,14 +195,19 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers {
it should "serialize an ApiDescription" in { it should "serialize an ApiDescription" in {
val l = ApiDescription( val l = ApiDescription(
"/foo/bar", "/foo/bar",
"the description", Some("the description"),
List(Operation( List(Operation(
"get", "get",
"the summary", "the summary",
"the notes", "the notes",
"string", "string",
"getMeSomeStrings", "getMeSomeStrings",
List(Parameter("id", "the id", "-1", false, true, "string", AllowableListValues(List("a","b","c")), "query")) 0,
List.empty,
List.empty,
List.empty,
List.empty,
List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query"))
)) ))
) )
write(l) should be ("""{"path":"/foo/bar","description":"the description","operations":[{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}]}""") write(l) should be ("""{"path":"/foo/bar","description":"the description","operations":[{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}]}""")
@ -241,7 +246,7 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers {
val json = parse(jsonString) val json = parse(jsonString)
json.extract[Operation] match { json.extract[Operation] match {
case op: Operation => { case op: Operation => {
op.httpMethod should be ("GET") op.method should be ("GET")
op.summary should be ("the summary") op.summary should be ("the summary")
op.notes should be ("the notes") op.notes should be ("the notes")
op.responseClass should be ("string") op.responseClass should be ("string")
@ -250,8 +255,8 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers {
op.parameters.foreach(m => { op.parameters.foreach(m => {
m.name should be ("id") m.name should be ("id")
m.description should be ("the id") m.description should be (Some("the id"))
m.defaultValue should be ("-1") m.defaultValue should be (Some("-1"))
m.required should be (false) m.required should be (false)
m.allowMultiple should be (true) m.allowMultiple should be (true)
m.dataType should be ("string") m.dataType should be ("string")
@ -269,7 +274,12 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers {
"the notes", "the notes",
"string", "string",
"getMeSomeStrings", "getMeSomeStrings",
List(Parameter("id", "the id", "-1", false, true, "string", AllowableListValues(List("a","b","c")), "query")) 0,
List.empty,
List.empty,
List.empty,
List.empty,
List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query"))
) )
write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""") write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""")
} }
@ -279,26 +289,26 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers {
class ErrorResponseSerializersTest extends FlatSpec with ShouldMatchers { class ErrorResponseSerializersTest extends FlatSpec with ShouldMatchers {
implicit val formats = SwaggerSerializers.formats implicit val formats = SwaggerSerializers.formats
it should "deserialize an ErrorResponse" in { it should "deserialize an ResponseResponse" in {
val jsonString = """ val jsonString = """
{ {
"code":101, "code":101,
"reason":"the reason" "message":"the message"
} }
""" """
val json = parse(jsonString) val json = parse(jsonString)
json.extract[ErrorResponse] match { json.extract[ResponseMessage] match {
case p: ErrorResponse => { case p: ResponseMessage => {
p.code should be (101) p.code should be (101)
p.reason should be ("the reason") p.message should be ("the message")
} }
case _ => fail("wrong type returned, should be ErrorResponse") case _ => fail("wrong type returned, should be ResponseMessage")
} }
} }
it should "serialize an operation" in { it should "serialize an operation" in {
val l = ErrorResponse(101, "the reason") val l = ResponseMessage(101, "the message")
write(l) should be ("""{"code":101,"reason":"the reason"}""") write(l) should be ("""{"code":101,"message":"the message"}""")
} }
} }
@ -329,8 +339,8 @@ class ParameterSerializersTest extends FlatSpec with ShouldMatchers {
json.extract[Parameter] match { json.extract[Parameter] match {
case p: Parameter => { case p: Parameter => {
p.name should be ("includeDuplicates") p.name should be ("includeDuplicates")
p.description should be ("Show duplicate examples from different sources") p.description should be (Some("Show duplicate examples from different sources"))
p.defaultValue should be ("false") p.defaultValue should be (Some("false"))
p.required should be (false) p.required should be (false)
p.allowMultiple should be (false) p.allowMultiple should be (false)
p.dataType should be ("string") p.dataType should be ("string")
@ -356,8 +366,8 @@ class ParameterSerializersTest extends FlatSpec with ShouldMatchers {
json.extract[Parameter] match { json.extract[Parameter] match {
case p: Parameter => { case p: Parameter => {
p.name should be ("name") p.name should be ("name")
p.description should be ("description") p.description should be (Some("description"))
p.defaultValue should be ("tony") p.defaultValue should be (Some("tony"))
p.required should be (false) p.required should be (false)
p.allowMultiple should be (true) p.allowMultiple should be (true)
p.dataType should be ("string") p.dataType should be ("string")
@ -368,7 +378,7 @@ class ParameterSerializersTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a parameter" in { it should "serialize a parameter" in {
val l = Parameter("name", "description", "tony", false, true, "string", Any, "query") val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query")
write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""") write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""")
} }
} }
@ -445,7 +455,7 @@ class ModelSerializationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model" in { it should "serialize a model" in {
val ref = Model("Foo", "Bar", (LinkedHashMap("s" -> ModelProperty("string", true, Some("a string"))))) val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string")))))
write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""") write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""")
} }
} }
@ -520,7 +530,7 @@ class ModelPropertySerializationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property with allowable values and ref" in { it should "serialize a model property with allowable values and ref" in {
val p = ModelProperty("string", false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar"))))
write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""") write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""")
} }
@ -552,7 +562,7 @@ class ModelPropertySerializationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property with allowable values" in { it should "serialize a model property with allowable values" in {
val p = ModelProperty("string", false, Some("nice"), AllowableListValues(List("a","b"))) val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")))
write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""") write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""")
} }
@ -576,7 +586,7 @@ class ModelPropertySerializationTest extends FlatSpec with ShouldMatchers {
} }
it should "serialize a model property" in { it should "serialize a model property" in {
val p = ModelProperty("string", false, Some("nice")) val p = ModelProperty("string", "string", 0, false, Some("nice"))
write(p) should be ("""{"type":"string","required":false,"description":"nice"}""") write(p) should be ("""{"type":"string","required":false,"description":"nice"}""")
} }
} }

View File

@ -44,9 +44,9 @@ class SwaggerModelTest extends FlatSpec with ShouldMatchers {
val apis = listing.apis.map(api => (api.path, api.description)).toMap val apis = listing.apis.map(api => (api.path, api.description)).toMap
apis("/store.{format}") should be ("Operations about store") apis("/store.{format}") should be (Some("Operations about store"))
apis("/pet.{format}") should be ("Operations about pets") apis("/pet.{format}") should be (Some("Operations about pets"))
apis("/user.{format}") should be ("Operations about user") apis("/user.{format}") should be (Some("Operations about user"))
} }
it should "deserialize ApiListing" in { it should "deserialize ApiListing" in {
@ -63,11 +63,11 @@ class SwaggerModelTest extends FlatSpec with ShouldMatchers {
val apiMap = apiListing.apis.map(api => (api.path, api)).toMap val apiMap = apiListing.apis.map(api => (api.path, api)).toMap
val petBaseApi = apiMap("/pet.{format}/{petId}") val petBaseApi = apiMap("/pet.{format}/{petId}")
petBaseApi.description should be ("Operations about pets") petBaseApi.description should be (Some("Operations about pets"))
petBaseApi.operations.size should be (1) petBaseApi.operations.size should be (1)
val getPetById = petBaseApi.operations.head val getPetById = petBaseApi.operations.head
getPetById.httpMethod should be ("GET") getPetById.method should be ("GET")
getPetById.summary should be ("Find pet by ID") getPetById.summary should be ("Find pet by ID")
getPetById.notes should be ("Returns a pet based on ID") getPetById.notes should be ("Returns a pet based on ID")
getPetById.responseClass should be ("Pet") getPetById.responseClass should be ("Pet")
@ -77,14 +77,14 @@ class SwaggerModelTest extends FlatSpec with ShouldMatchers {
val param = getPetById.parameters.head val param = getPetById.parameters.head
param.name should be ("petId") param.name should be ("petId")
param.description should be ("ID of pet that needs to be fetched") param.description should be (Some("ID of pet that needs to be fetched"))
param.paramType should be ("path") param.paramType should be ("path")
param.required should be (true) param.required should be (true)
param.allowMultiple should be (false) param.allowMultiple should be (false)
param.dataType should be ("string") param.dataType should be ("string")
getPetById.errorResponses.size should be (2) getPetById.responseMessages.size should be (2)
val errors = getPetById.errorResponses.map(error => (error.code, error.reason)).toMap val errors = getPetById.responseMessages.map(response => (response.code, response.message)).toMap
errors(400) should be ("Invalid ID supplied") errors(400) should be ("Invalid ID supplied")
errors(404) should be ("Pet not found") errors(404) should be ("Pet not found")
@ -99,7 +99,7 @@ class SwaggerModelTest extends FlatSpec with ShouldMatchers {
val param = findPetsByStatus.parameters.head val param = findPetsByStatus.parameters.head
param.name should be ("status") param.name should be ("status")
param.description should be ("Status values that need to be considered for filter") param.description should be (Some("Status values that need to be considered for filter"))
param.paramType should be ("query") param.paramType should be ("query")
param.required should be (true) param.required should be (true)
param.allowMultiple should be (true) param.allowMultiple should be (true)

View File

@ -58,8 +58,8 @@ class ApiExtractorTest extends FlatSpec with ShouldMatchers {
getOrderById should not be null getOrderById should not be null
getOrderById.httpMethod should be ("GET") getOrderById.method should be ("GET")
getOrderById.parameters.size should be (1) getOrderById.parameters.size should be (1)
getOrderById.errorResponses.size should be (2) getOrderById.responseMessages.size should be (2)
} }
} }