public void ThenTheResponseShouldNotContainALink(string linkRel) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); Resource resource = response.ResultAs <Resource>(); Assert.IsFalse(resource._links.TryGetValue(linkRel, out _)); }
public void ThenTheLocationHeaderShouldBeSet() { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); string locationHeader = response.Headers["Location"]?.First(); Assert.IsNotNull(locationHeader); }
public async Task <bool> ProcessAsync(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; var returnsDescription = await context.MethodInfo.GetXmlDocumentationTagAsync("returns") ?? string.Empty; foreach (Match match in ResponseRegex.Matches(returnsDescription)) { var statusCode = match.Groups["Code"].Value; if (!operation.Responses.TryGetValue(statusCode, out var response)) { response = new SwaggerResponse(); operation.Responses[statusCode] = response; } response.Description = match.Groups["Description"].Value; } await AddInternalErrorResponseAsync(context, operation); CleanupResponses(operation); return(true); }
public Task <SwaggerResponse <ICollection <Ronny> > > GetRonniesAsync() { var ronnies = _ronnyContext.Ronnies.Select(DbRonnyToReadRonny).ToList(); var response = new SwaggerResponse <ICollection <Ronny> >(HttpStatusCode.OK, ronnies); return(Task.FromResult(response)); }
/// <summary>Initializes a new instance of the <see cref="ResponseModel" /> class.</summary> /// <param name="response">The response.</param> /// <param name="clientGeneratorBase">The client generator base.</param> public ResponseModel(KeyValuePair <string, SwaggerResponse> response, ClientGeneratorBase clientGeneratorBase) { _response = response.Value; _clientGeneratorBase = clientGeneratorBase; StatusCode = response.Key; }
private async Task InspectTariffCompareMethod() { SwaggerResponse <ICollection <GetCalculatedTariffModel> > swaggerResponse = null; StringBuilder resultMessage = new StringBuilder(); string currentMethodName = nameof(InspectTariffCompareMethod); decimal testConsumptionValue = 100; var isSuccess = await RunApiMethod(currentMethodName, resultMessage, async() => { swaggerResponse = await _tariffClient.CompareAsync(testConsumptionValue); return(swaggerResponse); }); if (isSuccess) { var isAssertionConfirmed = true; var tariffs = swaggerResponse.Result.ToArray(); isAssertionConfirmed &= string.Equals("Basic electricity tariff", tariffs[0].TariffName); isAssertionConfirmed &= tariffs[0].AnnualCosts == 82; isAssertionConfirmed &= tariffs[0].AnnualConsumption == 100; if (isAssertionConfirmed) { resultMessage.AppendLine($"{currentMethodName} : Passed"); } else { resultMessage.AppendLine($"{currentMethodName} : Failed"); } } _logger.Log(LogLevel.Information, resultMessage.ToString()); }
public async Task <bool> ProcessAsync(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; var returnsDescription = await context.MethodInfo.GetXmlDocumentationTagAsync("returns"); if (!string.IsNullOrWhiteSpace(returnsDescription)) { foreach (Match match in ResponseRegex.Matches(returnsDescription)) { var statusCode = match.Groups["Code"].Value; if (!operation.Responses.TryGetValue(statusCode, out var response)) { response = new SwaggerResponse(); operation.Responses[statusCode] = response; } var description = match.Groups["Description"].Value; if (description.Contains("=>")) { throw new InvalidOperationException("Description not formatted correcly."); } response.Description = description; } } return(true); }
public void ThenTheCacheHeaderShouldBeSetTo(string expectedValue) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); string cacheHeader = response.Headers["Cache-Control"]?.First(); Assert.AreEqual(expectedValue, cacheHeader); }
private SwaggerResponse Create(IApiActionResponseInfo responseInfo) { var response = new SwaggerResponse { Code = responseInfo.StatusCode.ToString(), Description = responseInfo.Description }; if (responseInfo.ResponseData == null) { return(response); } var typeDetails = responseInfo.ResponseData.GetTypeDetails(); var link = "#/definitions/" + _definitionNameProvider.GetDefinitionName(responseInfo.ResponseData); if (typeDetails.IsCollection) { response.Reference = new SwaggerSchemaReferenceLink { Type = SwaggerType.Array, Link = link }; } else { response.Reference = new SwaggerReferenceLink { Link = link }; } return(response); }
/// <summary>Initializes a new instance of the <see cref="ResponseModel" /> class.</summary> /// <param name="response">The response.</param> /// <param name="exceptionSchema">The exception schema.</param> /// <param name="clientGeneratorBase">The client generator base.</param> public ResponseModel(KeyValuePair<string, SwaggerResponse> response, JsonSchema4 exceptionSchema, ClientGeneratorBase clientGeneratorBase) { _response = response.Value; _exceptionSchema = exceptionSchema; _clientGeneratorBase = clientGeneratorBase; StatusCode = response.Key; }
public static void AddResponse(this SwaggerOperation operation, string statusCode, string description, JsonSchema4 schema = null) { var response = new SwaggerResponse { Description = description, Schema = schema }; operation.Responses.Add(statusCode, response); }
/// <summary>Initializes a new instance of the <see cref="ResponseModel" /> class.</summary> /// <param name="response">The response.</param> /// <param name="exceptionSchema">The exception schema.</param> /// <param name="clientGeneratorBase">The client generator base.</param> public ResponseModel(KeyValuePair <string, SwaggerResponse> response, JsonSchema4 exceptionSchema, ClientGeneratorBase clientGeneratorBase) { _response = response.Value; _exceptionSchema = exceptionSchema; _clientGeneratorBase = clientGeneratorBase; StatusCode = response.Key; }
public void ThenEachContentSummaryInTheResponseShouldContainALink(string linkRel) { SwaggerResponse <ContentSummariesResponse> response = this.scenarioContext.GetLastApiResponse <ContentSummariesResponse>(); Assert.IsTrue( response.Result.Summaries.All(x => x._links.ContainsKey(linkRel)), $"Not all content summaries in the response contained the expected link, '{linkRel}'"); }
public void ThenTheETagHeaderShouldBeSet() { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); string etagHeader = response.Headers["ETag"]?.First(); Assert.IsNotNull(etagHeader); Assert.IsNotEmpty(etagHeader); }
private async Task ProcessOperationDescriptionsAsync(IEnumerable <OperationResponseDescription> operationDescriptions, ParameterInfo returnParameter, OperationProcessorContext context, string successResponseDescription) { foreach (var statusCodeGroup in operationDescriptions.GroupBy(r => r.StatusCode)) { var httpStatusCode = statusCodeGroup.Key; var returnType = statusCodeGroup.Select(r => r.ResponseType).FindCommonBaseType(); var description = string.Join("\nor\n", statusCodeGroup.Select(r => r.Description)); var typeDescription = _settings.ReflectionService.GetDescription( returnType, GetParameterAttributes(returnParameter), _settings.DefaultResponseReferenceTypeNullHandling, _settings); var response = new SwaggerResponse { Description = description ?? string.Empty }; if (IsVoidResponse(returnType) == false) { var isNullable = statusCodeGroup.Any(r => r.IsNullable) && typeDescription.IsNullable; response.IsNullableRaw = isNullable; response.ExpectedSchemas = await GenerateExpectedSchemasAsync(statusCodeGroup, context); response.Schema = await context.SchemaGenerator .GenerateWithReferenceAndNullabilityAsync <JsonSchema4>(returnType, null, isNullable, context.SchemaResolver) .ConfigureAwait(false); } context.OperationDescription.Operation.Responses[httpStatusCode] = response; } bool loadDefaultSuccessResponseFromReturnType; if (operationDescriptions.Any()) { // If there are some attributes declared on the controller \ action, only return a default success response // if a 2xx status code isn't already defined and the SwaggerDefaultResponseAttribute is declared. var operationResponses = context.OperationDescription.Operation.Responses; var hasSuccessResponse = operationResponses.Keys.Any(HttpUtilities.IsSuccessStatusCode); loadDefaultSuccessResponseFromReturnType = !hasSuccessResponse && context.MethodInfo.GetCustomAttributes() .Any(a => a.GetType().IsAssignableTo("SwaggerDefaultResponseAttribute", TypeNameStyle.Name)) || context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes() .Any(a => a.GetType().IsAssignableTo("SwaggerDefaultResponseAttribute", TypeNameStyle.Name)); } else { // If there are no attributes declared on the controller \ action, always return a success response loadDefaultSuccessResponseFromReturnType = true; } if (loadDefaultSuccessResponseFromReturnType) { await LoadDefaultSuccessResponseAsync(returnParameter, successResponseDescription, context); } }
public void ThenTheResponseShouldContainALink(string linkRel) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); Resource resource = response.ResultAs <Resource>(); resource._links.TryGetValue(linkRel, out ResourceLink link); Assert.IsNotNull(link, $"Expected the response to contain a link relation called '{linkRel}' but none was found"); }
public void ThenTheETagHeaderShouldBeSetTo(string property) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); string etagHeader = response.Headers["ETag"]?.First(); string expected = SpecHelpers.ParseSpecValue <string>(this.scenarioContext, property); Assert.AreEqual(expected, etagHeader); }
public void ThenTheResponseShouldContainContentSummaries(int expectedCount) { SwaggerResponse <ContentSummariesResponse> response = this.scenarioContext.GetLastApiResponse <ContentSummariesResponse>(); ObservableCollection <ContentSummaryResponse> summaries = response.Result.Summaries; Assert.IsNotNull(summaries); Assert.AreEqual(expectedCount, summaries.Count); }
public void ThenTheResponseShouldContainAnEmbeddedResourceCalled(string linkRel) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); Resource resource = response.ResultAs <Resource>(); resource._embedded.TryGetValue(linkRel, out ResourceEmbeddedResource embeddedResource); Assert.IsNotNull(embeddedResource, $"Expected the response to contain an embedded resource called '{linkRel}' but none was found"); }
public Task WhenIRequestTheContentWithSlugAndIdUsingTheEtagReturnedByThePreviousRequest(string slug, string id) { SwaggerResponse <ContentResponse> lastResponse = this.scenarioContext.GetLastApiResponse <ContentResponse>(); string lastEtag = lastResponse.Headers["ETag"].First(); this.scenarioContext.ClearLastApiResponse(); return(this.RequestContentItemAndStoreResponseAsync(slug, id, lastEtag)); }
private void GenerateResponse(SwaggerOperation operation, ApplicationAPIModel basicModal) { if (operation.Responses.Count > 0 && operation.Responses.Keys.Where(x => x.StartsWith("2")).Count() > 0) { //handling only the first sucess response code need to be improved //as discussed, for now handling response for only success string sucesskey = operation.Responses.Keys.Where(x => x.StartsWith("2")).ElementAt(0); SwaggerResponse response = null; operation.Responses.TryGetValue(sucesskey, out response); if (response != null && response.Schema == null) { if (response.Reference != null && response.Reference is SwaggerResponse) { response = response.Reference; } } if (response.Schema != null) { var schemaObj = response.Schema; if (response.Schema.HasReference && response.Schema.Reference != null) { schemaObj = response.Schema.Reference; } if (basicModal.ContentType == ApplicationAPIUtils.eContentType.XML) { ApplicationAPIModel JsonResponseModel = new ApplicationAPIModel(); var i = GenerateXMLBody(JsonResponseModel, schemaObj); foreach (AppModelParameter currModel in GenerateJsonBody(JsonResponseModel, schemaObj)) { ActReturnValue arv = new ActReturnValue(); arv.ItemName = currModel.ItemName; arv.Path = currModel.XPath; arv.DoNotConsiderAsTemp = true; basicModal.ReturnValues.Add(arv); } } else if (basicModal.ContentType == ApplicationAPIUtils.eContentType.JSon) { ApplicationAPIModel JsonResponseModel = new ApplicationAPIModel(); var i = GenerateJsonBody(JsonResponseModel, schemaObj); foreach (AppModelParameter currModel in GenerateJsonBody(JsonResponseModel, schemaObj)) { ActReturnValue arv = new ActReturnValue(); arv.ItemName = currModel.ItemName; arv.Path = currModel.XPath; arv.DoNotConsiderAsTemp = true; basicModal.ReturnValues.Add(arv); } } } } }
public void ThenTheResponseBodyShouldContentStateMatching(string stateName) { SwaggerResponse <ContentStateResponse> actual = this.scenarioContext.GetLastApiResponse <ContentStateResponse>(); Assert.IsNotNull(actual); Cms.ContentState expectedState = this.scenarioContext.Get <Cms.ContentState>(stateName); ContentSpecHelpers.Compare(expectedState, actual.Result); }
public void ThenTheResponseBodyShouldContainTheContentItem(string itemName) { SwaggerResponse <ContentResponse> actual = this.scenarioContext.GetLastApiResponse <ContentResponse>(); Assert.IsNotNull(actual); Cms.Content expected = this.scenarioContext.Get <Cms.Content>(itemName); ContentSpecHelpers.Compare(expected, actual.Result); }
/// <summary>Initializes a new instance of the <see cref="ResponseModelBase" /> class.</summary> /// <param name="statusCode">The status code.</param> /// <param name="response">The response.</param> /// <param name="isSuccessResponse">Specifies whether this is the success response.</param> /// <param name="exceptionSchema">The exception schema.</param> /// <param name="settings">The settings.</param> /// <param name="generator">The client generator.</param> protected ResponseModelBase(string statusCode, SwaggerResponse response, bool isSuccessResponse, JsonSchema4 exceptionSchema, CodeGeneratorSettingsBase settings, IClientGenerator generator) { _response = response; _exceptionSchema = exceptionSchema; _generator = generator; _settings = settings; IsSuccess = isSuccessResponse; StatusCode = statusCode; }
public void ThenTheEmbeddedResourceCalledShouldMatchTheContentCalled(string linkRel, string expectedKey) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); Resource resource = response.ResultAs <Resource>(); ContentResponse actual = resource.GetEmbeddedDocument <ContentResponse>(linkRel); Cms.Content expected = this.scenarioContext.Get <Cms.Content>(expectedKey); ContentSpecHelpers.Compare(expected, actual); }
/// <summary>Initializes a new instance of the <see cref="ResponseModelBase" /> class.</summary> /// <param name="operationModel">The operation model.</param> /// <param name="statusCode">The status code.</param> /// <param name="response">The response.</param> /// <param name="isPrimarySuccessResponse">Specifies whether this is the success response.</param> /// <param name="exceptionSchema">The exception schema.</param> /// <param name="settings">The settings.</param> /// <param name="generator">The client generator.</param> protected ResponseModelBase(IOperationModel operationModel, string statusCode, SwaggerResponse response, bool isPrimarySuccessResponse, JsonSchema4 exceptionSchema, CodeGeneratorSettingsBase settings, IClientGenerator generator) { _response = response; _exceptionSchema = exceptionSchema; _generator = generator; _settings = settings; _isPrimarySuccessResponse = isPrimarySuccessResponse; _operationModel = operationModel; StatusCode = statusCode; }
public Task WhenIRequestContentHistoryForSlugWithTheContinationTokenFromThePreviousResponse(string slug) { SwaggerResponse <ContentSummariesResponse> previousResponse = this.scenarioContext.GetLastApiResponse <ContentSummariesResponse>(); string continuationToken = previousResponse.Result.ExtractContinuationToken(); // Now stash the summaries themselves so we can verify that the ones we get back when we call using the // continuation token aren't the same. this.scenarioContext.Set(previousResponse.Result.Summaries.ToArray()); return(this.RequestContentHistoryAndStoreResponseAsync(slug, null, continuationToken, null)); }
public void ThenTheResponseShouldHaveAStatusOf(int expectedStatusCode) { if (expectedStatusCode >= 300) { SwaggerException ex = this.scenarioContext.GetLastApiException(); Assert.AreEqual(expectedStatusCode, ex.StatusCode); } else { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); Assert.AreEqual(expectedStatusCode, response.StatusCode); } }
public void ThenTheLocationHeaderShouldMatchTheResponseLink(string linkRel) { SwaggerResponse response = this.scenarioContext.GetLastApiResponse(); string locationHeader = response.Headers["Location"]?.First(); Resource resource = response.ResultAs <Resource>(); ResourceLink link = resource._links[linkRel]; Assert.IsNotNull(link); string selfLinkUrl = (string)link.AdditionalProperties["href"]; Assert.AreEqual(locationHeader, selfLinkUrl); }
public async Task <SwaggerResponse> DeleteRonnyAsync(string ronnyId) { if (Guid.TryParse(ronnyId, out var id)) { var ronny = await _ronnyContext.Ronnies.FindAsync(id); _ronnyContext.Ronnies.Remove(ronny); await _ronnyContext.SaveChangesAsync(); return(new SwaggerResponse(HttpStatusCode.OK)); } else { return(SwaggerResponse <Ronny> .BadRequest("Invalid PK format")); } }
/// <summary>Initializes a new instance of the <see cref="ResponseModelBase" /> class.</summary> /// <param name="operationModel">The operation model.</param> /// <param name="operation">The operation.</param> /// <param name="statusCode">The status code.</param> /// <param name="response">The response.</param> /// <param name="isPrimarySuccessResponse">Specifies whether this is the success response.</param> /// <param name="exceptionSchema">The exception schema.</param> /// <param name="resolver">The resolver.</param> /// <param name="settings">The settings.</param> /// <param name="generator">The client generator.</param> protected ResponseModelBase(IOperationModel operationModel, SwaggerOperation operation, string statusCode, SwaggerResponse response, bool isPrimarySuccessResponse, JsonSchema4 exceptionSchema, TypeResolverBase resolver, CodeGeneratorSettingsBase settings, IClientGenerator generator) { _response = response; _exceptionSchema = exceptionSchema; _generator = generator; _settings = settings; _resolver = resolver; _operationModel = operationModel; StatusCode = statusCode; IsPrimarySuccessResponse = isPrimarySuccessResponse; ActualResponseSchema = response.GetActualResponseSchema(operation); }