public void ValidateUrhouldThrowExceptionWithIncorrectString()
        {
            Test.AssertException<NullReferenceException>(
                () =>
                {
                    var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");

                    LocationValidator.ValidateUri(
                        actionResultWithLocation,
                        "http://somehost.com/",
                        TestObjectFactory.GetFailingValidationAction());
                }, 
                "location to be 'http://somehost.com/' instead received 'http://somehost.com/someuri/1?query=Test'");
        }
 public void ValidateUrhouldNotThrowExceptionWithProperUriWithCorrectString()
 {
     var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");
     
     LocationValidator.ValidateUri(
         actionResultWithLocation,
         TestObjectFactory.GetUri().OriginalString,
         TestObjectFactory.GetFailingValidationAction());
 }
Exemplo n.º 3
0
        public async Task ExecuteWhenAddSubscriptionCalledNoAdvancedFilterReturnsCreatedObjectResult()
        {
            A.CallTo(() => subscriptionRegistrationService.AddSubscription(A <SubscriptionSettings> .Ignored)).Returns(HttpStatusCode.Created);

            //Arrange
            A.CallTo(() => _request.Method).Returns("POST");
            A.CallTo(() => _request.Body).Returns(new MemoryStream(Encoding.UTF8.GetBytes(GetRequestBody(true, true, false, true))));
            A.CallTo(() => advancedFilterOptions.CurrentValue).Returns(new AdvancedFilterOptions {
                MaximumAdvancedFilterValues = 25
            });

            //Act
            CreatedResult result = (CreatedResult) await RunFunction(null);

            // Assert
            Assert.Equal((int?)HttpStatusCode.Created, result.StatusCode);
        }
        public async Task Post_ShouldAddOrder()
        {
            //Arrange
            var useCase = Builder <CreateOrderUseCase> .CreateNew().Build();

            var addedOrder = Builder <CreateOrderUseCaseResult> .CreateNew().Build();

            _orderUseCases.Setup(x => x.CreateOrderAsync(useCase)).ReturnsAsync(addedOrder);

            var expectedResult = new CreatedResult("orders/", addedOrder.Id);

            //Act
            var result = await _ordersController.Post(useCase);

            //Assert
            result.Should().BeEquivalentTo(expectedResult);
        }
Exemplo n.º 5
0
        public IActionResult CreateTodoItem(TodoItem todoItem)
        {
            IActionResult result;

            try
            {
                todoItem.Id = todoItem.Id ?? Guid.NewGuid();
                _todoRepository.CreateTodoItem(todoItem);
                result = new CreatedResult(new Uri($"/todo/{todoItem.Id}", UriKind.Relative), todoItem);
            }
            catch (Exception exception)
            {
                result = new ObjectResult($"Error creating Todo: {exception.Message}.");
            }

            return(result);
        }
Exemplo n.º 6
0
        public void GamePostMustReturnNewGamesIdInRepo()
        {
            // Given
            long respData = 100;

            serviceMock.Setup(m => m.NewGame(It.IsAny <BoringToeNewGameRequest>()))
            .Returns(respData);
            BoringToeController controller = new BoringToeController(serviceMock.Object);

            // When
            CreatedResult resp = controller.Post(new BoringToeNewGameRequest()) as CreatedResult;

            // Then
            Assert.AreEqual(respData, resp.Value, "Response value must be mocked one");
            Assert.IsInstanceOf <long>(resp.Value, "Value must be if type long");
            serviceMock.Verify(v => v.NewGame(It.IsAny <BoringToeNewGameRequest>()), Times.Once, "Service's New Game must be called 1 time");
        }
Exemplo n.º 7
0
    public async Task CreatedResult_OverwritesLocationHeader()
    {
        // Arrange
        var location      = "/test/";
        var httpContext   = GetHttpContext();
        var actionContext = GetActionContext(httpContext);

        httpContext.Response.Headers["Location"] = "/different/location/";
        var result = new CreatedResult(location, "testInput");

        // Act
        await result.ExecuteResultAsync(actionContext);

        // Assert
        Assert.Equal(StatusCodes.Status201Created, httpContext.Response.StatusCode);
        Assert.Equal(location, httpContext.Response.Headers["Location"]);
    }
Exemplo n.º 8
0
        public async Task AddExtractFromUPUDocument_ReturnsCreatedObjectResult()
        {
            //Arrange
            _mockBlankExtractFromUPUDocumentService
            .Setup(x => x.AddDocumentAsync(It.IsAny <ExtractFromUPUDocumentsDTO>()))
            .ReturnsAsync(new ExtractFromUPUDocumentsDTO());
            //Act
            var document = await _blanksController.AddExtractFromUPUDocument(new ExtractFromUPUDocumentsDTO());

            CreatedResult createdResult = document as CreatedResult;

            //Assert
            _mockBlankExtractFromUPUDocumentService.Verify();
            Assert.NotNull(document);
            Assert.IsInstanceOf <ObjectResult>(document);
            Assert.AreEqual(StatusCodes.Status201Created, createdResult.StatusCode);
        }
Exemplo n.º 9
0
        public void PostEquipment_Success(string vesselCode, string eqName, string eqCode, string eqLocation)
        {
            Equipment equip = new Equipment {
                name = eqName, code = eqCode, location = eqLocation
            };

            IActionResult result       = _fpsoController.PostEquipment(vesselCode, equip);
            CreatedResult objectResult = result as CreatedResult;

            Equipment retEquip = objectResult.Value as Equipment;

            Assert.AreEqual(objectResult.StatusCode, (int)HttpStatusCode.Created);
            Assert.AreEqual(retEquip.name, eqName);
            Assert.AreEqual(retEquip.code, eqCode);
            Assert.AreEqual(retEquip.location, eqLocation);
            Assert.AreEqual(retEquip.active, true);
        }
Exemplo n.º 10
0
        public CreatedResult GetError412_PreConditionFailed(string transactionID, string errorMessage, string errorInternal, string route)
        {
            GeneralErrorResponse general_412ErrorResponse = new GeneralErrorResponse();

            general_412ErrorResponse.TransactionID = transactionID;
            general_412ErrorResponse.Error         = errorMessage;
            general_412ErrorResponse.Route         = route;
            general_412ErrorResponse.ErrorInternal = errorInternal;
            GeneralErrorResponseContainer generalErrorResponseContainer = new GeneralErrorResponseContainer();

            generalErrorResponseContainer.Warning       = System.Net.HttpStatusCode.PreconditionFailed.ToString();
            generalErrorResponseContainer.ErrorResponse = general_412ErrorResponse;
            CreatedResult createdResult = new CreatedResult(route, null);

            createdResult.StatusCode = 412;
            createdResult.Value      = generalErrorResponseContainer;
            return(createdResult);
        }
        public async Task AddBiographyDocument_ReturnsCreatedObjectResult()
        {
            //Arrange
            _mockBiographyService
            .Setup(x => x.AddDocumentAsync(It.IsAny <BlankBiographyDocumentsDTO>()))
            .ReturnsAsync(GetBlankBiographyDocumentDTO());

            //Act
            var document = await _blanksController.AddBiographyDocument(GetBlankBiographyDocumentDTO());

            CreatedResult createdResult = document as CreatedResult;

            //Assert
            Assert.NotNull(document);
            Assert.NotNull(createdResult.Value);
            Assert.IsInstanceOf <ObjectResult>(document);
            Assert.AreEqual(StatusCodes.Status201Created, createdResult.StatusCode);
        }
Exemplo n.º 12
0
        public async Task List_GivenNoParametersProvided_ShouldReturnDocumentCollection()
        {
            var sortProperty  = "Filename";
            var sortDirection = "Ascending";

            var expectedResults = new List <Document>
            {
                new Document("example1.pdf", 1000, "application/pdf", new DateTime(02, 03, 04, 05, 06, 07)),
                new Document("example2.pdf", 1000, "application/pdf", new DateTime(01, 02, 03, 04, 05, 06)),
                new Document("example3.pdf", 1000, "application/pdf", new DateTime(08, 06, 05, 04, 03, 02)),
            };

            var expectedContentResult = new CreatedResult("/", expectedResults);

            var configuration = new Mock <IConfiguration>();

            ConfigurationHelper.SetupMaximumFileSizeInBytes(configuration, Constants.MaximumFileSizeInBytes);
            ConfigurationHelper.SetupAllowedContentTypes(configuration, "application/pdf");

            var validator = new UploadRequestValidator(configuration.Object);
            var logger    = new TestLogger <AzureFunctions>();
            var mediator  = new Mock <IMediator>();

            mediator
            .Setup(m => m.Send(It.IsAny <GetDocumentCollectionQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new ValueWrapper <IEnumerable <Document> >(new List <Document>(), true));

            var function = new AzureFunctions(mediator.Object, validator, logger);

            var httpRequest  = HttpRequestHelper.CreateMockRequest(expectedResults);
            var actionResult = await function.List(httpRequest.Object, sortProperty, sortDirection);

            var statusCodeResult = (IStatusCodeActionResult)actionResult;

            var createdResult = (OkObjectResult)actionResult;

            createdResult.Value.ShouldNotBeSameAs(expectedContentResult.Value);

            statusCodeResult.StatusCode.ShouldBe((int)HttpStatusCode.OK);

            var msg = logger.Logs[0];

            Assert.Contains("documents found", msg);
        }
        public async Task Upload_GivenValidParameters_ShouldUploadToBlobStorage()
        {
            var filename = "example.pdf";
            var stream   = StreamHelper.CreateExampleStream();
            var base64   = StreamHelper.ConvertStreamToBase64(stream);

            var configuration = new Mock <IConfiguration>();

            ConfigurationHelper.SetupMaximumFileSizeInBytes(configuration, Constants.MaximumFileSizeInBytes);
            ConfigurationHelper.SetupAllowedContentTypes(configuration, "application/pdf");

            var validator = new UploadRequestValidator(configuration.Object);
            var logger    = new Mock <ILogger <AzureFunctions> >();
            var mediator  = new Mock <IMediator>();

            mediator
            .Setup(m => m.Send(It.IsAny <UploadBlobCommand>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new ValueWrapper <bool>(true))
            .Verifiable($"{nameof(UploadBlobCommand)} was not called");

            var function = new AzureFunctions(mediator.Object, validator, logger.Object);

            Mock <HttpRequest> httpRequest = HttpRequestHelper.CreateMockRequest(new UploadRequest
            {
                Filename = filename,
                Data     = base64
            });

            var expectedContentResult = new CreatedResult("/", new
            {
                Filename = filename,
                Size     = stream.Length
            });

            var actionResult = await function.Upload(httpRequest.Object);

            var statusCodeResult = (IStatusCodeActionResult)actionResult;

            var createdResult = (ObjectResult)actionResult;

            createdResult.Value.Equals(expectedContentResult.Value);
            statusCodeResult.StatusCode.ShouldBe((int)HttpStatusCode.Created);
        }
Exemplo n.º 14
0
        public void GivenNewCustomerDTO_WhenCreatingNewCustomer_ThenReturnCreatedWithStatusCode201AndCustomerDTO()
        {
            //Given
            CustomerDTO customerDTO = new CustomerDTO();

            customerDTO.Firstname        = "test";
            customerDTO.Lastname         = "test";
            customerDTO.AdressOfCustomer = new Adress(1820, "Perk", "kerkstraat", 5);
            customerDTO.Email            = "*****@*****.**";
            customerDTO.PhoneNumber      = "04/72123456";
            _customerServiceStub.CreateNewCustomer(customerDTO).Returns(customerDTO);

            //When
            CreatedResult result = (CreatedResult)_customerController.CreateNewCustomer(customerDTO).Result;

            //Then
            Assert.Equal(customerDTO, result.Value);
            Assert.Equal(201, result.StatusCode);
        }
Exemplo n.º 15
0
        public async Task <IActionResult> PutRobotConnectionAsync(string deviceId)
        {
            string connectionString;

            try
            {
                connectionString = await fleetManager.CreateIfNotExistsRobotConnectionAsync(deviceId);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                var badRequest = new BadRequestObjectResult(ex.Message);
                return(badRequest);
            }

            var connectionResult = new CreatedResult(nameof(GetRobotAsync), connectionString);

            return(connectionResult);
        }
Exemplo n.º 16
0
        public IActionResult Delete(GeneralBodyPost GeneralBodyPost)
        {
            string          transactionID   = Guid.NewGuid().ToString();
            string          currentURL      = this.Request.Method;
            HelperRestError helperRestError = new HelperRestError();
            HelperHTTPLog   helperHTTPLog   = new HelperHTTPLog(HelperHTTPLog.WhatToLog.All);

            try
            {
                GeneralPostResponse resultContainer = new GeneralPostResponse();
                resultContainer.ReportPostHeader.TransactionID = transactionID;
                RestExceptionError restExceptionError = null;

                RESTSuppliersDB     rESTSuppliersDB = new RESTSuppliersDB(base.RESTConfig);
                DeleteSuppliersView viewToDelete    = rESTSuppliersDB.TryParse <DeleteSuppliersView>(GeneralBodyPost, out restExceptionError);
                if (restExceptionError != null)
                {
                    CreatedResult errorResult = helperRestError.GetError412_PreConditionFailed(transactionID, restExceptionError.ExceptionMessage, restExceptionError.InternalMessage, "Suppliers/Insert");
                    return(errorResult);
                }

                rESTSuppliersDB.TryDelete(viewToDelete, out restExceptionError);
                if (restExceptionError != null)
                {
                    CreatedResult errorResult = helperRestError.GetError500_InternalServerError(transactionID, restExceptionError.ExceptionMessage, restExceptionError.InternalMessage, "Suppliers/GetAll");
                    return(errorResult);
                }

                resultContainer.ReportPostHeader.Message = "Success";
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                httpResponseMessage.StatusCode = System.Net.HttpStatusCode.OK;
                CreatedResult createdResult = new CreatedResult("Suppliers/Delete", httpResponseMessage);
                createdResult.Value      = resultContainer;
                createdResult.StatusCode = 200;
                return(createdResult);
            }
            catch (Exception ex)
            {
                CreatedResult errorResult = helperRestError.GetError500_InternalServerError(transactionID, ex.Message, "x", "Suppliers/Create");
                return(errorResult);
            }
        }
Exemplo n.º 17
0
        public async Task <CreatedResult> TryCreateEvent(string name, string descr, string code)
        {
            var @event = await _eventsRepo.FindEventByVerificationCode(code);

            CreatedResult result = new CreatedResult();

            if (@event != null)
            {
                result.AddError(ErrorType.CodeAlreadyExists);
            }

            if (string.IsNullOrEmpty(name))
            {
                result.AddError(ErrorType.NameIsMissing);
            }

            if (string.IsNullOrEmpty(descr))
            {
                result.AddError(ErrorType.DescriptionIsMissing);
            }

            if (name.Length > 20)
            {
                result.AddError(ErrorType.NameIsTooLong);
            }

            if (code.Length < 4)
            {
                result.AddError(ErrorType.CodeIsTooShort);
            }

            @event = new Event
            {
                Name             = name,
                Description      = descr,
                VerificationCode = code,
            };

            _eventsRepo.Add(@event);

            return(result);
        }
Exemplo n.º 18
0
        public async Task Post_ShouldCreateBuyTrade()
        {
            var tradeModel = new TradeModel
            {
                Symbol      = "CBI",
                Action      = "BUY",
                PortfolioId = 1,
                NoOfShares  = 5
            };

            // Arrange

            _portfolioRepositoryMock.Setup(p => p.Query()).Returns(new List <Portfolio> {
                new Portfolio {
                    Id = 1
                }
            }.AsQueryable());
            _shareRepositoryMock.Setup(p => p.Query()).Returns(new List <HourlyShareRate> {
                new HourlyShareRate {
                    Symbol = "CBI"
                }
            }.AsQueryable());

            _tradeRepositoryMock.Setup(p => p.Buy(It.IsAny <TradeModel>(), It.IsAny <Func <HourlyShareRate> >())).ReturnsAsync(new Trade
            {
                Id = 1
            });

            // Act
            var result = await _tradeController.Post(tradeModel);

            // Assert
            Assert.NotNull(result);

            _tradeRepositoryMock.Verify(p => p.Buy(It.IsAny <TradeModel>(), It.IsAny <Func <HourlyShareRate> >()), Times.Once());

            CreatedResult createdResult = result as CreatedResult;

            Assert.NotNull(createdResult);
            Assert.AreEqual(201, createdResult.StatusCode);
            Assert.IsTrue(createdResult.Value is Trade);
        }
Exemplo n.º 19
0
        public async Task PostPayment_ReturnsCreatedResult()
        {
            // Arrange

            Guid          id            = Guid.NewGuid();
            PaymentStatus paymentStatus = PaymentStatus.Paid;

            PaymentReqVM paymentReqVM = MockPaymentReqVM.Get();

            PaymentReqRespModel  paymentReqRespModel  = MockPaymentReqRespModel.Get(id, paymentStatus);
            ModelStateDictionary modelStateDictionary = new ModelStateDictionary();

            mockPaymentManager.Setup(s => s.PostAsync(It.IsAny <PaymentReqModel>(), It.IsAny <ModelStateDictionary>()))
            .Returns(Task.FromResult <(PaymentReqRespModel, ModelStateDictionary)>((paymentReqRespModel, modelStateDictionary)))
            .Verifiable();

            // Act

            ActionResult actionResult = await paymentController.Post(paymentReqVM) as ActionResult;

            // Assert

            Assert.IsNotNull(actionResult);
            Assert.IsInstanceOf <CreatedResult>(actionResult);

            CreatedResult createdResult = actionResult as CreatedResult;

            Assert.IsNotNull(createdResult);
            Assert.AreEqual(StatusCodes.Status201Created, createdResult.StatusCode);

            Assert.IsNotNull(createdResult.Value);
            Assert.IsInstanceOf <PaymentCreatedRespVM>(createdResult.Value);

            PaymentCreatedRespVM paymentCreatedRespVM = createdResult.Value as PaymentCreatedRespVM;

            Assert.IsNotNull(paymentCreatedRespVM);
            Assert.AreEqual(id, paymentCreatedRespVM.Id);
            Assert.AreEqual(paymentStatus.ToString(), paymentCreatedRespVM.Status);
            Assert.AreEqual($"/api/v1/Payment/{id}", paymentCreatedRespVM.Href);

            mockPaymentManager.Verify(v => v.PostAsync(It.IsAny <PaymentReqModel>(), It.IsAny <ModelStateDictionary>()));
        }
Exemplo n.º 20
0
        //[TestCase(Description = "Create a new Task", TestName = "Test for Create Task returns Valid result")]
        public void Test_Post_NewTask_Valid()
        {
            // Arrange
            var newTestTask = new Models.ViewModels.Task()
            {
                TaskId = 20, TaskName = "Test New Task", TaskOwnerId = Guid.NewGuid(), Priority = 20, StartDate = DateTime.Today, ProjectId = 100
            };
            var expectedTestResult = new CreatedResult(string.Concat("/", newTestTask.TaskId), newTestTask);

            mockTaskLogic.Setup(api => api.CreateTask(newTestTask)).Returns(newTestTask);

            // Act
            var actualResult     = mockController.Post(newTestTask);
            var actualTaskResult = (CreatedResult)actualResult;

            // Assert
            Assert.NotNull(actualTaskResult);
            Assert.Equal(StatusCodes.Status201Created, actualTaskResult.StatusCode);
            Assert.Equal(newTestTask, actualTaskResult.Value);
        }
Exemplo n.º 21
0
        //[TestCase(Description = "Create a new Project", TestName = "Test for Create Project returns Valid result")]
        public void Test_Post_NewProject_Valid()
        {
            // Arrange
            var newTestProject = new Models.ViewModels.Project()
            {
                ProjectId = 20, ProjectName = "Test New Project", ManagerId = Guid.NewGuid(), Priority = 20, ProjectStart = DateTime.Today
            };
            var expectedTestResult = new CreatedResult(string.Concat("/", newTestProject.ProjectId), newTestProject);

            mockProjectsLogic.Setup(api => api.CreateProject(newTestProject)).Returns(newTestProject);

            // Act
            var actualResult   = mockController.Post(newTestProject);
            var actualProjData = ((CreatedResult)actualResult).Value as Models.ViewModels.Project;

            // Assert
            Assert.NotNull(actualResult);
            Assert.IsType <CreatedResult>(actualResult);
            Assert.Equal(newTestProject, actualProjData);
        }
Exemplo n.º 22
0
        public void Post_NewEvenement()
        {
            DataAccessProvider dp    = new DataAccessProvider(_context);
            List <string>      liste = new List <string>();
            Evenement          e     = new Evenement(0, "test", "test", "test", liste);
            var evenementAdded       = new EvenementController(_context).Post(e);

            Assert.IsInstanceOfType(evenementAdded, typeof(CreatedResult));
            CreatedResult cEvenementAdded = (CreatedResult)evenementAdded;

            Evenement eventAdded = (Evenement)cEvenementAdded.Value;

            int nbEvent = dp.GetAllEvent().Count;

            nbEvent.Should().Be(3);

            eventAdded.id.Should().Be(e.id);
            eventAdded.titre.Should().Be(e.titre);
            eventAdded.description.Should().Be(e.description);
        }
Exemplo n.º 23
0
        //[TestCase(Description = "Create a new User", TestName = "Test Create valid User returns Ok result")]
        public void Test_Post_NewUser_Valid()
        {
            // Arrange
            var newTestUser = new Models.ViewModels.User()
            {
                FirstName = "TestUserAddFirst", LastName = "TestUserAddLastName", UserId = "TestUserNew1"
            };
            var expectedTestResult = new CreatedResult(string.Concat("/", newTestUser.UserId), newTestUser);

            mockUserLogic.Setup(api => api.AddUser(newTestUser)).Returns(newTestUser);

            // Act
            var actualResult   = mockController.Post(newTestUser);
            var actualUserData = (CreatedResult)actualResult;

            // Assert
            Assert.IsType <CreatedResult>(actualResult);
            Assert.Equal(StatusCodes.Status201Created, actualUserData.StatusCode);
            Assert.Equal(newTestUser, (actualUserData.Value as Models.ViewModels.User));
        }
Exemplo n.º 24
0
        public async Task Post_ReturnsCreatedResult()
        {
            var SUT = Setup();
            var createMenuItemViewModel = new CreateMenuItemViewModel
            {
                Name     = "Test input meal",
                Price    = 3.50f,
                MealType = "Main",
            };

            var expectedResult = new CreatedResult($"/MenuItems/{MenuItem.Id}", MenuItem).Value;
            var result         = await SUT.Post(createMenuItemViewModel);

            var createdResult = result as ObjectResult;

            createdResult.Should().NotBeNull();
            createdResult.Should().BeOfType(typeof(CreatedResult));
            createdResult.Value.Should().Be(expectedResult);
            createdResult.StatusCode.Should().Be(StatusCodes.Status201Created);
        }
Exemplo n.º 25
0
        public void UnregisterStrategyTest2()
        {
            StrategyDetailsDto strategyDetails = new StrategyDetailsDto();

            strategyDetails.Instruction   = TradingPlaces.Resources.BuySell.Sell;
            strategyDetails.PriceMovement = 2;
            strategyDetails.Quantity      = 10;
            strategyDetails.Ticker        = "MSBT";
            StrategyController strategyController = new StrategyController();
            var           mockDependency          = new Mock <StrategyController>();
            CreatedResult result = new CreatedResult("12345678", strategyDetails);

            mockDependency.Setup(x => x.RegisterStrategy(strategyDetails)).Returns(result);
            string id       = "12345678";
            var    result2  = strategyController.UnregisterStrategy(id);
            var    okResult = result2 as OkObjectResult;

            Assert.NotNull(okResult);
            Assert.Equal(200, okResult.StatusCode);
        }
Exemplo n.º 26
0
        public void Post_NewEvenement()
        {
            DataAccessProvider dp = new DataAccessProvider(_context);

            Commentaire c = new Commentaire(0, "test", DateTime.MinValue, 1);
            var         commentaireAddedBeta = new CommentaireController(_context).Post(1, c);

            Assert.IsInstanceOfType(commentaireAddedBeta, typeof(CreatedResult));
            CreatedResult cCommentaireAdded = (CreatedResult)commentaireAddedBeta;

            Commentaire commentaireAdded = (Commentaire)cCommentaireAdded.Value;

            int nbcommentaire = dp.GetAllComms().Count;

            nbcommentaire.Should().Be(3);

            commentaireAdded.id.Should().Be(c.id);
            commentaireAdded.date.Should().Be(c.date);
            commentaireAdded.description.Should().Be(c.description);
            commentaireAdded.evenementid.Should().Be(c.evenementid);
        }
Exemplo n.º 27
0
        public void ValidateLocationShouldNotThrowExceptionWithCorrectLocationBuilder()
        {
            var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");

            LocationValidator.ValidateLocation(
                actionResultWithLocation,
                location =>
                location
                .WithHost("somehost.com")
                .AndAlso()
                .WithAbsolutePath("/someuri/1")
                .AndAlso()
                .WithPort(80)
                .AndAlso()
                .WithScheme("http")
                .AndAlso()
                .WithFragment(string.Empty)
                .AndAlso()
                .WithQuery("?query=Test"),
                TestObjectFactory.GetFailingValidationAction());
        }
Exemplo n.º 28
0
        public async Task GetByIdTest()
        {
            var actual = await controller.Create(new Picture()
            {
                Name = "GetIdPicture", UserId = "1"
            });

            Assert.IsType <CreatedResult>(actual);
            CreatedResult result = actual as CreatedResult;
            var           item   = result.Value as Picture;

            var actual2 = await controller.GetById(Guid.Parse(item.Id));

            Assert.IsType <OkObjectResult>(actual2);

            OkObjectResult result2 = actual2 as OkObjectResult;
            var            item2   = result2.Value as Picture;

            Assert.Equal(item.Id, item2.Id);
            Assert.Equal("GetIdPicture", item2.Name);
        }
        public void ValidateLocationShouldNotThrowExceptionWithCorrectLocationBuilder()
        {
            var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");

            LocationValidator.ValidateLocation(
                actionResultWithLocation,
                location =>
                    location
                        .WithHost("somehost.com")
                        .AndAlso()
                        .WithAbsolutePath("/someuri/1")
                        .AndAlso()
                        .WithPort(80)
                        .AndAlso()
                        .WithScheme("http")
                        .AndAlso()
                        .WithFragment(string.Empty)
                        .AndAlso()
                        .WithQuery("?query=Test"),
                TestObjectFactory.GetFailingValidationAction());
        }
Exemplo n.º 30
0
        public IActionResult GetAllX(GeneralBodyGet GeneralBodyGet)
        {
            string          transactionID   = Guid.NewGuid().ToString();
            string          currentURL      = this.Request.Method;
            HelperRestError helperRestError = new HelperRestError();
            HelperHTTPLog   helperHTTPLog   = new HelperHTTPLog(HelperHTTPLog.WhatToLog.All);

            try
            {
                RestExceptionError restExceptionError = null;
                RESTSuppliersDB    rESTSuppliersDB    = new RESTSuppliersDB(base.RESTConfig);

                //1)Get all rows. Note: Create "select * from MyTable". DB filter must be mannually done
                List <GetSuppliersView> rawResult = rESTSuppliersDB.GetAllWithDBFilter(GeneralBodyGet, out restExceptionError);
                if (restExceptionError != null)
                {
                    CreatedResult errorResult = helperRestError.GetError412_PreConditionFailed(transactionID, restExceptionError.ExceptionMessage, restExceptionError.InternalMessage, "Suppliers/GetAllX");
                    return(errorResult);
                }

                GeneralGetResponse resultContainer = new GeneralGetResponse();
                resultContainer.Data = rawResult;
                resultContainer.ReportHeader.TotalItensAvailable = 1;
                resultContainer.ReportHeader.TotalItensRetrieved = 1;
                resultContainer.ReportHeader.TransactionID       = transactionID;

                HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                httpResponseMessage.StatusCode = System.Net.HttpStatusCode.OK;

                CreatedResult createdResult = new CreatedResult("Suppliers/GetAllX", httpResponseMessage);
                createdResult.Value = resultContainer;
                return(createdResult);
            }
            catch (Exception ex)
            {
                CreatedResult errorResult = helperRestError.GetError500_InternalServerError(transactionID, ex.Message, "x", "Suppliers/GetAllX");
                return(errorResult);
            }
        }
        public async Task AddAuthor_WhenCallingValidRequest_ShouldReturnOk()
        {
            // Arrange
            var authorId = Guid.NewGuid();

            var locationUrl = "http://location";

            _authorServiceMock.Setup(a => a.AddAuthor(It.IsAny <AuthorDto>())).Returns(authorId);
            _urlHelperMock.Setup(m => m.Link(It.IsAny <string>(), It.IsAny <object>()))
            .Returns(locationUrl);

            // Act
            IActionResult actionResult = await _authorsApiController.AddAuthor(new AuthorDto());

            CreatedResult result = actionResult as CreatedResult; // null if cast fails

            // Assert
            Assert.IsNotNull(actionResult);
            Assert.IsNotNull(result);
            Assert.AreEqual(locationUrl, result.Location);
            Assert.IsInstanceOf <AuthorDto>(result.Value);
        }
Exemplo n.º 32
0
        public void CreateTest()
        {
            PersonalLoanModel personalLoanModel = CreatePersonalLoanModel();
            var personalLoan = new PersonalLoan(PersonalLoanName, 1, 1, 1, Payback.EveryMonth, PersonalLoanId);

            mapperMock.Setup(m => m.Map <PersonalLoan>(personalLoanModel)).Returns(personalLoan);
            loansRepositoryMock.Setup(m => m.Add(personalLoan)).Returns(personalLoan);
            mapperMock.Setup(m => m.Map <PersonalLoanModel>(personalLoan)).Returns(personalLoanModel);

            var expectedResponse = new ResponseModel <PersonalLoanModel>()
            {
                Data = personalLoanModel
            };
            var expected = new CreatedResult(nameof(LoansController.Get), expectedResponse);
            var actual   = loansController.Create(expectedResponse.Data);

            Assert.Equal(
                expected,
                (CreatedResult)actual,
                GetActionResultResponsePersonalLoanModelComparer()
                );
        }
Exemplo n.º 33
0
        public void GivenNewOrderDTOWithItemGroupWithItemIdAndAmount_WhenMakeNewOrder_ThenReturnOKWithOrderDTO()
        {
            //Given
            ItemGroupDTO itemgroupDTO1 = new ItemGroupDTO()
            {
                ItemId = 0, AmountOfThisItem = 2
            };
            OrderDTO orderDTO1 = new OrderDTO()
            {
                IdOfCustomer = 0
            };

            orderDTO1.ItemGroupsDTO.Add(itemgroupDTO1);
            _orderServiceStub.CreateNewOrder(orderDTO1).Returns(orderDTO1);

            //When
            CreatedResult result = (CreatedResult)_ordersController.MakeNewOrder(orderDTO1).Result;

            //Then
            Assert.Equal(orderDTO1, result.Value);
            Assert.Equal(201, result.StatusCode);
        }
        public void ValidateLocationShouldThrowExceptionWithIncorrectLocationBuilder()
        {
            Test.AssertException<NullReferenceException>(
                () =>
                {
                    var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");

                    LocationValidator.ValidateLocation(
                        actionResultWithLocation,
                        location =>
                            location
                                .WithHost("somehost12.com")
                                .AndAlso()
                                .WithAbsolutePath("/someuri/1")
                                .AndAlso()
                                .WithPort(80)
                                .AndAlso()
                                .WithScheme("http")
                                .AndAlso()
                                .WithFragment(string.Empty)
                                .AndAlso()
                                .WithQuery("?query=Test"),
                        TestObjectFactory.GetFailingValidationAction());
                },
                "URI to be 'http://somehost12.com/someuri/1?query=Test' was in fact 'http://somehost.com/someuri/1?query=Test'");
        }
        public void ValidateLocationShouldNotThrowExceptionWithCorrectPassingPredicate()
        {
            var actionResultWithLocation = new CreatedResult(TestObjectFactory.GetUri(), "Test");

            LocationValidator.ValidateLocation(
                actionResultWithLocation,
                location => location.Passing(uri => uri.Host == "somehost.com"),
                TestObjectFactory.GetFailingValidationAction());
        }