public async Task ResourceValidationExceptionShouldIncludeExpectedErrors(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string message,
            string errorMessage)
        {
            var expectedErrors = new List <ValidationError> {
                new ValidationError("EntityType", "EntityId", ValidationErrorCode.Invalid, errorMessage)
            };

            var thrownException = new EntityValidationException(code, new ValidationErrorDetails(message, expectedErrors));

            exceptionService.Setup(s => s.Execute()).Throws(thrownException);

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                try
                {
                    await response.HandleErrors();
                }
                catch (EntityValidationException exception)
                {
                    var errors = exception.Event?.ErrorDetails?.Errors;
                    errors.Should().BeEquivalentTo(expectedErrors);
                }
            }
        }
Esempio n. 2
0
        public async Task GetNotFoundTestServerHandlesErrorMessageContainsRequest(
            SampleServerFactory serverFactory,
            string uri)
        {
            using (var server = serverFactory.Create())
            {
                using (var flurlClient = new FlurlClient())
                {
                    flurlClient.Settings.HttpClientFactory =
                        new OwinTestHttpClientFactory(server);

                    flurlClient.BaseUrl = "http://localhost";

                    try
                    {
                        var json = await flurlClient.Request(uri).GetJsonAsync();
                    }
                    catch (FlurlHttpException exception)
                    {
                        var response = exception.Call?.Response;
                        if (response == null)
                        {
                            throw;
                        }

                        var throwException = await Assert.ThrowsAsync <Exception>(() => response.HandleErrors(throwOnUnhandledResponses: false));

                        Assert.True(throwException.Message.Contains("Request"));
                    }
                }
            }
        }
        public async Task ResourceValidationExceptionShouldReturnExpectedCode(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string message,
            string entityType,
            string entityId,
            string errorMessage)
        {
            var expectedErrors = new List <ValidationError> {
                new ValidationError(entityType, entityId, ValidationErrorCode.Invalid, errorMessage)
            };

            var thrownException = new EntityValidationException(new ValidationErrorDetails(message, expectedErrors));

            exceptionService.Setup(s => s.Execute()).Throws(thrownException);

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                try
                {
                    await response.HandleErrors();
                }
                catch (EntityValidationException exception)
                {
                    Assert.Equal("AR422", exception.Event.Code);
                }
            }
        }
Esempio n. 4
0
        public async Task UnauthenticatedExceptionShouldReturn401(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new UnauthenticatedException("Unauthenticated"));
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
            }
        }
Esempio n. 5
0
        public async Task EntityValidationExceptionShouldReturn422(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityValidationException(new ValidationErrorDetails("Validation error")));
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
Esempio n. 6
0
        public async Task UnknownResponseExceptionContainsResponse(
            SampleServerFactory serverFactory)
        {
            using (var server = serverFactory.Create())
            {
                var response = await server.HttpClient.GetAsync("/foo");

                var exception = await Assert.ThrowsAsync <Exception>(() => response.HandleErrors());

                Assert.True(exception.Message.Contains("Response"));
            }
        }
        public async Task DomainValidationExceptionInOwinShouldReturn422(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            DomainValidationException exception)
        {
            exceptionService.Setup(s => s.Execute()).Throws(exception);
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
        public async Task UnauthenticatedResponseShouldThrowUnauthenticatedException(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            UnauthenticatedException exception)
        {
            exceptionService.Setup(s => s.Execute()).Throws(exception);
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                await Assert.ThrowsAsync <UnauthenticatedException>(() => response.HandleErrors());
            }
        }
Esempio n. 9
0
        public async Task EntityCreatePermissionShouldReturn403(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string userId,
            string entityType)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityCreatePermissionException(userId, entityType));
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
            }
        }
Esempio n. 10
0
        public async Task EntityNotFoundExceptionShouldReturn404(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string entityType,
            string entityId)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityNotFoundException(entityType, entityId));
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
Esempio n. 11
0
        public async Task EntityNotFoundExceptionShouldReturnExpectedCode(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            EntityNotFoundException exception)
        {
            exceptionService.Setup(s => s.Execute()).Throws(exception);
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                var apiModel = response.As <ResourceNotFoundApiModel>();
                Assert.Equal("AR404", apiModel.Code);
            }
        }
Esempio n. 12
0
        public async Task EntityNotFoundExceptionShouldReturnResourceIdAsCamelCase(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string entityType)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityNotFoundException(code, entityType, "EntityId"));
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                var apiModel = response.As <ResourceNotFoundApiModel>();
                Assert.Equal("entityId", apiModel.ResourceId);
            }
        }
        public async Task DomainValidationExceptionInWebApiShouldReturn422(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            DomainValidationException exception,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>())).Throws(exception);

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
        public async Task NotFoundExceptionGenericShouldReturn404(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>()))
            .Throws(new EntityNotFoundException <Value>(entityId.ToString()));

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
        public async Task UnauthenticatedExceptionShouldReturn401(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            string entityType,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>()))
            .Throws(new UnauthenticatedException("The user is not authenticated"));

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
            }
        }
        public async Task CreatePermissionExceptionShouldReturn403(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            string userId,
            string entityType,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>()))
            .Throws(new EntityCreatePermissionException(userId, entityType, entityId.ToString()));

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
            }
        }
Esempio n. 17
0
        public async Task ValidationResultShouldReturn422(
            SampleServerFactory serverFactory,
            Mock <IHttpActionResultFactory> actionResultFactory,
            HttpRequestMessage request,
            EntityValidationApiEvent apiEvent)
        {
            var result = new TestAutoResponseResult(request, apiEvent);

            actionResultFactory.Setup(f => f.Create(It.IsAny <HttpRequestMessage>())).Returns(result);

            using (var server = serverFactory.With <IHttpActionResultFactory>(actionResultFactory.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/api/result");

                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
        public async Task PermissionExceptionShouldReturnExpectedMessage(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            string userId,
            string entityType,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>()))
            .Throws(new EntityPermissionException(userId, entityType, entityId.ToString()));

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                var apiModel = response.As <ErrorApiModel>();
                Assert.NotNull(apiModel.Message);
            }
        }
        public async Task EntityValidationExceptionShouldReturnKebabCaseEntityIdWhenConfigured(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string entityType)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityNotFoundException(code, entityType, "EntityId"));
            using (var server = serverFactory
                                .With <IExceptionService>(exceptionService.Object)
                                .With <IAutoResponseExceptionFormatter>(new AutoResponseExceptionFormatter(useCamelCase: false))
                                .Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                var apiModel = response.As <ResourceNotFoundApiModel>();
                Assert.Equal("entity-id", apiModel.ResourceId);
            }
        }
        public async Task EntityValidationExceptionShouldReturnCamelCaseEntityProperty(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string userId,
            string message)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityValidationException(new ValidationErrorDetails(
                                                                                              message, new ValidationError <User>(u => u.UserName, ValidationErrorCode.Invalid))));

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                var apiModel = response.As <ErrorDetailsApiModel <ValidationErrorApiModel> >();
                var error    = apiModel.Errors.First();
                Assert.Equal("userName", error.Field);
            }
        }
        public async Task EntityWithPostFixNameShouldReturnKebabCaseEntityType(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string userId,
            string entityId,
            string message)
        {
            exceptionService.Setup(s => s.Execute()).Throws(new EntityValidationException(new ValidationErrorDetails(
                                                                                              message, new ValidationError <ApiModel>(u => u.Id, ValidationErrorCode.Invalid))));

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                var apiModel = response.As <ErrorDetailsApiModel <ValidationErrorApiModel> >();
                var error    = apiModel.Errors.First();
                Assert.Equal("apiModel", error.Resource);
            }
        }
Esempio n. 22
0
        public async Task OwinExceptionShouldInvokeLogger(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            EntityValidationException exception,
            Mock <IAutoResponseLogger> logger)
        {
            logger.Setup(l => l.LogException(It.IsAny <Exception>())).Returns(Task.FromResult(0));
            exceptionService.Setup(s => s.Execute()).Throws(exception);

            using (var server = serverFactory
                                .With <IExceptionService>(exceptionService.Object)
                                .With <IAutoResponseLogger>(logger.Object)
                                .Create())
            {
                await server.HttpClient.GetAsync("/");

                logger.Verify(l => l.LogException(It.IsAny <Exception>()), Times.Once());
            }
        }
        public async Task ExceptionWithNotIncludeDetailsShouldNotReturnDetails(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            InvalidOperationException exception,
            Mock <ISettingsService> settingsService,
            int entityId)
        {
            settingsService.Setup(s => s.GetIncludeFullDetails()).Returns(false);
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>())).Throws(exception);

            using (var server = serverFactory
                                .With <ISettingsService>(settingsService.Object)
                                .With <IValuesRepository>(valuesRepository.Object)
                                .Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                var content = await response.Content.ReadAsStringAsync();

                var jobject = JObject.Parse(content);
                Assert.Null(jobject.Property("exceptionMessage"));
            }
        }