public void ValidateBindingShouldNotThrowExceptionWithValidPropertyCall()
        {
            var actionResultWithProperty = new OkObjectResult("Test");

            RuntimeBinderValidator.ValidateBinding(() =>
            {
                var value = (actionResultWithProperty as dynamic).Value;
                Assert.NotNull(value);
                Assert.Equal("Test", value);
            });
        }
        public void ValidateBindingShouldThrowExceptionWithInvalidPropertyCall()
        {
            Test.AssertException<InvalidCallAssertionException>(
                () =>
                {
                    var actionResultWithProperty = new OkObjectResult("Test");

                    RuntimeBinderValidator.ValidateBinding(() =>
                    {
                        var value = (actionResultWithProperty as dynamic).InvalidValue;
                        Assert.NotNull(value);
                        Assert.Equal("Test", value);
                    });
                }, 
                "Expected result to contain 'InvalidValue' property to test, but in fact such property was not found.");
        }
        public void DeleteData()
        {
            DbContextOptions <Context> options = new DbContextOptionsBuilder <Context>()
                                                 .UseInMemoryDatabase(databaseName: "del")
                                                 .Options;

            // Insert seed data into the database using one instance of the context
            using (Context context = new Context(options))
            {
                context.OilFields.Add(new OilField
                {
                    ID = 1, Location = "test1", Name = "test1", NumOfEmployees = 0, NumOfPumpjacks = 1, Production = 5
                });
                context.OilFields.Add(new OilField
                {
                    ID = 2, Location = "test2", Name = "test21", NumOfEmployees = 2, NumOfPumpjacks = 2, Production = 5
                });
                context.OilFields.Add(new OilField
                {
                    ID = 3, Location = "test3", Name = "test3", NumOfEmployees = 444, NumOfPumpjacks = 444, Production = 444
                });
                context.SaveChanges();
            }

            // Use a clean instance of the context to run the test
            using (Context context = new Context(options))
            {
                OilFieldController service = new OilFieldController(context);

                IActionResult  result = service.Delete(3);
                OkObjectResult res    = result as OkObjectResult;
                Assert.AreEqual(200, res.StatusCode);
                Assert.IsTrue((bool)res.Value);

                result = service.Get(3);
                NotFoundResult resNo = result as NotFoundResult;
                Assert.AreEqual(404, resNo.StatusCode);
            }
        }
示例#4
0
        public void PullRecordingHttpTriggerRunTwilioAuthenticationException()
        {
            InitializeWithTwilioMock();
            InitializeSecrets(true);
            InitializeTwilioExceptions(new Dictionary <string, Exception>()
            {
                { _config[GlobalConstants.TwilioAccountSidSecretNameAppSettingName], new TwilioEx.AuthenticationException("TestException") },
            });

            string expectedInputId = "A012345678"; // Example pulled from https://citizenpath.com/faq/find-alien-registration-number/
            string expectedCallSid = "CA10000000000000000000000000000001";

            HttpRequest request = CreateHttpPostRequest(expectedInputId, expectedCallSid);

            ExecutionContext context = new ExecutionContext()
            {
                FunctionAppDirectory = Directory.GetCurrentDirectory(),
            };

            IActionResult result = PullRecordingHttpTrigger.Run(request, Log, context).Result;

            Assert.IsInstanceOfType(result, typeof(OkObjectResult));

            OkObjectResult okResult = (OkObjectResult)result;

            Assert.AreEqual(200, okResult.StatusCode);
            Assert.IsInstanceOfType(okResult.Value, typeof(PullRecordingResponse));

            PullRecordingResponse response = (PullRecordingResponse)okResult.Value;

            Assert.AreEqual(expectedCallSid, response.CallSid);

            Assert.AreEqual((int)CommonStatusCode.Error, response.StatusCode);
            Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Error), response.StatusDesc);

            Assert.IsTrue(response.HasError);
            Assert.AreEqual((int)CommonErrorCode.TwilioAuthenticationFailed, response.ErrorCode);
            Assert.AreEqual(CommonErrorMessage.TwilioAuthenticationFailedMessage, response.ErrorDetails);
        }
示例#5
0
        public void PostTestReturnsEmptyModelForEmptyFile()
        {
            // Arrange
            var             filePath       = "InputData.csv";
            TestFileHelper  tstHelper      = new TestFileHelper(filePath, "");
            FilesController fileController = new FilesController(tstHelper.config.Object,
                                                                 new CsvFileHandler(new ValidationService(),
                                                                                    new FileService(tstHelper.config.Object),
                                                                                    new ParsingService()));

            // Expected result
            var expectedCsvResult = new CsvHandleResult();

            expectedCsvResult.Success          = true;
            expectedCsvResult.ParsedCsvContent = new DataModel();
            var expectedResult = new OkObjectResult(new
            {
                isHeadedFiles = true,
                resultList    = new List <CsvHandleResult>()
                {
                    expectedCsvResult
                }
            });

            // Act
            var actualResult =
                fileController.Post(new List <IFormFile>()
            {
                tstHelper.fileMock.Object
            }, true);

            // Assert
            Assert.IsNotNull(actualResult);
            Assert.IsNotNull(actualResult.Result);
            Assert.AreEqual(expectedResult.StatusCode,
                            ((OkObjectResult)actualResult.Result).StatusCode);
            Assert.AreEqual(expectedResult.Value.ToString(),
                            ((OkObjectResult)actualResult.Result).Value.ToString());
        }
示例#6
0
        public IActionResult GetTesterParameterXml(string searchTerms, int revisionnumber = 0)
        {
            OkObjectResult result = null;

            if (revisionnumber > 0)
            {
                var deviceList = _context.TesterParameters.Where(n => n.DeviceName.ToUpper() == searchTerms.ToUpper() && n.Revision == revisionnumber).Select(n => n.Parameter).FirstOrDefault();
                result = Ok(deviceList);
                result.Formatters.Clear();

                result.Formatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter());
                return(result);
            }
            else
            {
                var             getDeviceList = _context.TesterParameters.Where(n => n.DeviceName.ToUpper() == searchTerms.ToUpper()).ToList();
                TesterParameter deviceToSend  = new TesterParameter();
                foreach (var device in getDeviceList)
                {
                    if (deviceToSend.DeviceName == null)
                    {
                        deviceToSend = device;
                    }
                    else
                    {
                        if (device.Revision > deviceToSend.Revision)
                        {
                            deviceToSend = device;
                        }
                    }
                }
                var deviceList = deviceToSend.Parameter;
                result = Ok(deviceList);
                result.Formatters.Clear();

                result.Formatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter());
                return(result);
            }
        }
示例#7
0
        public void DeleteUser()
        {
            var user = new User
            {
                Id       = 1,
                UserName = "******",
                Email    = "*****@*****.**",
                Password = "******",
                Name     = "User Name",
                Address  = "1 Address St.",
                Gender   = "man",
                Note     = 10
            };

            var userMockRepo = new UserMockRepo(new List <User> {
                user
            });
            var articleMockRepo = new ArticleMockRepo();
            var cartMockRepo    = new CartMockRepo();
            var userController  = new UserController(_loggerMock.Object, articleMockRepo._articleRepo, userMockRepo._mockRepo, cartMockRepo._mockRepo, null);

            var preCount = userMockRepo._usersMockList.Count;

            var userGet = userController.Delete(1).Result;

            var postCount = userMockRepo._usersMockList.Count;

            Assert.AreEqual(preCount - 1, postCount);

            try
            {
                OkObjectResult res = (OkObjectResult)userGet;
            }
            catch
            {
                Assert.Fail();
            }
        }
示例#8
0
        private static async Task <IActionResult> DoLogin(HttpRequest req, CloudStorageAccount storageAccount, ILogger log)
        {
            try
            {
                string username;
                string password;
                using (var reader = new StreamReader(req.Body, Encoding.UTF8))
                {
                    var reqString = reader.ReadToEnd();
                    var credCheck = GetCredentialsFromRequest(reqString, out username, out password);
                    if (credCheck == false)
                    {
                        return(new BadRequestResult());
                    }
                }

                var repo    = new Repo(storageAccount);
                var account = await repo.GetAccount(username);

                if (account == null || !HashHelper.Verify(password, account.Password))
                {
                    return(new UnauthorizedResult());
                }

                account.PersonalBestToken = Guid.NewGuid().ToString();
                await repo.UpdateAccount(account);

                log.LogInformation($"{account.Username} LOGGED IN");
                var response = new OkObjectResult(new Account(account));
                response.ContentTypes.Add("application/json");
                return(response);
            }
            catch (Exception e)
            {
                log.LogError(e.Message, e);
                return(new InternalServerErrorResult());
            }
        }
示例#9
0
        public async void CanGetListWithItems()
        {
            DbContextOptions <ToDoNgDbContext> options = new DbContextOptionsBuilder <ToDoNgDbContext>()
                                                         .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                                         .Options;

            using (ToDoNgDbContext context = new ToDoNgDbContext(options))
            {
                // Arrange
                ToDoController     itemController = new ToDoController(context);
                ToDoListController listController = new ToDoListController(context);

                CreatedAtActionResult listResult = await listController.Post(new ToDoList()
                {
                    Name = "Foo"
                }) as CreatedAtActionResult;

                int listId = (listResult.Value as ToDoList).Id;

                CreatedAtActionResult itemResult = await itemController.Post(new ToDo()
                {
                    Message = "Hello, world!",
                    IsDone  = false,
                    ListId  = listId
                }) as CreatedAtActionResult;

                int itemId = (itemResult.Value as ToDo).Id;

                // Act
                OkObjectResult getResult = await listController.GetToDoList(listId) as OkObjectResult;

                PropertyInfo       itemsPropertyInfo = getResult.Value.GetType().GetProperty("items");
                IEnumerable <ToDo> associatedItems   = itemsPropertyInfo.GetValue(getResult.Value) as IEnumerable <ToDo>;

                // Assert
                Assert.Contains(associatedItems, i => i.Id == itemId);
            }
        }
示例#10
0
        public async Task GetResultCounts_GivenModelWithScenarioIdsButBothResultsButNoFacets_ReturnsOKWithNoResult()
        {
            //Arrange
            TestScenariosResultsCountsRequestModel model = new TestScenariosResultsCountsRequestModel
            {
                TestScenarioIds = new[] { "1", "2" }
            };

            ILogger logger = CreateLogger();

            TestScenarioSearchResults testScenarioSearchResults1 = new TestScenarioSearchResults();
            TestScenarioSearchResults testScenarioSearchResults2 = new TestScenarioSearchResults();

            ITestResultsSearchService searchService = CreateTestResultsSearchService();

            searchService
            .SearchTestScenarioResultsInternal(Arg.Any <SearchModel>())
            .Returns(testScenarioSearchResults1, testScenarioSearchResults2);

            TestResultsCountsService service = CreateResultCountsService(searchService, logger: logger);

            //Act
            IActionResult result = await service.GetResultCounts(model);

            //Assert
            result
            .Should()
            .BeOfType <OkObjectResult>();

            OkObjectResult okResult = result as OkObjectResult;

            ConcurrentBag <TestScenarioResultCounts> results = okResult.Value as ConcurrentBag <TestScenarioResultCounts>;

            results
            .Count
            .Should()
            .Be(0);
        }
        public IActionResult Delete(int id)
        {
            string customMessage = "";

            try
            {
                var foundOneCourse = Database.Courses
                                     .Single(eachCourse => eachCourse.CourseId == id);
                foundOneCourse.DeletedAt   = DateTime.Now;
                foundOneCourse.DeletedById = GetUserIdFromUserInfo();
                //Tell the db model to commit/persist the changes to the database,
                //I use the following command.
                Database.SaveChanges();
            }
            catch (Exception ex)
            {
                customMessage = "Unable to delete course record.";
                object httpFailRequestResultMessage = new { message = customMessage };
                //Return a bad http request message to the client
                return(BadRequest(httpFailRequestResultMessage));
            }//End of try .. catch block on manage data

            //Build a custom message for the client
            //Create a success message anonymous object which has a
            //Message member variable (property)
            var successRequestResultMessage = new
            {
                message = "Deleted course record"
            };

            //Create a OkObjectResult class instance, httpOkResult.
            //When creating the object, provide the previous message object into it.
            OkObjectResult httpOkResult =
                new OkObjectResult(successRequestResultMessage);

            //Send the OkObjectResult class object back to the client.
            return(httpOkResult);
        }//end of Delete() Web API method with /apis/Courses/digit route
示例#12
0
        public void GetOrders_Pass_Options_ResetToDefaults()
        {
            // Setup Fixtures.
            GetOrdersOptions options = new()
            {
                IncludeCanceled = true,
                PageNumber      = -1,
                PageSize        = -1,
                SearchText      = string.Empty,
            };

            List <OrderListDto> searchResult = new()
            {
                TestValues.OrderListDto,
            };

            // Setup Mocks.
            this._orderServiceMock
            .Setup(m => m.GetOrders(
                       It.Is <GetOrdersOptions>(opt =>
                                                opt.IncludeCanceled == options.IncludeCanceled &&
                                                opt.PageNumber == 1 &&
                                                opt.PageSize == 10 &&
                                                opt.SearchText.Equals(options.SearchText))))
            .Returns(searchResult)
            .Verifiable();

            // Execute SUT.
            IActionResult results = this._sut.GetOrders(options);

            // Verify Results.
            OkObjectResult      okResult = Assert.IsType <OkObjectResult>(results);
            List <OrderListDto> value    = Assert.IsType <List <OrderListDto> >(okResult.Value);

            Assert.Equal(searchResult.Count, value.Count);

            this._orderServiceMock.Verify();
        }
示例#13
0
        public async Task UpdateItem_success()
        {
            //arrange
            var        customerId = "123";
            var        basket     = GetCustomerBasketFake(customerId);
            BasketItem input      = new BasketItem("004", "004", "produto 004", 45.67m, 4);
            var        items      = basket.Items;

            items.Add(input);
            _basketRepositoryMock
            .Setup(c => c.UpdateBasketAsync(customerId, It.IsAny <UpdateQuantityInput>()))
            .ReturnsAsync(new UpdateQuantityOutput(input,
                                                   new CustomerBasket
            {
                CustomerId = customerId,
                Items      = items
            }))
            .Verifiable();

            var controller = new BasketController(
                _basketRepositoryMock.Object,
                _identityServiceMock.Object,
                _serviceBusMock.Object,
                _loggerMock.Object,
                _configurationMock.Object);

            //act
            ActionResult <UpdateQuantityOutput> actionResult = await controller.UpdateItem(customerId, new UpdateQuantityInput(input.ProductId, input.Quantity));

            //assert
            OkObjectResult       okObjectResult         = Assert.IsType <OkObjectResult>(actionResult.Result);
            UpdateQuantityOutput updateQuantidadeOutput = Assert.IsAssignableFrom <UpdateQuantityOutput>(okObjectResult.Value);

            Assert.Equal(input.ProductId, updateQuantidadeOutput.BasketItem.ProductId);
            _basketRepositoryMock.Verify();
            _identityServiceMock.Verify();
            _serviceBusMock.Verify();
        }
        public static IActionResult result(int code, string uri, object data = null, object msg = null, int totalData = 0)
        {
            var env = new Envelope <object> {
                success   = false,
                status    = code,
                message   = msg == null ? "" : msg,
                url       = uri,
                data      = data == null ? new object() : data,
                totalData = totalData
            };

            var okObject = new OkObjectResult(env);

            switch (code)
            {
            case 200:
                env.message = msg != null ? msg : "Success";
                env.success = true;
                return(new OkObjectResult(env));

            case 404:
                env.message = msg != null ? msg : "Data not found";
                return(new NotFoundObjectResult(env));

            case 400:
                env.message = msg != null ? msg : "Invalid Request";
                return(new BadRequestObjectResult(env));

            case 401:
                env.message         = msg != null ? msg : "Unauthorized";
                okObject.StatusCode = StatusCodes.Status401Unauthorized;
                break;
            }

            env.message         = msg != null ? msg : code + " Error";
            okObject.StatusCode = code;
            return(okObject);
        }
示例#15
0
        public async Task UpdateItem_success()
        {
            //arrange
            var          clienteId = "123";
            var          carrinho  = GetCarrinhoClienteFake(clienteId);
            ItemCarrinho input     = new ItemCarrinho("004", "004", "produto 004", 45.67m, 4);
            var          itens     = carrinho.Itens;

            itens.Add(input);
            _carrinhoRepositoryMock
            .Setup(c => c.UpdateCarrinhoAsync(clienteId, It.IsAny <UpdateQuantidadeInput>()))
            .ReturnsAsync(new UpdateQuantidadeOutput(input,
                                                     new CarrinhoCliente
            {
                ClienteId = clienteId,
                Itens     = itens
            }))
            .Verifiable();

            var controller = new CarrinhoController(
                _carrinhoRepositoryMock.Object,
                _identityServiceMock.Object,
                _serviceBusMock.Object,
                _loggerMock.Object,
                _configurationMock.Object);

            //act
            ActionResult <UpdateQuantidadeOutput> actionResult = await controller.UpdateItem(clienteId, new UpdateQuantidadeInput(input.ProdutoId, input.Quantidade));

            //assert
            OkObjectResult         okObjectResult         = Assert.IsType <OkObjectResult>(actionResult.Result);
            UpdateQuantidadeOutput updateQuantidadeOutput = Assert.IsAssignableFrom <UpdateQuantidadeOutput>(okObjectResult.Value);

            Assert.Equal(input.ProdutoId, updateQuantidadeOutput.ItemPedido.ProdutoId);
            _carrinhoRepositoryMock.Verify();
            _identityServiceMock.Verify();
            _serviceBusMock.Verify();
        }
        public void GetAllUsers()
        {
            var userEntityList = new List <GameUser>
            {
                new GameUser {
                    Id        = "32c88adb-056a-48b9-a898-632ff09806c1",
                    UserName  = "******",
                    FirstName = "Jess",
                    LastName  = "Scott",
                    Email     = "*****@*****.**"
                }
            };
            var mappedUserModelList = new List <UserModel>
            {
                new UserModel
                {
                    Id        = userEntityList[0].Id,
                    FirstName = userEntityList[0].FirstName,
                    LastName  = userEntityList[0].LastName,
                    Email     = userEntityList[0].Email
                }
            };

            _mockedRepository.Setup(x => x.GetUsers())
            .Returns(userEntityList);
            _mockedMapper.Setup(m => m.Map <IEnumerable <UserModel> >(It.IsAny <IEnumerable <GameUser> >())).Returns(mappedUserModelList);

            IActionResult result = _sut.GetUsers();

            // Check repo was queried userId.
            _mockedRepository.Verify(
                x => x.GetUsers(), Times.Once);
            // Check returned results.
            OkObjectResult okResult = Assert.IsType <OkObjectResult>(result);

            Assert.Equal(200, okResult.StatusCode);
            Assert.Equal(mappedUserModelList, okResult.Value);
        }
示例#17
0
        public void CheckCallProgressHttpTriggerRunTwilioAuthenticationException()
        {
            InitializeWithTwilioMock();
            InitializeTwilioExceptions(new Dictionary <string, Exception>()
            {
                { _config[GlobalConstants.TwilioAccountSidSecretNameAppSettingName], new TwilioEx.AuthenticationException("TestException") },
            });

            string expectedCallSid = $"CA10000000000000000000000000000200";

            HttpRequest request = CreateHttpPostRequest(expectedCallSid);

            ExecutionContext context = new ExecutionContext()
            {
                FunctionAppDirectory = Directory.GetCurrentDirectory(),
            };

            IActionResult result = CheckCallProgressHttpTrigger.Run(request, Log, context).Result;

            Assert.IsInstanceOfType(result, typeof(OkObjectResult));

            OkObjectResult okResult = (OkObjectResult)result;

            Assert.AreEqual(200, okResult.StatusCode);
            Assert.IsInstanceOfType(okResult.Value, typeof(CheckCallProgressResponse));

            CheckCallProgressResponse response = (CheckCallProgressResponse)okResult.Value;

            Assert.AreEqual(expectedCallSid, response.CallSid);
            Assert.IsNull(response.Status);

            Assert.AreEqual((int)CommonStatusCode.Error, response.StatusCode);
            Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Error), response.StatusDesc);

            Assert.IsTrue(response.HasError);
            Assert.AreEqual((int)CommonErrorCode.TwilioAuthenticationFailed, response.ErrorCode);
            Assert.AreEqual(CommonErrorMessage.TwilioAuthenticationFailedMessage, response.ErrorDetails);
        }
示例#18
0
        public async void GetOwners()
        {
            using (MyProfileDbContext context = new MyProfileDbContext(_dbContextOptions))
            {
                IMapper mapper = CreateMapperConfig();

                MyProfileController myProfileController = new MyProfileController(mapper, new OwnerRepository(context), new AddressRepository(context), new ContactRepository(context), new ExperienceRepository(context));

                for (int i = 0; i < 10; ++i)
                {
                    OwnerDto owner = new OwnerDto()
                    {
                        DateBirth = DateTime.Now,
                        FirstName = $"Test{i}",
                        LastName  = $"{i}Test"
                    };

                    myProfileController.PostOwner(owner);
                }
            }

            using (MyProfileDbContext context = new MyProfileDbContext(_dbContextOptions))
            {
                IMapper mapper = CreateMapperConfig();

                MyProfileController myProfileController = new MyProfileController(mapper, new OwnerRepository(context), new AddressRepository(context), new ContactRepository(context), new ExperienceRepository(context));

                IActionResult result = await myProfileController.GetOwners();

                OkObjectResult  okResult = result as OkObjectResult;
                List <OwnerDto> owners   = okResult.Value as List <OwnerDto>;

                Assert.NotNull(okResult);
                Assert.Equal(200, okResult.StatusCode);
                Assert.NotNull(owners);
                Assert.Equal(10, owners.Count);
            }
        }
        public IActionResult Put(int id, [FromForm] IFormCollection value)
        {
            string          customMsg = "";
            var             identity  = HttpContext.User.Identity as ClaimsIdentity;
            ClaimsPrincipal user      = HttpContext.User;
            int             userId    = 0;

            if (identity != null)
            {
                IEnumerable <Claim> claims = identity.Claims;

                userId = Int32.Parse(identity.FindFirst("userid").Value);
                var oneSessionSynopsis = Database.SessionSynopses
                                         .Where(session => session.SessionSynopsisId == id).SingleOrDefault();
                oneSessionSynopsis.SessionSynopsisName = value["sessionSynopsisName"];
                oneSessionSynopsis.IsVisible           = Convert.ToBoolean(value["isVisible"]);
                oneSessionSynopsis.UpdatedById         = userId;
                try
                {
                    Database.Update(oneSessionSynopsis);
                    Database.SaveChanges();
                }
                catch (Exception ex)
                {
                    customMsg = "Unable to save session synopsis due to anotehr record having the same session synopsis name: " + value["sessionSynopsisName"];
                    object msg = new { message = customMsg };
                    return(BadRequest(msg));
                }
                var successRequestResultMessage = new
                {
                    message = "Updated Session Synopsis \nName: " + value["sessionSynopsisName"]
                              + "\nVisibility: " + value["isVisible"]
                };
                OkObjectResult okObjectResult = new OkObjectResult(successRequestResultMessage);
                return(okObjectResult);
            }
            return(null);
        }
示例#20
0
        public void Add_should_add_road_map_by_staff_id()
        {
            // Arrange
            RoadMapData request = new()
            {
                StaffId   = 1,
                CreatedOn = Timestamp.FromDateTime(_dateTimeUtil.GetCurrentDateTime()),
                Status    = 1,
                Tasks     = "test"
            };
            BaseResponse response = new()
            {
                Code         = Code.Success,
                ErrorMessage = string.Empty,
                DataId       = 2,
            };

            BaseMock.Response = response;
            LogData log = new()
            {
                CallSide         = nameof(RoadMapsController),
                CallerMethodName = nameof(_controller.Add),
                CreatedOn        = _dateTimeUtil.GetCurrentDateTime(),
                Request          = request,
                Response         = response
            };

            // Act
            OkObjectResult result = _controller.Add(request) as OkObjectResult;
            BaseResponse   actual = result.Value as BaseResponse;

            // Assert
            Assert.AreEqual(response, actual, "Response as expected");
            _loggerMock.Verify(m => m.AddLog(log), Times.Once);
            _roadMapsClientMock.Verify(m => m.AddAsync(request, null, null, new CancellationToken()), Times.Once);
        }

        [Test]
示例#21
0
        public async Task GetBooksSuccess()
        {
            //Arrange
            var books = new List <Book>
            {
                new Book()
                {
                    Id    = 1,
                    Title = "Test Title"
                },
                new Book()
                {
                    Id    = 2,
                    Title = "Test Title 2"
                }
            };

            var fileServiceMock = new Mock <IBookService>();

            fileServiceMock.Setup(m => m.GetBooksForUserAsync(It.IsAny <string>(), It.IsAny <BooksResourceParameters>()))
            .Returns(books.AsEnumerable());
            var storageMock    = new Mock <IStorageService>();
            var fileController = new BookController(_mapper, fileServiceMock.Object, _logger, storageMock.Object);

            //Act
            IActionResult actionResult = fileController.GetBooks("ID1", new BooksResourceParameters());

            //Assert
            actionResult.ShouldNotBeNull();

            OkObjectResult result = actionResult as OkObjectResult;

            result.StatusCode.ShouldEqual(200);

            PagedList <BookDto> modelResult = result.Value as PagedList <BookDto>;

            modelResult.Items.Count.ShouldEqual(2);
        }
示例#22
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Sleep/{sleepDate}")] HttpRequest req,
            ILogger log,
            string sleepDate)
        {
            IActionResult result;

            try
            {
                bool isDateValid = _dateValidator.IsSleepDateValid(sleepDate);
                if (isDateValid == false)
                {
                    result = new BadRequestResult();
                    return(result);
                }

                var sleepResponse = await _sleepDbService.GetSleepRecordByDate(sleepDate);

                if (sleepResponse == null)
                {
                    result = new NotFoundResult();
                    return(result);
                }

                var sleep = sleepResponse.Sleep;

                result = new OkObjectResult(sleep);
            }
            catch (Exception ex)
            {
                log.LogError($"Internal Server Error. Exception thrown: {ex.Message}");
                await _serviceBusHelpers.SendMessageToQueue(_configuration["ExceptionQueue"], ex);

                result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return(result);
        }
示例#23
0
        public void WebApi_Locations_Get()
        {
            // Arrange
            Mock <ILogger <LocationsController> > mockLogger             = new Mock <ILogger <LocationsController> >();
            Mock <ILocationRepository>            mockLocationRepository = new Mock <ILocationRepository>();

            mockLocationRepository.Setup(m => m.GetLocations).Returns((new Location[] {
                new Location {
                    LocationId = 1, ParentId = 0, Description = "L1"
                },
                new Location {
                    LocationId = 2, ParentId = 1, Description = "L2"
                },
                new Location {
                    LocationId = 3, ParentId = 1, Description = "L3"
                },
                new Location {
                    LocationId = 4, ParentId = 1, Description = "L4"
                },
                new Location {
                    LocationId = 5, ParentId = 1, Description = "L5"
                }
            }).AsQueryable <Location>());

            LocationsController controller = new LocationsController(mockLogger.Object, mockLocationRepository.Object);

            // Act
            OkObjectResult result = controller.Get("1", "9999") as OkObjectResult;

            var locations = JsonConvert.DeserializeObject <List <Location> >(result.Value.ToString());

            // Assert
            Assert.AreEqual("L1", locations[0].Description);
            Assert.AreEqual("L2", locations[1].Description);
            Assert.AreEqual("L3", locations[2].Description);
            Assert.AreEqual("L4", locations[3].Description);
            Assert.AreEqual("L5", locations[4].Description);
        }
        public void Put_Should_change_some_value_in_existing_flight_return_statusCode_200()
        {
            var flightDTO1 = new FlightDTO
            {
                Id               = 1,
                Number           = 1111,
                PointOfDeparture = "Lviv",
                DepartureTime    = new DateTime(2018, 07, 10, 18, 23, 0),
                Destination      = "London",
                DestinationTime  = new DateTime(2018, 07, 11, 18, 23, 0)
            };
            var flightDTO2 = new FlightDTO
            {
                Id               = 1,
                Number           = 1111,
                PointOfDeparture = "Kiyv",
                DepartureTime    = new DateTime(2018, 07, 10, 18, 23, 0),
                Destination      = "Paris",
                DestinationTime  = new DateTime(2018, 07, 11, 18, 23, 0)
            };

            var flightService = A.Fake <IFlightService>();

            A.CallTo(() => flightService.GetEntity(A <int> ._)).Returns(flightDTO1);

            var flightsController = new FlightsController(flightService);

            //Act
            var actionResult = flightsController.Put(1, flightDTO2);

            //Assert
            Assert.NotNull(actionResult);

            OkObjectResult result = actionResult as OkObjectResult;

            Assert.NotNull(result);
            Assert.AreEqual(200, result.StatusCode);
        }
示例#25
0
        public void DeleteRecordingsHttpTriggerRunTwilioGenericException()
        {
            InitializeWithTwilioMock();

            string expectedCallSid = $"CA10000000000000000000000000000200";

            InitializeTwilioExceptions(new Dictionary <string, Exception>()
            {
                { expectedCallSid, new TwilioEx.TwilioException("TestException") },
            });

            HttpRequest request = CreateHttpPostRequest(expectedCallSid);

            ExecutionContext context = new ExecutionContext()
            {
                FunctionAppDirectory = Directory.GetCurrentDirectory(),
            };

            IActionResult result = DeleteRecordingsHttpTrigger.Run(request, Log, context).Result;

            Assert.IsInstanceOfType(result, typeof(OkObjectResult));

            OkObjectResult okResult = (OkObjectResult)result;

            Assert.AreEqual(200, okResult.StatusCode);
            Assert.IsInstanceOfType(okResult.Value, typeof(DeleteRecordingsResponse));

            DeleteRecordingsResponse response = (DeleteRecordingsResponse)okResult.Value;

            Assert.AreEqual(expectedCallSid, response.CallSid);

            Assert.AreEqual((int)CommonStatusCode.Error, response.StatusCode);
            Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Error), response.StatusDesc);

            Assert.IsTrue(response.HasError);
            Assert.AreEqual((int)CommonErrorCode.TwilioGenericFailure, response.ErrorCode);
            Assert.AreEqual(CommonErrorMessage.TwilioGenericFailureMessage, response.ErrorDetails);
        }
示例#26
0
        /// <summary>
        /// Runner for ensuring ExtractInfoHttpTrigger.Run() implementation runs correctly for concurrent executions.
        /// </summary>
        /// <param name="queue">The queue of tests to run.</param>
        public void ExtractInfoRunnerLocal(ConcurrentQueue <TestConfiguration> queue)
        {
            TestConfiguration nextTestConfiguration = null;

            while (!queue.IsEmpty)
            {
                if (queue.TryDequeue(out nextTestConfiguration))
                {
                    HttpRequest request = CreateHttpPostRequest(nextTestConfiguration.CallSid, nextTestConfiguration.Transcript);

                    ExecutionContext context = new ExecutionContext()
                    {
                        FunctionAppDirectory = Directory.GetCurrentDirectory(),
                    };

                    IActionResult result = ExtractInfoHttpTrigger.Run(request, _log, context).Result;

                    Assert.IsInstanceOfType(result, typeof(OkObjectResult));

                    OkObjectResult okResult = (OkObjectResult)result;

                    Assert.AreEqual(200, okResult.StatusCode);
                    Assert.IsInstanceOfType(okResult.Value, typeof(ExtractInfoResponse));

                    ExtractInfoResponse response = (ExtractInfoResponse)okResult.Value;

                    Assert.AreEqual(nextTestConfiguration.CallSid, response.CallSid);
                    Assert.IsNotNull(response.Data);

                    _log.LogInformation("Writing extracted data to test configuration...");
                    nextTestConfiguration.Data = response.Data;
                }

                TH.Thread.Sleep(2000);
            }

            _concurrentConfig.Save(GlobalTestConstants.ConcurrentTestConfigurationFilePath);
        }
示例#27
0
        public void GetByStaffId_should_return_road_map_by_staff_id()
        {
            // Arrange
            ByStaffRequest request = new ByStaffRequest
            {
                StaffId = _roadMapData.StaffId
            };
            RoadMapResponse response = new()
            {
                Status = new BaseResponse
                {
                    Code         = Code.Success,
                    ErrorMessage = string.Empty,
                },
                Data = _roadMapData
            };

            BaseMock.Response = response;
            LogData log = new()
            {
                CallSide         = nameof(RoadMapsController),
                CallerMethodName = nameof(_controller.GetByStaffId),
                CreatedOn        = _dateTimeUtil.GetCurrentDateTime(),
                Request          = request,
                Response         = response
            };

            // Act
            OkObjectResult  result = _controller.GetByStaffId(request) as OkObjectResult;
            RoadMapResponse actual = result.Value as RoadMapResponse;

            // Assert
            Assert.AreEqual(response, actual, "Response as expected");
            _loggerMock.Verify(m => m.AddLog(log), Times.Once);
            _roadMapsClientMock.Verify(m => m.GetByStaffId(request, null, null, new CancellationToken()), Times.Once);
        }

        [Test]
示例#28
0
        public async Task <ObjectResult> DeclineInviteAsync(
            string inviteId,
            CancellationToken cancellationToken = default)
        {
            BsonObjectId bsonInviteId;

            try
            {
                bsonInviteId = _mapper.Map <BsonObjectId>(inviteId);
            }
            catch (AutoMapperMappingException)
            {
                var modelState = new ModelStateDictionary();
                modelState.AddModelError(nameof(inviteId), "Invalid format");

                var badResult = new BadRequestObjectResult(modelState);
                return(badResult);
            }

            var userFromIdentity = GetUserFromIdentity();

            try
            {
                await _houseInviteService.DeclineInviteAvailableForUserAsync(
                    userFromIdentity.GoogleId,
                    bsonInviteId,
                    cancellationToken);
            }
            catch (HouseInviteNotFoundException)
            {
                var badResult = new NotFoundObjectResult(null);
                return(badResult);
            }

            var result = new OkObjectResult(string.Empty);

            return(result);
        }
示例#29
0
        public void UpdateEmployee_ValidInput_ReturnsOkObjectResult_WithUpdatedEmployee()
        {
            // Arrange
            Employee employeeToUpdate = SeedTestData.GetTestEmployee();

            employeeToUpdate.Name     = "gewijzigde naam";
            employeeToUpdate.Age      = 25;
            employeeToUpdate.Position = "gewijzigde positie";

            EmployeeForUpdateDto employeeForUpdateDto = new EmployeeForUpdateDto
            {
                Name     = employeeToUpdate.Name,
                Age      = employeeToUpdate.Age,
                Position = employeeToUpdate.Position,
            };

            mockRepo.Setup(repo => repo.Employee.GetEmployee(employeeToUpdate.Id, true))
            .Returns(employeeToUpdate).Verifiable();
            mockRepo.Setup(repo => repo.Save()).Verifiable();

            var controller = new EmployeesController(mockRepo.Object, _mapper);

            //Act
            var result = controller.UpdateEmployee(employeeToUpdate.Id, employeeForUpdateDto);

            // Assert
            Assert.IsInstanceOf <OkObjectResult>(result);
            OkObjectResult okResult = result as OkObjectResult;

            Assert.IsInstanceOf <Employee>(okResult.Value);
            var updatedEmployee = okResult.Value as Employee;

            Assert.AreEqual(employeeToUpdate.Name, updatedEmployee.Name);
            Assert.AreEqual(employeeToUpdate.Age, updatedEmployee.Age);
            Assert.AreEqual(employeeToUpdate.Position, updatedEmployee.Position);
            mockRepo.Verify(repo => repo.Employee.GetEmployee(updatedEmployee.Id, true), Times.Once);
            mockRepo.Verify(repo => repo.Save(), Times.Once);
        }
示例#30
0
        public async Task GetProduct_Positive()
        {
            //Arrange
            Product ProductObj = new Product()
            {
                ProductID           = 1,
                ProductRate         = 500,
                ProductAvailable    = true,
                ProductAvailableQty = "1",
                ProductCategory     = "Shoe",
                ProductName         = "Adidas"
            };
            ProductDisplayDto Product = new ProductDisplayDto()
            {
                ProductID           = 1,
                ProductRate         = "$500",
                ProductAvailable    = true,
                ProductAvailableQty = "1",
                ProductCategory     = "Shoe",
                ProductName         = "Adidas"
            };

            //Mock
            mockShopiMaxRepo.Setup(x => x.GetProduct(1)).ReturnsAsync(ProductObj);
            mockMapperRepo.Setup(mock => mock.Map <ProductDisplayDto>(It.IsAny <Product>())).Returns(Product);


            //Result
            IActionResult result = await controllerObj.GetProduct(1);

            OkObjectResult    Objresult      = result as OkObjectResult;
            ProductDisplayDto ProductDisplay = Objresult.Value as ProductDisplayDto;


            //Assert
            Assert.IsTrue(ProductDisplay.ProductID == Product.ProductID);
            Assert.IsTrue(ProductDisplay.ProductAvailable == Product.ProductAvailable);
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "search/detail")] HttpRequest req, ILogger log)
        {
            var dateStart = DateTime.Now;

            log.LogInformation("HTTP trigger function init request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            try
            {
                ScraperConfig scraperConfig = JsonConvert.DeserializeObject <ScraperConfig>(requestBody);

                if (scraperConfig == null || string.IsNullOrEmpty(scraperConfig.Source))
                {
                    return(new BadRequestObjectResult("Please pass ScraperConfig in the request body."));
                }

                LogicEngine logicEngine = new LogicEngine();
                ItemInfo    itemInfo    = logicEngine.SearchDetail(scraperConfig);

                var result = new OkObjectResult(itemInfo);

                TimeSpan diff = DateTime.Now - dateStart;
                log.LogInformation($"HTTP trigger function processed a request. Time: {diff.TotalMilliseconds} ms.");

                return(result);
            }
            catch (PlatformException e)
            {
                log.LogError(new EventId(-200), e, $"xl-error-platform: {e.Message} RequestBody: {requestBody}");
                throw e;
            }
            catch (Exception e)
            {
                log.LogError(new EventId(-100), e, $"xl-error: {e.Message} RequestBody: {requestBody}");
                throw e;
            }
        }
示例#32
0
        public async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            UserDto userReq,
            [CosmosDB("ProjetWeb", "Users", ConnectionStringSetting = "CosmosDB")]
            IAsyncCollector <Models.User> users,
            ILogger log)
        {
            try
            {
                var saltAndHash    = _passwordProvider.GenerateNewSaltedPassword(userReq.Password);
                var userToRegister = new Models.User
                {
                    Email      = userReq.Email,
                    FirstName  = userReq.FirstName,
                    LastName   = userReq.LastName,
                    Address    = string.Empty,
                    City       = string.Empty,
                    PostalCode = string.Empty,
                    Salt       = saltAndHash.Salt,
                    Password   = saltAndHash.PasswordHashed,
                };
                await users.AddAsync(userToRegister);

                return(new OkObjectResult(new BaseResponse <UserDto>(_mapper.Map <UserDto>(userToRegister))));
            }
            catch (Exception ex)
            {
                var conflictResponse = new BaseResponse <object>();
                conflictResponse.Errors.Add(
                    "Cet adresse email est déjà utilisée par un autre compte, veuillez en utiliser une autre.");
                var conflictResult = new OkObjectResult(conflictResponse)
                {
                    StatusCode = StatusCodes.Status409Conflict
                };

                return(conflictResult);
            }
        }