コード例 #1
0
        public void given_a_request_when_ProcessImageUseCase_ExecuteGet_method_is_called_then_it_returns_the_response_object_of_correct_type_and_data()
        {
            //assert
            var request  = MatProcessDataHelper.CreateGetProcessImageRequestObject();
            var imageKey = ImagePersistingHelper.generateImageKey(request.processType, request.imageId, request.processRef, request.fileExtension);

            var expectedBase64ImageString = MatProcessDataHelper.CreatePostProcessImageRequestObject().base64Image;

            _mockGateway.Setup(g => g.RetrieveImage(It.Is <string>(obj => obj == imageKey))).Returns(expectedBase64ImageString);

            var expectedUsecaseResponse = new GetProcessImageResponse(expectedBase64ImageString, DateTime.Now, request); //The date time is impossible to test equality for, as it will differ in few microseconds from the actual response one. So I set it to DateTime.Min to signify its unimportance.

            //act
            var usecaseResponse = _processImageUseCase.ExecuteGet(request);

            //assert
            Assert.IsNotNull(usecaseResponse);
            Assert.IsInstanceOf <GetProcessImageResponse>(usecaseResponse);

            Assert.AreEqual(expectedUsecaseResponse.Base64Image, usecaseResponse.Base64Image);
            Assert.AreEqual(expectedUsecaseResponse.Request.processRef, usecaseResponse.Request.processRef);
            Assert.AreEqual(expectedUsecaseResponse.Request.imageId, usecaseResponse.Request.imageId);

            //This assertion has an accuracy of 1 second. If time difference between [when expected object was created] and [when actual usecase response was created] is within 1 second, then the times are considered equal. 1 Second is plenty of time for the code in between to run, considering it's using a Mock gateway.
            Assert.Less((usecaseResponse.GeneratedAt - expectedUsecaseResponse.GeneratedAt).TotalMilliseconds, 1000);
        }
コード例 #2
0
        public void given_failed_request_validation_when_GetProcessImage_controller_method_is_called_then_it_makes_the_logger_log_the_correctly_formatted_validation_failure_messages_returned_by_the_validator()
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject(); //doesn't matter that it's valid right now, because validation failure is built up manually anyway. This object is needs values set so that logger message could be checked.

            int errorCount          = _faker.Random.Int(1, 10);                      //simulate from 1 to 10 validation errors (triangulation).
            var validationErrorList = new List <ValidationFailure>();                //this list will be used as constructor argument for 'ValidationResult'.

            for (int i = errorCount; i > 0; i--)
            {
                validationErrorList.Add(new ValidationFailure(_faker.Random.Word(), _faker.Random.Word()));
            }                                                                        //generate from 1 to 10 fake validation errors. Single line for-loop so that it wouldn't distract from what's key in this test.

            var fakeValidationResult = new FV.ValidationResult(validationErrorList); //Need to create ValidationResult so that I could setup Validator mock to return it upon '.Validate()' call. Also this is the only place where it's possible to manipulate the validation result - You can only make the validation result invalid by inserting a list of validation errors as a parameter through a constructor. The boolean '.IsValid' comes from expression 'IsValid => Errors.Count == 0;', so it can't be set manually.

            _mockGetValidator.Setup(v => v.Validate(It.IsAny <GetProcessImageRequest>())).Returns(fakeValidationResult);

            string expectedValidationErrorMessages = fakeValidationResult.Errors
                                                     .Select(e => $"Validation error for: '{e.PropertyName}', message: '{e.ErrorMessage}'.")
                                                     .Aggregate((acc, m) => acc + "\n" + m);
            string expectedLogMessage = $"Get ProcessImage request for Process Type: {request.processType}, Process Reference: {request.processRef}, Image Id: {request.imageId} and File Extension: {request.fileExtension} did not pass the validation:\n\n{expectedValidationErrorMessages}";

            //act
            _processImageController.GetProcessImage(request);

            //assert
            _mockLogger.Verify(l => l.Log(
                                   LogLevel.Information,
                                   It.IsAny <EventId>(),
                                   It.Is <FormattedLogValues>(v => v.ToString().Contains(expectedLogMessage)),
                                   It.IsAny <Exception>(),
                                   It.IsAny <Func <object, Exception, string> >()
                                   ), Times.Once);
        }
コード例 #3
0
        public void given_successful_request_validation_when_GetProcessImage_controller_method_is_called_then_it_returns_an_Ok_result_with_correct_data_based_of_that_request()
        {
            //arrange
            var request          = MatProcessDataHelper.CreateGetProcessImageRequestObject();
            var expectedResponse = new GetProcessImageResponse(_faker.Random.Hash().ToString(), DateTime.Now, request);

            _mockUsecase.Setup(u => u.ExecuteGet(It.IsAny <GetProcessImageRequest>())).Returns(expectedResponse);
            _mockGetValidator.Setup(x => x.Validate(It.IsAny <GetProcessImageRequest>())).Returns(new FV.ValidationResult()); //setup validator to return a no error validation result

            //act
            var controllerResponse = _processImageController.GetProcessImage(request);
            var result             = controllerResponse as ObjectResult;
            var resultContents     = result.Value as GetProcessImageResponse;

            //assert
            Assert.NotNull(controllerResponse);
            Assert.IsInstanceOf <OkObjectResult>(result);
            Assert.NotNull(result);
            Assert.IsInstanceOf <GetProcessImageResponse>(resultContents);
            Assert.NotNull(resultContents);

            Assert.AreEqual(expectedResponse.Base64Image, resultContents.Base64Image);
            Assert.AreEqual(expectedResponse.GeneratedAt, resultContents.GeneratedAt);
            Assert.AreEqual(expectedResponse.Request.processRef, resultContents.Request.processRef);
            Assert.AreEqual(expectedResponse.Request.imageId, resultContents.Request.imageId);
        }
        public void given_a_request_with_valid_ImageId_guid_when_getProcessImageRequestValidator_is_called_then_it_returns_no_error()
        {
            //arange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            //act, assert
            _getValidator.ShouldNotHaveValidationErrorFor(req => req.imageId, request);
        }
        public void given_a_request_with_empty_or_whitespace_imageId_when_getProcessImageRequestValidator_is_called_then_it_returns_an_error(string imageId)
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            request.imageId = imageId;

            //act, assert
            _getValidator.ShouldHaveValidationErrorFor(req => req.imageId, request).WithErrorMessage("Image Id must not be empty.");
        }
        public void given_a_request_with_empty_or_whitespace_processRef_when_getProcessImageRequestValidator_is_called_then_it_returns_an_error(string processRef)
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            request.processRef = processRef;

            //act, assert
            _getValidator.ShouldHaveValidationErrorFor(req => req.processRef, request).WithErrorMessage("Process reference must not be empty.");
        }
        public void given_a_request_with_null_fileExtension_when_getProcessImageRequestValidator_is_called_then_it_returns_an_error()
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            request.fileExtension = null;

            //act, assert
            _getValidator.ShouldHaveValidationErrorFor(req => req.fileExtension, request).WithErrorMessage("File Extension must be provided.");
        }
        [TestCase("ju5t70m3-w0rd-th4t-w1ll-m34nn0th1ng0")] //uses characters that are not among hexadecimal numerals
        public void given_a_request_with_invalid_ImageId_guid_when_getProcessImageRequestValidator_is_called_then_it_returns_an_error(string imageId)
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            request.imageId = imageId;

            //act, assert
            _getValidator.ShouldHaveValidationErrorFor(req => req.imageId, request).WithErrorMessage("You need to provide a valid Image Id.");
        }
コード例 #9
0
        public void given_a_request_when_ProcessImageUseCase_ExecuteGet_method_is_called_then_it_calls_the_gateway_with_imageKey_generated_based_on_the_request()
        {
            //assert
            var request  = MatProcessDataHelper.CreateGetProcessImageRequestObject();
            var imageKey = ImagePersistingHelper.generateImageKey(request.processType, request.imageId, request.processRef, request.fileExtension);

            //act
            _processImageUseCase.ExecuteGet(request);

            //assert
            _mockGateway.Verify(g => g.RetrieveImage(It.Is <string>(obj => obj == imageKey)), Times.Once);
        }
コード例 #10
0
        public void given_a_request_object_when_GetProcessImage_controller_method_is_called_then_it_calls_the_validator_with_that_request_object()
        {
            //arrange
            var request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            _mockGetValidator.Setup(x => x.Validate(It.IsAny <GetProcessImageRequest>())).Returns(new FV.ValidationResult()); //setup validator to return a no error validation result

            //act
            _processImageController.GetProcessImage(request);

            //assert
            _mockGetValidator.Verify(v => v.Validate(It.Is <GetProcessImageRequest>(obj => obj == request)), Times.Once);
        }
コード例 #11
0
        public void given_successful_request_validation_when_GetProcessImage_controller_method_is_called_then_it_calls_usecase_with_correct_data_based_of_request()
        {
            //arrange
            GetProcessImageRequest request = MatProcessDataHelper.CreateGetProcessImageRequestObject();

            _mockGetValidator.Setup(x => x.Validate(It.IsAny <GetProcessImageRequest>())).Returns(new FV.ValidationResult()); //setup validator to return a no error validation result

            //act
            _processImageController.GetProcessImage(request);

            //assert
            _mockUsecase.Verify(u => u.ExecuteGet(It.Is <GetProcessImageRequest>(obj =>
                                                                                 obj.processRef == request.processRef &&
                                                                                 obj.imageId == request.imageId
                                                                                 )), Times.Once);
        }
コード例 #12
0
        public void given_a_request_when_GetProcessImage_controller_method_is_called_then_it_makes_the_logger_log_the_information_about_the_request_regardless_of_the_validator_behaviour()  //Since there's no validator setup, it returns no validation result, which will make the flow crash. If the Verify bit shows that logger was called under these conditions, then this shows that validation result or behaviour has no influence on logger being called at least once, which is important if you want to register that request happened regardless of the validity of the request.
        {
            //arrange
            var    request            = MatProcessDataHelper.CreateGetProcessImageRequestObject();
            string expectedLogMessage = $"Get ProcessImage request for Process Type: {request.processType}, Process Reference: {request.processRef}, Image Id: {request.imageId} and File Extension: {request.fileExtension}";

            //act
            try { _processImageController.GetProcessImage(request); } catch (Exception ex) { } //the empty try-catch is needed to ignore the exception being thrown due to absense of validation result returned later down the line. The idea is that logger is the first thing that is being called once request comes in.

            //assert
            _mockLogger.Verify(l => l.Log(
                                   LogLevel.Information,
                                   It.IsAny <EventId>(),
                                   It.Is <FormattedLogValues>(v => v.ToString().Contains(expectedLogMessage)),
                                   It.IsAny <Exception>(),
                                   It.IsAny <Func <object, Exception, string> >()
                                   ), Times.AtLeastOnce);
        }