public async Task CollidingShipsPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); List <ShipPlacement> incorrectShips = new List <ShipPlacement> { // COLLISION! new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(1, 1), new Coordinate(1, 2) } }, new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(1, 2), new Coordinate(2, 2) } } }; ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1, Ships = incorrectShips }; var ex = Assert.Throws <CollidingShipsLogError>(() => controller.PlaceShips(request)); Assert.Equal("Provided ships are colliding as they share coordinates", ex.Message); }
public async Task CacheFound() { const string inputToken = "996"; string t; _tokenGeneratorMock.Setup(p => p.TryParseToken(inputToken, out t)) .Returns(true); var link = new Link { OriginUrl = "https://996.icu" }; var memoryCache = MockMemoryCacheService.GetMemoryCache(link); // var cachedResponse = memoryCache.Get<Link>(inputToken); _mockFeatureManager.Setup(p => p.IsEnabledAsync(nameof(FeatureFlags.HonorDNT))).Returns(Task.FromResult(false)); var ctl = new ForwardController( _appSettingsMock.Object, _loggerMock.Object, _linkForwarderServiceMock.Object, _tokenGeneratorMock.Object, memoryCache, _linkVerifierMock.Object, _mockFeatureManager.Object) { ControllerContext = GetHappyPathHttpContext() }; var result = await ctl.Forward(inputToken); Assert.IsInstanceOf(typeof(RedirectResult), result); }
public void ReturnsBadRequestWhenModelStateIsInvalid() { // Arrange var battleshipOptions = new BattleshipOptions { Alignment = BattleShip.Horizontal, Column = 1, Row = 0, ShipSize = 4, OpponentId = 2 }; _mockBattleshipUtility.Setup(m => m.AddBattleship(It.IsAny <Cell[][]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>())).Returns((BattleshipUtilityResult)null); Cell[][] playerBoard = null; var memoryCache = MockMemoryCacheService.GetMockedMemoryCache(); memoryCache.Set(0, playerBoard); var battleshipController = new BattleshipController(memoryCache, _mockBattleshipUtility.Object); // Act battleshipController.ModelState.AddModelError("Bad", "Request"); var subject = battleshipController.Add(battleshipOptions); // Assert var badRequestObjectResult = subject.Result as Microsoft.AspNetCore.Mvc.BadRequestObjectResult; Assert.IsNull(subject.Value); Assert.AreEqual(badRequestObjectResult.StatusCode.Value, StatusCodes.Status400BadRequest); }
public async Task IncorrectCoordinatesShotTest() { object expected = new GameStateResponse(1234) { GameStatus = GameStatuses.SHOOTING, NextPlayer = 1 }; var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); List <Coordinate> incorrectCoordinates = new List <Coordinate> { new Coordinate(-1, 1), new Coordinate(1, -2), new Coordinate(0, 1), new Coordinate(1, 0), new Coordinate(15, 5), new Coordinate(5, 15), new Coordinate(15, 15) }; foreach (Coordinate c in incorrectCoordinates) { ShotRequest request = new ShotRequest() { GameId = 1234, PlayerId = 1, Coordinate = c }; var ex = Assert.Throws <InvalidCoordinatesException>(() => controller.Shot(request)); Assert.Equal("Invalid coordinates supplied, possible values: columns 1-10, rows 1-10", ex.Message); } }
public async Task IncorrectCoordinatesShipsPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); List <ShipPlacement> incorrectShips = new List <ShipPlacement> { // INCORRECT COORDINATE 1,12 new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(1, 12), new Coordinate(1, 2) } }, new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(3, 2), new Coordinate(2, 2) } } }; ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1, Ships = incorrectShips }; var ex = Assert.Throws <InvalidCoordinatesException>(() => controller.PlaceShips(request)); Assert.Equal("Invalid coordinates supplied, possible values: columns 1-10, rows 1-10", ex.Message); }
public async Task InvalidShipAmountPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); List <ShipPlacement> incorrectShips = new List <ShipPlacement> { //ONLY 2 SHIPS new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(1, 1), new Coordinate(1, 2) } }, new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(3, 2), new Coordinate(2, 2) } } }; ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1, Ships = incorrectShips }; var ex = Assert.Throws <InvalidShipAmountException>(() => controller.PlaceShips(request)); Assert.Equal("Provided ships do not conform to the configured amounts, which is: [{\"Size\":5,\"Amount\":1},{\"Size\":4,\"Amount\":2},{\"Size\":3,\"Amount\":3},{\"Size\":2,\"Amount\":4}]", ex.Message); }
public async Task InvalidShipIntegrityPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); List <ShipPlacement> incorrectShips = prepareValidShipsWithoutOne2Fielded(); incorrectShips.Add(new ShipPlacement { Coordinates = new List <Coordinate> { new Coordinate(8, 8), new Coordinate(10, 8) } }); //desintegrated ship ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1, Ships = incorrectShips }; var ex = Assert.Throws <InvalidShipIntegrityException>(() => controller.PlaceShips(request)); Assert.Equal("Each ship needs to have connected coordinates", ex.Message); }
public async Task GetArticlesWithIncorrectType_ShouldReturn500NewArticles() { var memoryCache = MockMemoryCacheService.GetMemoryCache(expected); var query = new ArticleService(null, memoryCache); List <ArticleItem> result = await query.GetArticlesAsync("New"); Assert.AreEqual(500, result.Count()); }
public GoogleProfileManagerTests() { CacheModel testCacheModel = new CacheModel { UserProfile = null }; _memoryCacheMock = MockMemoryCacheService.GetMemoryCache(_validTestSessionId, testCacheModel); _testingProfileManager = new GoogleProfileManager(_memoryCacheMock); }
public async Task browse_async_calls_httpclient_with_defined_uri_if_cache_get_returns_null() { //Given var expectedUri = new Uri("https://financialmodelingprep.com/api/v3/company/stock/list"); var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); handlerMock.Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) // prepare the expected response of the mocked http call .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{\n \"symbolsList\" : [ {\n \"symbol\" : \"SPY\",\n \"name\" : \"SPDR S&P 500\",\n \"price\" : 299.39\n }, {\n \"symbol\" : \"CMCSA\",\n \"name\" : \"Comcast Corporation Class A Common Stock\",\n \"price\" : 45.54\n } ]\n}") }) .Verifiable(); // use real http client with mocked handler here var httpClinet = new HttpClient(handlerMock.Object) { BaseAddress = new Uri("https://financialmodelingprep.com") }; var memoryCacheMock = MockMemoryCacheService.RegisterMemoryCache(null); var sut = new FinancialModelingPrepRepository(httpClinet, memoryCacheMock.Object); //When var result = await sut.BrowseAsync(); //Then result.Should().NotBeNull(); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), // we expected a single external request ItExpr.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Get && // we expected a GET request req.RequestUri == expectedUri // to this uri ), ItExpr.IsAny <CancellationToken>() ); MockMemoryCacheService.GetMethodWasCalledOnce(memoryCacheMock); }
public async Task PlacingGameShotTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShotRequest request = new ShotRequest() { GameId = 1234, PlayerId = 1, Coordinate = new Coordinate(1, 1) }; var ex = Assert.Throws <InvalidGameStatusShootingException>(() => controller.Shot(request)); Assert.Equal("Game is not in the Shooting mode, current mode: PLACING", ex.Message); }
public async Task InvalidGameShotTest() { object expected = null; //game not found var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShotRequest request = new ShotRequest() { GameId = 1234, PlayerId = 1, Coordinate = new Coordinate(1, 1) }; var ex = Assert.Throws <InvalidGameIdException>(() => controller.Shot(request)); Assert.Equal("Invalid game Id 1234, no valid game with the given id exists.", ex.Message); }
public async Task InvalidPlayerIdPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 15 }; var ex = Assert.Throws <InvalidPlayerIdException>(() => controller.PlaceShips(request)); Assert.Equal("Invalid Player Id. Only Players with Id 1 and 2 are permited", ex.Message); }
public void FirstTimeRequest_InvalidOriginUrl() { string inputToken = "996"; string t; _tokenGeneratorMock .Setup(p => p.TryParseToken(inputToken, out t)) .Returns(true); var link = new Link { IsEnabled = true, OriginUrl = "INVALID_VALUE" }; var memoryCache = MockMemoryCacheService.GetMemoryCache(link, false); _linkForwarderServiceMock .Setup(p => p.GetLinkAsync(null)) .ReturnsAsync(link); _linkVerifierMock .Setup(p => p.Verify(It.IsAny <string>(), It.IsAny <IUrlHelper>(), It.IsAny <HttpRequest>(), false)) .Returns(LinkVerifyResult.InvalidFormat); _appSettingsMock.Setup(p => p.Value).Returns(new AppSettings { DefaultRedirectionUrl = "https://edi.wang" }); var ctl = new ForwardController( _appSettingsMock.Object, _loggerMock.Object, _linkForwarderServiceMock.Object, _tokenGeneratorMock.Object, memoryCache, _linkVerifierMock.Object, _mockFeatureManager.Object) { ControllerContext = GetHappyPathHttpContext() }; Assert.ThrowsAsync(typeof(UriFormatException), async() => { await ctl.Forward(inputToken); }); }
public async Task NoShipsPlacingTest() { object expected = new GameStateResponse(1234); //status = placing var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); mockConfig.Setup(config => config.Value).Returns(() => prepareConfig()); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1 }; var ex = Assert.Throws <NoShipsProvidedException>(() => controller.PlaceShips(request)); Assert.Equal("No ships provided in placement", ex.Message); }
public async Task browse_async_checks_if_cache_contains_proper_data() { //Given var cacheResult = new List <Company>(); var httpClientMock = new Mock <HttpClient>(); var memoryCacheMock = MockMemoryCacheService.RegisterMemoryCache(cacheResult); var sut = new FinancialModelingPrepRepository(httpClientMock.Object, memoryCacheMock.Object); //When var result = await sut.BrowseAsync(); //Then MockMemoryCacheService.GetMethodWasCalledOnce(memoryCacheMock); result.Should().BeSameAs(cacheResult); }
public async Task FirstTimeRequest_LinkNotExists_ValidDefRedir() { string inputToken = "996"; string t; _tokenGeneratorMock .Setup(p => p.TryParseToken(inputToken, out t)) .Returns(true); var link = new Link(); var memoryCache = MockMemoryCacheService.GetMemoryCache(link, false); _linkForwarderServiceMock .Setup(p => p.GetLinkAsync(null)) .ReturnsAsync(() => null); _linkVerifierMock .Setup(p => p.Verify(It.IsAny <string>(), It.IsAny <IUrlHelper>(), It.IsAny <HttpRequest>(), false)) .Returns(LinkVerifyResult.Valid); _appSettingsMock.Setup(p => p.Value).Returns(new AppSettings { DefaultRedirectionUrl = "https://edi.wang" }); var ctl = new ForwardController( _appSettingsMock.Object, _loggerMock.Object, _linkForwarderServiceMock.Object, _tokenGeneratorMock.Object, memoryCache, _linkVerifierMock.Object, _mockFeatureManager.Object) { ControllerContext = GetHappyPathHttpContext() }; var result = await ctl.Forward(inputToken); Assert.IsInstanceOf(typeof(RedirectResult), result); }
public async Task IncorrectPlayerGameShotTest() { object expected = new GameStateResponse(1234) { GameStatus = GameStatuses.SHOOTING, NextPlayer = 1 }; var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShotRequest request = new ShotRequest() { GameId = 1234, PlayerId = 2, Coordinate = new Coordinate(1, 1) }; var ex = Assert.Throws <InvalidTurnPlayerException>(() => controller.Shot(request)); Assert.Equal("Not your turn! Wait for player 1 to shot next", ex.Message); }
public async Task GetUserProfile_UnexistingSessionId_NoExceptionThrown() { //arrange string unexistingSessionId = "1"; CacheModel testCacheModel = new CacheModel { UserProfile = null }; _memoryCacheMock = MockMemoryCacheService.GetMemoryCache(unexistingSessionId, testCacheModel); //act await _testingProfileManager.GetUserProfileAsync(_validTestTokenModel, unexistingSessionId); UserProfile actualUserProfile = _memoryCacheMock.Get <CacheModel>(unexistingSessionId)?.UserProfile; UserProfile userProfileForValidSession = _memoryCacheMock.Get <CacheModel>(_validTestSessionId)?.UserProfile; //assert actualUserProfile.Should().BeNull(); userProfileForValidSession.Should().BeNull(); }
public async Task FinishedGamePlacingTest() { object expected = new GameStateResponse(1234) { GameStatus = GameStatuses.FINISHED }; var mockCache = MockMemoryCacheService.GetMemoryCache(expected); var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >(); var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object); var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null); ShipPlacementRequest request = new ShipPlacementRequest() { GameId = 1234, PlayerId = 1 }; var ex = Assert.Throws <InvalidGameStatusPlacingException>(() => controller.PlaceShips(request)); Assert.Equal("Game already started thus it's no longer possible to place ships, current mode: FINISHED", ex.Message); }
public async Task FirstTimeRequest_NoDnt_NoTTL() { string inputToken = "996"; string t; _tokenGeneratorMock .Setup(p => p.TryParseToken(inputToken, out t)) .Returns(true); var link = new Link { IsEnabled = true, OriginUrl = "https://edi.wang" }; var memoryCache = MockMemoryCacheService.GetMemoryCache(link, false); _linkForwarderServiceMock .Setup(p => p.GetLinkAsync(null)) .ReturnsAsync(link); _linkVerifierMock .Setup(p => p.Verify(It.IsAny <string>(), It.IsAny <IUrlHelper>(), It.IsAny <HttpRequest>(), false)) .Returns(LinkVerifyResult.Valid); _mockFeatureManager.Setup(p => p.IsEnabledAsync(nameof(FeatureFlags.HonorDNT))).Returns(Task.FromResult(false)); var ctl = new ForwardController( _appSettingsMock.Object, _loggerMock.Object, _linkForwarderServiceMock.Object, _tokenGeneratorMock.Object, memoryCache, _linkVerifierMock.Object, _mockFeatureManager.Object) { ControllerContext = GetHappyPathHttpContext() }; var result = await ctl.Forward(inputToken); Assert.IsInstanceOf(typeof(RedirectResult), result); }
public void ReturnsValidBattleship() { // Arrange var battleshipOptions = new BattleshipOptions { Alignment = BattleShip.Horizontal, Column = 1, PlayerId = 1, Row = 1, ShipSize = 4, OpponentId = 2 }; _mockBattleshipUtility.Setup( m => m.AddBattleship( It.IsAny <Cell[][]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>())) .Returns(new BattleshipUtilityResult("Battleship added", BattleshipResultType.Added)); var memoryCache = MockMemoryCacheService.GetMemoryCache(BattleshipUtilityTestHelpers.CreateDefaultBoard()); var battleshipController = new BattleshipController(memoryCache, _mockBattleshipUtility.Object); // Act var subject = battleshipController.Add(battleshipOptions); // Assert Assert.IsNotNull(subject); Assert.AreEqual(subject.Value.ResultType, BattleshipResultType.Added); }
public async Task browse_async_saves_http_request_result_to_cache_if_it_returns_null() { //Given var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); handlerMock.Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) // prepare the expected response of the mocked http call .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{\n \"symbolsList\" : [ {\n \"symbol\" : \"SPY\",\n \"name\" : \"SPDR S&P 500\",\n \"price\" : 299.39\n }, {\n \"symbol\" : \"CMCSA\",\n \"name\" : \"Comcast Corporation Class A Common Stock\",\n \"price\" : 45.54\n } ]\n}") }) .Verifiable(); // use real http client with mocked handler here var httpClinet = new HttpClient(handlerMock.Object) { BaseAddress = new Uri("https://financialmodelingprep.com") }; var memoryCacheMock = MockMemoryCacheService.RegisterMemoryCache(null); var sut = new FinancialModelingPrepRepository(httpClinet, memoryCacheMock.Object); //When await sut.BrowseAsync(); //Then MockMemoryCacheService.SetMethodWasCalledOnce(memoryCacheMock); }
public void ReturnsNotFoundWhenPlayerboardIsNull() { // Arrange var battleshipOptions = new BattleshipOptions { Alignment = BattleShip.Horizontal, Column = 1, PlayerId = 1, Row = 1, ShipSize = 4, OpponentId = 2 }; _mockBattleshipUtility.Setup(m => m.AddBattleship(It.IsAny <Cell[][]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>())).Returns((BattleshipUtilityResult)null); Cell[][] playerBoard = null; var memoryCache = MockMemoryCacheService.GetMockedMemoryCache(); memoryCache.Set(0, playerBoard); var battleshipController = new BattleshipController(memoryCache, _mockBattleshipUtility.Object); // Act var subject = battleshipController.Add(battleshipOptions); // Assert var notFoundObjectResult = subject.Result as Microsoft.AspNetCore.Mvc.NotFoundObjectResult; Assert.IsNull(subject.Value); Assert.AreEqual(notFoundObjectResult.StatusCode.Value, StatusCodes.Status404NotFound); }
public async Task browse_async_does_not_call_httpclient_if_cache_get_method_returns_not_null() { //Given var cacheResult = new List <Company>(); var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClinet = new HttpClient(handlerMock.Object); var memoryCacheMock = MockMemoryCacheService.RegisterMemoryCache(cacheResult); var sut = new FinancialModelingPrepRepository(httpClinet, memoryCacheMock.Object); //When var result = await sut.BrowseAsync(); //Then result.Should().BeSameAs(cacheResult); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(0), // we expect that http client has not been used ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); }