public void Apply_WhenPassingDictionary_ShouldSetExampleOnRequestSchema() { // Arrange serviceProvider.GetService(typeof(IExamplesProvider <Dictionary <string, object> >)).Returns(new DictionaryAutoRequestExample()); var bodyParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/object" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { bodyParameter } }; var parameterDescriptions = new List <ApiParameterDescription>() { new ApiParameterDescription { Type = typeof(Dictionary <string, object>) } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.DictionaryRequestAttribute), parameterDescriptions); // Act sut.Apply(operation, filterContext); // Assert var actualExample = (JObject)bodyParameter.Schema.Example; actualExample["PropertyInt"].ShouldBe(1); actualExample["PropertyString"].ShouldBe("Some string"); }
public RequestBodyObjectConverterTests() { _validBodyInput = new BodyParameter() { Schema = new Schema { Ref = "#/definitions/BodyType" }, Description = "test description", }; _validSchemaDefinitions = new Dictionary <string, Schema> { { "BodyType", new Schema { Type = "object", Title = "bodyObjectType", Properties = new Dictionary <string, Schema>() { { "uuid", new Schema { Title = "uuid", Format = "string", Type = "string" } }, { "code", new Schema { Title = "code", Format = "string", Type = "string" } } } } } }; _requetBodyBuilderMock = new Mock <IRequestBodyJsonBuilder>(); _requetBodyBuilderMock .Setup(m => m.GetJsonResult(It.IsAny <Schema>(), It.IsAny <IDictionary <string, Schema> >())) .Returns(new JObject()); }
public void Apply_WhenRequestIsANullableEnum_ShouldNotThrowException() { // Arrange serviceProvider.GetService(typeof(IExamplesProvider <Title?>)).Returns(new TitleExample()); var titleParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/Title" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { titleParameter } }; var parameterDescriptions = new List <ApiParameterDescription>() { new ApiParameterDescription { Type = typeof(Title?) } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.RequestTakesANullableEnum), parameterDescriptions); // Act sut.Apply(operation, filterContext); // Assert var actualParameterExample = Enum.Parse(typeof(Title), titleParameter.Schema.Example.ToString()); var expectedExample = new TitleExample().GetExamples().Value; actualParameterExample.ShouldBe(expectedExample); }
public virtual void InitParameterII(ref BodyParameter _parameter) { foreach (Equipment e in equipmentList) { e.InitParameterII(ref _parameter); } }
public void Apply_DoesNotSetRequestExamples_FromMethodAttributes_WhenSwaggerRequestExampleAttributePresent() { // Arrange serviceProvider.GetService(typeof(IExamplesProvider <PersonRequest>)).Returns(new PersonRequestAutoExample()); var personRequestParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/PersonRequest" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { personRequestParameter } }; var parameterDescriptions = new List <ApiParameterDescription>() { new ApiParameterDescription { Type = typeof(PersonRequest) } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerRequestExampleAttribute), parameterDescriptions); // Act sut.Apply(operation, filterContext); // Assert filterContext.SchemaRegistry.Definitions.ShouldNotContainKey("PersonRequest"); personRequestParameter.Schema.Example.ShouldBeNull(); }
public void Apply_SetsRequestExamples_FromMethodAttributes() { // Arrange var personRequestParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/PersonRequest" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { personRequestParameter } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerRequestExampleAttribute)); // Act sut.Apply(operation, filterContext); // Assert var actualSchemaExample = (JObject)filterContext.SchemaRegistry.Definitions["PersonRequest"].Example; var expectedExample = (PersonRequest) new PersonRequestExample().GetExamples(); AssertPersonRequestExampleMatches(actualSchemaExample, expectedExample); var actualParameterExample = (JObject)personRequestParameter.Schema.Example; AssertPersonRequestExampleMatches(actualParameterExample, expectedExample); }
public static BodyParameter AddBodySchema <T>(this BodyParameter bodyParameter, ISwaggerModelCatalog modelCatalog) { var schema = GetSchema <T>(modelCatalog); bodyParameter.Schema = schema; return(bodyParameter); }
public static BodyParameter AddBodySchema(this BodyParameter bodyParameter, Type type, ISwaggerModelCatalog modelCatalog) { var schema = GetSchema(modelCatalog, type, false); bodyParameter.Schema = schema; return(bodyParameter); }
public static void AddExampleToParameter(this BodyParameter parameter, ISchemaRegistry schemaRegistry, string operationId, object example, bool allowMultipleExamples = false, JsonSerializerSettings customJsonSerializerSettings = null) { if (example != null) { parameter.Schema = schemaRegistry.AddExampleToSchemaDefinitions(operationId, example, allowMultipleExamples: allowMultipleExamples, customJsonSerializerSettings: customJsonSerializerSettings); } }
public virtual void Init(RobotCreatInfo info, Vector3 destination) { //init equipment InitEquitments(info); //init the parameter BodyParameter _parameter = DataManager.Instance.GetBodyParameter(info.bodyName.ToString()); InitParameterI(ref _parameter); InitParameterII(ref _parameter); parameter = _parameter; //agent if (_agent == null) { _agent = GetComponent <NavMeshAgent>(); } //init state machine behaviors & navigate agent InitBehaviors(); SetDestination(); _agent.speed = parameter.MoveSpeed; //health TODO: change the health robotHealth.Init(this, parameter.Health, parameter.Power); //effect robotEffect.Init(this); //teamcolor teamColor = info.teamColor; isInit = true; }
public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List <IParameter>(); } var attribute = context .ApiDescription.ActionAttributes() .FirstOrDefault(x => x is SwaggerCertificateContentDescriptor) as SwaggerCertificateContentDescriptor; if (attribute == null) { return; } var parameter = new BodyParameter { Name = attribute.ParameterName, In = "body", Required = attribute.Required, Description = attribute.Description, Schema = new Schema { Type = "string" } }; operation.Parameters.Add(parameter); }
public void Apply_SetsRequestExamples_FromMethodAttributes() { // Arrange serviceProvider.GetService(typeof(IExamplesProvider <PersonRequest>)).Returns(new PersonRequestAutoExample()); var personRequestParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/PersonRequest" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { personRequestParameter } }; var parameterDescriptions = new List <ApiParameterDescription>() { new ApiParameterDescription { Type = typeof(PersonRequest) } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.PersonRequestUnannotated), parameterDescriptions); // Act sut.Apply(operation, filterContext); // Assert var actualSchemaExample = (JObject)filterContext.SchemaRegistry.Definitions["PersonRequest"].Example; var expectedExample = (PersonRequest) new PersonRequestAutoExample().GetExamples(); AssertPersonRequestExampleMatches(actualSchemaExample, expectedExample); }
public void SetRequestExampleForType( Operation operation, ISchemaRegistry schemaRegistry, Type requestType, object example, IContractResolver contractResolver = null, JsonConverter jsonConverter = null) { if (example == null) { return; } var schema = schemaRegistry.GetOrRegister(requestType); var bodyParameters = operation.Parameters.Where(p => p.In == "body").Cast <BodyParameter>(); var bodyParameter = bodyParameters.FirstOrDefault(p => p?.Schema.Ref == schema.Ref || p.Schema?.Items?.Ref == schema.Ref); if (bodyParameter == null) { bodyParameter = new BodyParameter() { In = "body", Name = "body", Schema = schema, Description = "", }; // return; // The type in their [SwaggerRequestExample(typeof(requestType), ...] is not passed to their controller action method } operation.Consumes.Add("application/json"); operation.Parameters.Add(bodyParameter); var serializerSettings = this.jsonSerializerSettings ?? serializerSettingsDuplicator.SerializerSettings(contractResolver, jsonConverter); var formattedExample = jsonFormatter.FormatJson(example, serializerSettings, includeMediaType: false); string name = SchemaDefinitionName(requestType, schema); // Console.Out.WriteLine($" SchemaDefinitionName: {name}"); if (string.IsNullOrEmpty(name)) { return; } // set the example on the object in the schema registry (this is what swagger-ui will display) if (schemaRegistry.Definitions.ContainsKey(name)) { //Console.Out.WriteLine($" Registry contains key"); var definitionToUpdate = schemaRegistry.Definitions[name]; if (definitionToUpdate.Example == null) { definitionToUpdate.Example = formattedExample; } } else { //Console.Out.WriteLine($" Registry does not contain key"); bodyParameter.Schema.Example = formattedExample; // set example on the request paths/parameters/schema/example property } }
public static void WriteOperation(IParseNodeWriter writer, Operation operation) { writer.WriteStartMap(); writer.WriteList("tags", operation.Tags, Tag.WriteRef); writer.WriteStringProperty("summary", operation.Summary); writer.WriteStringProperty("description", operation.Description); writer.WriteObject("externalDocs", operation.ExternalDocs, WriteExternalDocs); writer.WriteStringProperty("operationId", operation.OperationId); var parameters = new List <Parameter>(operation.Parameters); Parameter bodyParameter = null; if (operation.RequestBody != null) { writer.WritePropertyName("consumes"); writer.WriteStartList(); var consumes = operation.RequestBody.Content.Keys.Distinct(); foreach (var mediaType in consumes) { writer.WriteListItem(mediaType, (w, s) => w.WriteValue(s)); } writer.WriteEndList(); // Create bodyParameter bodyParameter = new BodyParameter() { Name = "body", Description = operation.RequestBody.Description, Schema = operation.RequestBody.Content.First().Value.Schema }; // add to parameters parameters.Add(bodyParameter); } var produces = operation.Responses.Where(r => r.Value.Content != null).SelectMany(r => r.Value.Content?.Keys).Distinct(); if (produces.Count() > 0) { writer.WritePropertyName("produces"); writer.WriteStartList(); foreach (var mediaType in produces) { writer.WriteListItem(mediaType, (w, s) => w.WriteValue(s)); } writer.WriteEndList(); } writer.WriteList <Parameter>("parameters", parameters, WriteParameterOrReference); writer.WriteMap <Response>("responses", operation.Responses, WriteResponseOrReference); writer.WriteBoolProperty("deprecated", operation.Deprecated, Operation.DeprecatedDefault); writer.WriteList("security", operation.Security, WriteSecurityRequirement); writer.WriteExtensions(operation.Extensions); writer.WriteEndMap(); }
public void TestLowerEdge() { BodyParameter p1 = new BodyParameter(min: 20.0, max: 300.0, "Weight", "kg"); bool succeeded = p1.SetValueFromString("20.0", out string strErr); Assert.IsTrue(succeeded, "Lower edge test failed to parse correctly"); Assert.IsTrue(strErr.Equals(""), "Error string for lower edge was incorrect"); }
public void TestNullString() { var p1 = new BodyParameter(min: 20.0, max: 200.0, "Weight", "Kg"); string errStr; bool res1 = p1.SetValueFromString("", out errStr); double?v = p1; Assert.IsNull(v, "Empty string value did not return null"); Assert.IsFalse(res1, "Failed to detect empty string"); Assert.IsTrue(errStr.Equals("Please enter a numerical value"), "Error string \"" + errStr + "\" is incorrect for null string:"); }
public void TestUpperEdge() { var p1 = new BodyParameter(min: 20.0, max: 200.0, "Weight", "Kg"); string errStr; bool res1 = p1.SetValueFromString("200.0", out errStr); Assert.IsTrue(res1, "SetValueFromString failed upper edge case"); Assert.IsTrue(p1 == 200.0, "SetValueFromString had wrong value for lower edge case"); Assert.IsTrue(errStr.Equals(""), "Error string incorrect for upper edge"); }
public void TestInvalidString() { var p1 = new BodyParameter(min: 20.0, max: 200.0, "Weight", "Kg"); string errStr; bool res1 = p1.SetValueFromString("12a", out errStr); double?v = p1; Assert.IsNull(v, "Invalid string did not return null"); Assert.IsFalse(res1, "Failed to detect invalid string"); Assert.IsTrue(errStr.Equals("Please enter a numerical value"), "Error string incorrect for invalid string input"); }
public void TestBelowLowerEdge() { var p1 = new BodyParameter(min: 20.0, max: 200.0, "Weight", "Kg"); string errStr; bool res1 = p1.SetValueFromString("19.99", out errStr); double?v = p1; Assert.IsNull(v, "Out of range value did not return null"); Assert.IsFalse(res1, "SetValueFromString failed for value below lower edge"); Assert.IsTrue(errStr.Equals("Weight must be between 20.0 and 200.0Kg"), "Error string incorrect for below lower edge"); }
public string Serialize(BodyParameter bodyParameter) { var savedNamespace = _xmlSerializer.Namespace; _xmlSerializer.Namespace = bodyParameter.XmlNamespace ?? savedNamespace; var result = _xmlSerializer.Serialize(bodyParameter.Value); _xmlSerializer.Namespace = savedNamespace; return(result); }
private ParameterContract BuildParameter(BodyParameter p) { if (p != null) { string type = "string"; if (p.Schema != null && p.Schema.Type != null) { type = p.Schema.Type; } return(ParameterContract.Create(p.Name, type, p.Description, null, p.Required)); } return(null); }
private static Parameter ParseBodyParameter(JToken parameter) { var result = new BodyParameter(); SetCommonParameter(result, parameter); result.Required = parameter["required"]?.Value<bool>() ?? false; result.Schema = ParseSchema(parameter["schema"]); if (result.Schema == null) { result.Schema = new Schema { Type = "string" }; } return result; }
/// <summary> /// The build. /// </summary> /// <returns> /// The <see cref="Parameter"/>. /// </returns> public BodyParameter Build() { if (string.IsNullOrWhiteSpace(this.name)) { throw new RequiredFieldException("Name"); } if (this.schema == null) { throw new RequiredFieldException("Schema"); } var parameter = new BodyParameter { Name = this.name, In = ParameterIn.Body, Description = this.description, Required = true, Schema = this.schema }; return(parameter); }
/// <summary> /// Применяет фильтр для аутентификации. /// </summary> /// <param name="operation"></param> /// <param name="context"></param> public void Apply(Operation operation, OperationFilterContext context) { var authAttribute = context.MethodInfo.GetCustomAttributes <AuthorizeAttribute>() .FirstOrDefault(); if (authAttribute != null) { operation.Parameters = operation.Parameters ?? new List <IParameter>(); var param = new BodyParameter { Name = "Authorization", In = "header", Description = "access token", Required = true, }; param.Extensions.Add("default", "Bearer "); operation.Parameters.Add(param); } }
/// <summary> /// Token input boxes in the header /// </summary> /// <param name="swaggerDoc">The swagger document.</param> /// <param name="context">The swagger document.</param> public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { var tokenParameter = new BodyParameter { Name = "Bearer", Description = "Authorization Token", @In = "header", Required = true }; IList <IDictionary <string, IEnumerable <string> > > security = new List <IDictionary <string, IEnumerable <string> > >(); security.Add(new Dictionary <string, IEnumerable <string> > { { tokenParameter.Name, new string[0] } }); swaggerDoc.Security = security; }
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); IParameter parameter = null; if (jsonObject["in"].ToString() == "body") { parameter = new BodyParameter(); } else { parameter = new NonBodyParameter(); } serializer.Populate(jsonObject.CreateReader(), parameter); return(parameter); }
public void Apply_WhenPassingDictionary_ShouldSetExampleOnRequestSchema() { // Arrange var bodyParameter = new BodyParameter { In = "body", Schema = new Schema { Ref = "#/definitions/object" } }; var operation = new Operation { OperationId = "foobar", Parameters = new[] { bodyParameter } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithDictionarySwaggerRequestExampleAttribute)); // Act sut.Apply(operation, filterContext); // Assert var actualExample = (JObject)bodyParameter.Schema.Example; actualExample["PropertyInt"].ShouldBe(1); actualExample["PropertyString"].ShouldBe("Some string"); }
public PostmanCollectionItem Convert(string path, PostmanHttpMethod method, Operation operation, SwaggerDocument swaggerDoc) { IList <IParameter> parameters = operation.Parameters; if (parameters == null) { parameters = new List <IParameter>(); } PostmanUrl urlObject = this.urlConverter.Convert(path, parameters.ToList(), swaggerDoc.Host, swaggerDoc.BasePath); List <PostmanHeader> headerList = this.headerConverter.Convert(parameters.OfType <NonBodyParameter>().ToList()); BodyParameter bodyParam = parameters.OfType <BodyParameter>().FirstOrDefault(p => p is BodyParameter); PostmanRequestBody body = requestBodyConverter.Convert(bodyParam, parameters.ToList(), swaggerDoc.Definitions); var collectionItem = new PostmanCollectionItem() { Description = new PostmanDescription { Content = operation.Description }, Id = operation.OperationId, Name = path, Request = new PostmanRequest { Method = method, Description = new PostmanDescription { Content = operation.Description ?? "" }, Url = urlObject, Headers = headerList, Body = body } }; return(collectionItem); }
public static BodyParameter AddBodySchema <T>(this BodyParameter bodyParameter, ISwaggerModelCatalog modelCatalog) { return(bodyParameter.AddBodySchema(typeof(T), modelCatalog)); }
public virtual void Init(RobotCreatInfo info , Vector3 destination) { //init equipment InitEquitments(info); //init the parameter BodyParameter _parameter = DataManager.Instance.GetBodyParameter(info.bodyName.ToString()); InitParameterI(ref _parameter); InitParameterII(ref _parameter); parameter = _parameter; //agent if ( _agent == null ) _agent = GetComponent<NavMeshAgent>(); //init state machine behaviors & navigate agent InitBehaviors(); SetDestination(); _agent.speed = parameter.MoveSpeed; //health TODO: change the health robotHealth.Init(this, parameter.Health , parameter.Power); //effect robotEffect.Init(this); //teamcolor teamColor = info.teamColor; isInit = true; }
public PostmanRequestBody Convert(BodyParameter bodyParam, List <IParameter> allParams, IDictionary <string, Schema> swaggerDocDefinitions) { PostmanRequestBody bodyResult = new PostmanRequestBody(); if (bodyParam != null) { bodyResult.Mode = PostmanRequestBodyMode.raw; if (bodyParam.Schema != null) { if (!string.IsNullOrWhiteSpace(bodyParam.Schema.Ref)) { string typeName = bodyParam.Schema.Ref.Replace("#/definitions/", ""); string json = ""; if (swaggerDocDefinitions[typeName] != null) { Schema bodySchema = swaggerDocDefinitions[typeName]; JToken bodyJson = this.jsonRequestBodyBuilder.GetJsonResult(bodySchema, swaggerDocDefinitions); json = bodyJson.ToString(); } bodyResult.Raw = json; } else { // non complex types to the result directly (primitives and array types) JToken bodyJson = this.jsonRequestBodyBuilder.GetJsonResult(bodyParam.Schema, swaggerDocDefinitions); string json = bodyJson.ToString(); bodyResult.Raw = json; } } } var formdataParams = allParams.OfType <NonBodyParameter>() .Where(p => p.In == SwashbuckleParameterTypeConstants.FormData); if (formdataParams.Count() > 0) { bodyResult.Mode = PostmanRequestBodyMode.urlencoded; bodyResult.UrlEncoded = new List <PostmanKeyValuePair>(); } else { bodyResult.Mode = PostmanRequestBodyMode.raw; } foreach (NonBodyParameter p in formdataParams) { object defaultValue = this.defaultValueFactory.GetDefaultValueFromFormat(p.Format, p.Type); string value = (defaultValue != null) ? defaultValue.ToString() : ""; if (p.In == SwashbuckleParameterTypeConstants.FormData) { bodyResult.UrlEncoded.Add(new PostmanKeyValuePair { Description = new PostmanDescription { Content = p.Description }, Disabled = false, Key = p.Name, Value = value }); } } return(bodyResult); }
public virtual void InitParameterII(ref BodyParameter _parameter) { foreach(Equipment e in equipmentList) e.InitParameterII(ref _parameter); }
public string Serialize(BodyParameter bodyParameter) { return(JsonConvert.SerializeObject(bodyParameter.Value, JsonSetting)); }