public DiffControllerTests()
        {
            _mockDiffService  = new Mock <IDiffService>();
            _mockEntryService = new Mock <IEntryService>();

            _objectToTest = new DiffController(_mockEntryService.Object, _mockDiffService.Object);
        }
Exemplo n.º 2
0
        public async Task PostAsync_creates_new_diff()
        {
            // Arrange
            var inputRepository = new Mock <IInputRepository>();
            var diffRepository  = new Mock <IDiffRepository>();
            var eventBus        = new Mock <IRabbitMQEventBus>();

            var controller = new DiffController(
                _logger,
                diffRepository.Object,
                inputRepository.Object,
                _mapper,
                eventBus.Object);

            // Act
            var response = await controller.PostAsync();

            // Assert
            var createdResult = Assert.IsType <CreatedResult>(response);
            var result        = Assert.IsType <DiffViewModel>(createdResult.Value);

            Assert.NotNull(result);
            Assert.NotEqual(Guid.Empty, result.Id);

            diffRepository.Verify(dr =>
                                  dr.AddOneAsync(It.IsAny <Diff>()),
                                  Times.Once
                                  );
        }
Exemplo n.º 3
0
 public void Setup()
 {
     controller      = new DiffController();
     leftRepository  = new LeftRepository();
     rightRepository = new RightRepository();
     diffService     = new DiffService();
 }
Exemplo n.º 4
0
        public async Task GetDiffDataShouldReturnDiffResultWhenAnalysisIsSuccessful()
        {
            // Arrange
            var repositoryMock = new Mock <IDiffRepositoryManager>();

            repositoryMock
            .Setup(r => r.GetById(It.IsAny <int>()))
            .ReturnsAsync(new DiffData());

            var diffAnalyserMock = new Mock <IDiffAnalyser>();

            diffAnalyserMock
            .Setup(d => d.Analyse(It.IsAny <byte[]>(), It.IsAny <byte[]>()))
            .Returns(default(Domain.DiffResult));

            var someValidId = int.MaxValue;

            var diffController = new DiffController(repositoryMock.Object, diffAnalyserMock.Object, _defaultMapperMock.Object);

            // Act
            IHttpActionResult result = await diffController.GetDiffData(someValidId);

            // Assert
            Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult <Models.Diff.DiffResult>));
        }
Exemplo n.º 5
0
        public void Init()
        {
            _dataManagerMock = new Mock <IDataManager>(MockBehavior.Strict);
            _differMock      = new Mock <IDiffer>(MockBehavior.Strict);
            _sut             = new DiffController(_dataManagerMock.Object, _differMock.Object);


            //base64 for image files
            _img2 = "iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADE" +
                    "tGw7AAAABGdBTUEAALGPC/xhBQAAAkFJREFUOBGllT1oFEEUx38zuxf1MGghQiqFCMFCK7" +
                    "WwEez8OBQLQRQLLSxEcpUE/Eij2EqIBIuQws4qIaK9pEgheB6ijVbiaWEhivFj1x3fG5zc7" +
                    "p17l4sDy8x77//+zLw3819DyXAzbE9+ccpAzcGYzCMCTZyjheG5hYVoI4/MJVb+RSH44nCz" +
                    "DKffmMBRF5JqMVq0JPmDsUxGV5g1hiwfLRC7KUaTjEUB7M6D+q2FdDHezFlzka8Bu0qspGnG" +
                    "shx7WwgOMgvRs3gTh0JppFSgx9edrpfUc8C+5AdzYTOe2Nd0wOMHgsLsOJ1OcUx9VruvjSoA8o" +
                    "Ydylt915njjoKsXqle3Y8Oz2D3X4NoQ19SD3DscXfZa6XotZ4ZcZXo4C3icy8xO470hIZgaqhZ" +
                    "vfzB0Ws2W3cRn3xMdHwehnf2gkplGdMd64ta87CjJ4jPv8IeuCE5vvdducqpkaQr0s/x+S3u/" +
                    "VNBFR5bO8uRxP7tw5a2t3zlfn4hW54kezEtlz8tBTpDK5ZoQ76+Tzh7/YDfS1dh5WMp4WrA0Yily" +
                    "PNy986sOjsW7lOTtHkP11rqiJSblQoLxt2nmn7njXRyoCaW0UrjnlTqHLUqGip9ZcBB/EKaSW0n" +
                    "NMffl796qnL5f8Nw09RpKoknVpH2eirSt25mw1xlnNsh3xOroSKteiq/nYchuJZZjy8buz40zo" +
                    "U8XvzdQ6XPq5QISne07dFGaU3D8dsR2Wje6FyrSqmg6NsX4IiIQKKXX+aGv1KXedeZE+w/" +
                    "BTKl4mGKsZwAAAAASUVORK5CYII=";
            _img1 =
                "iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAMAAAAM7l6QAAAAMFBMVEX" +
                "///+NmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmqaNmq" +
                "ZMjrU7AAAAD3RSTlMAoEAQ8LAw0ODAYCBQkHCRjMcEAAAApElEQVR42r3S2w6DIBAE0O4uKDed" +
                "///bZk1aGDC+NOm8GDjZDKivv2STHUASvUOL+CTbOhrQE7Z59lIp2iS4V+YIYK+9JZOq67dRAOjIv" +
                "lGpKY6cABmWBxBGBlCmLmIu23zN3B6mA3efEwsQjE4a+d7jhtBJPdndukKI6/WmD1U9E0C+" +
                "fLFbz6tTWoQnFunOMTV/sHNG10dnZqc/ZHXSNaquP+YNmD0L7UqbR+YAAAAASUVORK5CYII=";
        }
        public async Task ShouldGetMessageResult()
        {
            Guid sessionId = Guid.NewGuid();

            ISessionRepository repository = Substitute.For <ISessionRepository>();

            MessageBuilder leftMessageBuilder = new MessageBuilder().WithData(ApplicationConstants.DefaultData);

            MessageBuilder rightMessageBuilder = new MessageBuilder().WithData(ApplicationConstants.SameSizeDifferentData);

            repository.Get(sessionId.ToString())
            .Returns(new SessionBuilder(sessionId.ToString())
                     .WithLeftSideMessage(leftMessageBuilder)
                     .WithRightSideMessage(rightMessageBuilder)
                     .Build());

            DiffController controller = new DiffController(repository);

            ActionResult result = await controller.Get(sessionId);

            result.ShouldBeAssignableTo <OkObjectResult>();

            ((OkObjectResult)result).Value.ToString().ShouldContain("Differences found starting at 3 ending at 5");
            ((OkObjectResult)result).Value.ToString().ShouldContain("Differences found starting at 66 ending at 68");
        }
Exemplo n.º 7
0
        public void TestInitialize()
        {
            var mockedBus = new Mock <IBus>();

            var mockedMapper = SetupMockMapper();

            var mockedDiffRepo = new Mock <IDiffAnalysisRepository>();

            mockedDiffRepo
            .Setup(x => x.GetAnalysis(It.IsAny <Guid>()))
            .ReturnsAsync((Guid id) =>
            {
                return(GetSampleAnalysis().FirstOrDefault(a => a.Id == id));
            });

            // Mock the Url property of the controller
            var mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelper.Setup(x => x.RouteUrl(It.IsAny <UrlRouteContext>()))
            .Returns("/v1/diff/");

            // Initialize the diff controller used on all tests
            _diffController = new DiffController(mockedBus.Object, mockedMapper.Object, mockedDiffRepo.Object)
            {
                Url = mockUrlHelper.Object
            };
        }
Exemplo n.º 8
0
        public async Task GetDiffDataShouldReturnInternalServerErrorResultWhenExceptionIsThrownInAnalysis()
        {
            // Arrange
            var repositoryMock = new Mock <IDiffRepositoryManager>();

            repositoryMock
            .Setup(r => r.GetById(It.IsAny <int>()))
            .ReturnsAsync(new DiffData());

            var diffAnalyserMock = new Mock <IDiffAnalyser>();

            diffAnalyserMock
            .Setup(d => d.Analyse(It.IsAny <byte[]>(), It.IsAny <byte[]>()))
            .Throws <Exception>();

            var someValidId = int.MaxValue;

            var diffController = new DiffController(repositoryMock.Object, diffAnalyserMock.Object, _defaultMapperMock.Object);

            // Act
            IHttpActionResult result = await diffController.GetDiffData(someValidId);

            // Assert
            Assert.IsInstanceOfType(result, typeof(InternalServerErrorResult));
        }
Exemplo n.º 9
0
        private async Task <IActionResult> PostRight()
        {
            var controller = new DiffController(_mediator.Object);
            var result     = await controller.PostRight(_id, _json);

            _mediator.Verify(_mediatorSendRequest, Times.Exactly(2));
            return(result);
        }
        public DiffControllerTests()
        {
            _payLoadService  = Substitute.For <IPayLoadService>();
            _diffService     = Substitute.For <IDiffService>();
            _responseCreator = Substitute.For <IResponseCreator>();

            _sut = new DiffController(_payLoadService, _diffService, _responseCreator);
        }
Exemplo n.º 11
0
        private async Task Should_request_and_handle_Exception()
        {
            _mediator.Setup(_mediatorSendResultRequest).Throws(new Exception("Id Not found."));
            var controller = new DiffController(_mediator.Object);
            var result     = await controller.Post(_id);

            _mediator.Verify(_mediatorSendResultRequest, Times.Once);
            Assert.True(result is BadRequestObjectResult);
        }
Exemplo n.º 12
0
        public void Initialize()
        {
            IDependencyResolver dependencyResolver = DependencyRegistrations.GetDependencyResolver();

            // While creating the controller for tests we could use a different repository speficic
            // for tests, but here the ideia is use the same for the exercise purposes.
            _diffController = (DiffController)dependencyResolver.GetService(typeof(DiffController));
            _repository     = (IRepository)dependencyResolver.GetService(typeof(IRepository));
            _repository.ClearData();
        }
Exemplo n.º 13
0
        public void leftTest()
        {
            // Arrange
            DiffController controller = new DiffController();

            // Act
            var result = controller.left("AAA");

            // Assert
            Assert.IsNotNull(result);
        }
        public void DiffController_CompareMembers_ShouldReturn_HttpNotFound_NonExistentId()
        {
            var controller = new DiffController(new BinaryDiffService(new BinaryRepository(), new BinaryComparer()));
            int testId     = 1000;

            var actualResult   = controller.CompareMembers(testId).Result as NotFoundResult;
            var expectedResult = new NotFoundResult();

            Assert.IsNotNull(actualResult);
            Assert.AreEqual(expectedResult.StatusCode, actualResult.StatusCode);
        }
Exemplo n.º 15
0
        public void ShouldNotSaveLeft()
        {
            var e = new Entity()
            {
                Id = 700
            };
            var ctrl = new DiffController();
            var res  = ctrl.PostLeft(e.Id, e) as BadRequestObjectResult;

            Assert.AreEqual(400, res.StatusCode);
        }
Exemplo n.º 16
0
        public void rightTest()
        {
            // Arrange
            DiffController controller = new DiffController();

            // Act
            var result = controller.right("XXX");

            // Assert
            Assert.IsNotNull(result);
        }
Exemplo n.º 17
0
        public void IndexTest()
        {
            // Arrange
            DiffController controller = new DiffController();

            // Act
            var result = controller.Index();

            // Assert
            Assert.IsNotNull(result);
        }
Exemplo n.º 18
0
        public void ShouldSaveRight()
        {
            var e = new Entity()
            {
                Id = 600, Right = right
            };
            var ctrl = new DiffController();
            var res  = ctrl.PostRight(e.Id, e) as OkObjectResult;

            Assert.AreEqual(200, res.StatusCode);
        }
Exemplo n.º 19
0
        public async Task GetReturnsNoContentResultWhenReadinessNotReady()
        {
            var service = Substitute.For <IDifferenceService>();

            service.FindDiffAsync(10).Returns(
                Task.FromResult(((DifferenceContent)null, DifferenceReadiness.NotReady)));

            var controller = new DiffController(service);
            var result     = await controller.Get(10);

            result.Should().BeOfType <NoContentResult>();
        }
Exemplo n.º 20
0
        public async Task PostLeftReturnsBadRequestResultWhenModelIsInvalid()
        {
            var service = Substitute.For <IDifferenceService>();

            var controller = new DiffController(service);

            controller.ModelState.AddModelError("error", "some error");

            var result = await controller.PostLeft(10, new SourceContentRequest());

            result.Should().BeOfType <BadRequestResult>();
        }
Exemplo n.º 21
0
        public async Task PostRightDiffDataShouldReturnStatusCodeOkWhenNoErrorsOccurs()
        {
            // Arrange
            var someValidId    = int.MaxValue;
            var diffController = new DiffController(_defaultRepositoryMock.Object, _defaultDiffAnalyserMock.Object, _defaultMapperMock.Object);

            // Act
            IHttpActionResult result = await diffController.PostRightDiffData(someValidId, _validBase64string);

            // Assert
            Assert.IsInstanceOfType(result, typeof(OkResult));
        }
Exemplo n.º 22
0
        public void ShouldGetEntityLeft()
        {
            var e = new Entity()
            {
                Id = 800, Left = left
            };
            var controller = new DiffController();

            controller.PostLeft(e.Id, e);
            var res = controller.GetLeft(e.Id).Value;

            Assert.AreEqual(e.Left, res);
        }
Exemplo n.º 23
0
        public async Task PostLeftReturnsBadRequestResultWhenModelDataIsNotBase64()
        {
            var service = Substitute.For <IDifferenceService>();
            var request = new SourceContentRequest
            {
                Data = "__."
            };

            var controller = new DiffController(service);
            var result     = await controller.PostLeft(10, request);

            result.Should().BeOfType <BadRequestResult>();
        }
Exemplo n.º 24
0
        public void ShouldSaveLeft()
        {
            var e = new Entity()
            {
                Id = 500, Left = left
            };

            e.Id = new Random().Next(20, 30);
            var ctrl = new DiffController();
            var res  = ctrl.PostLeft(e.Id, e) as OkObjectResult;

            Assert.AreEqual(200, res.StatusCode);
        }
Exemplo n.º 25
0
        public void ShouldGetEntityRight()
        {
            var e = new Entity()
            {
                Id = 800, Right = right
            };
            var controller = new DiffController();

            controller.PostRight(e.Id, e);
            var res = controller.GetRight(e.Id).Value;

            Assert.AreEqual(e.Right, res);
        }
Exemplo n.º 26
0
        private async Task Should_request_diff()
        {
            _differResult.Setup(d => d.AreEqual).Returns(true);
            _differResult.Setup(d => d.Id).Returns(_id);
            var mediatrResult = Task.FromResult(_differResult.Object);

            _mediator.Setup(_mediatorSendResultRequest).Returns(mediatrResult);
            var controller = new DiffController(_mediator.Object);
            var result     = await controller.Post(_id);

            _mediator.Verify(_mediatorSendResultRequest, Times.Once);
            Assert.True(result is OkObjectResult okResult &&
                        okResult.Value is IDifferResult diffResult &&
                        diffResult.AreEqual);
        }
        public void DiffController_AddRightMember_ShouldReturn_HttpBadRequest_InvalidBase64String()
        {
            var controller = new DiffController(new BinaryDiffService(new BinaryRepository(), new BinaryComparer()));
            int testId     = 7;

            var response = controller.AddRightMember(testId, new DiffRequest {
                Data = "InvalidBase64String"
            });

            var actualResult   = response as BadRequestResult;
            var expectedResult = new BadRequestResult();

            Assert.IsNotNull(actualResult);
            Assert.AreEqual(expectedResult.StatusCode, actualResult.StatusCode);
        }
Exemplo n.º 28
0
        public void Given_Valid_And_Different_Data_When_Execute_Diff_Then_Should_Return_Differences()
        {
            //Arrange
            var id            = _fixture.Create <string>();
            var base64String  = _fixture.Create <string>();
            var base64String2 = base64String.Replace(base64String.Substring(2, 1), base64String.Substring(4, 1));
            var differences   = _fixture.Build <Result>()
                                .With(x => x.AreEqual, false).With(x => x.AreSameSize, true)
                                .With(x => x.Differences, _fixture.CreateMany <Difference>().ToArray()).Create();

            var diffServiceMock = new Mock <IDiffService>();

            diffServiceMock.Setup(x => x.GetDifferences(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(differences);

            var comparisonServiceMock = new Mock <IComparisonService>();

            comparisonServiceMock.Setup(x => x.Get(It.IsNotNull <string>()))
            .Returns(new Comparison()
            {
                ComparisonId = id, Left = base64String, Right = base64String2
            })
            .Verifiable();

            var controller = new DiffController(diffServiceMock.Object, comparisonServiceMock.Object)
            {
                Request       = new HttpRequestMessage(),
                Configuration = new HttpConfiguration()
            };


            //Act
            var response = controller.Diff(id);


            //Assert
            comparisonServiceMock.Verify(x => x.Get(It.IsNotNull <string>()), Times.Once);
            diffServiceMock.Verify(x => x.GetDifferences(It.IsNotNull <string>(), It.IsNotNull <string>()), Times.Once);
            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Result retVal;

            Assert.IsTrue(response.TryGetContentValue(out retVal));
            Assert.IsTrue(!retVal.AreEqual);
            Assert.IsTrue(retVal.AreSameSize);
            CollectionAssert.AllItemsAreUnique(retVal.Differences);
            Assert.Greater(retVal.Differences.Count, 0);
        }
Exemplo n.º 29
0
        public async Task PostLeftAddsSourceForGivenDiff(int diffId)
        {
            var data    = new byte[] { 1, 2, 3 };
            var service = Substitute.For <IDifferenceService>();
            var request = new SourceContentRequest
            {
                Data = Convert.ToBase64String(data)
            };

            var controller = new DiffController(service);
            var result     = await controller.PostLeft(diffId, request);

            result.Should().BeOfType <OkResult>();
            await service.Received().AddSourceAsync(diffId, Arg.Is <SourceContent>(
                                                        c => c.SourceSide == SourceSide.Left && c.Data.SequenceEqual(data)));
        }
Exemplo n.º 30
0
        public void Init()
        {
            // Arrange
            var mock = new Mock <IDiffRepository>();

            mock.Setup(d => d.GetDiffs()).Returns(new List <Diff>()
            {
                new Diff {
                    DiffId = 1, LeftData = null, RightData = null
                },
                new Diff {
                    DiffId = 2, LeftData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA==", RightData = null
                },
                new Diff {
                    DiffId = 3, LeftData = null, RightData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA=="
                },
                new Diff {
                    DiffId = 4, LeftData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA==", RightData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA=="
                },
                new Diff {
                    DiffId = 5, LeftData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA==", RightData = "TGVwIHBvemRyYXYgMzU1"
                },
                new Diff {
                    DiffId = 6, LeftData = "TGVwIHBvemRyYXYgaXogZGFsamF2IDIzNA==", RightData = "TGVwIG9kemRyYXYgaXogZGFsamF2IDM1NQ=="
                },
                new Diff {
                    DiffId = 7, LeftData = "", RightData = ""
                },
            }
                                                  .AsQueryable());

            _ctrl = new DiffController(mock.Object);

            var config    = new HttpConfiguration();
            var request   = new HttpRequestMessage(HttpMethod.Get, "http://localhost/v1/Diff");
            var route     = config.Routes.MapHttpRoute("Diffs", "v1/{controller}/{diffId}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary
            {
                { "controller", "Diff" },
                { "diffId", @"\d+" }
            });

            _ctrl.ControllerContext = new HttpControllerContext(config, routeData, request);
            _ctrl.Request           = request;
            _ctrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
        }