public void ConstructionThenAdvance() { Instant instant = Instant.FromUnixTimeTicks(100L); FakeClock clock = new FakeClock(instant); Assert.AreEqual(instant, clock.GetCurrentInstant()); Assert.AreEqual(instant, clock.GetCurrentInstant()); Duration advance = Duration.FromTicks(5); clock.AutoAdvance = advance; // Setting auto-advance doesn't actually change the clock... // but this call will. Assert.AreEqual(instant, clock.GetCurrentInstant()); Assert.AreEqual(instant + advance, clock.GetCurrentInstant()); Assert.AreEqual(instant + advance + advance, clock.GetCurrentInstant()); }
public void DirectConstruction() { Instant instant = Instant.FromUnixTimeTicks(100L); FakeClock clock = new FakeClock(instant); Assert.AreEqual(instant, clock.GetCurrentInstant()); }
public void UtcDateTimeConstruction() { Instant instant = Instant.FromUtc(2010, 1, 1, 10, 30, 25); FakeClock clock = FakeClock.FromUtc(2010, 1, 1, 10, 30, 25); Assert.AreEqual(instant, clock.GetCurrentInstant()); }
public void AdvanceSeconds() { FakeClock clock = new FakeClock(Instant.FromUnixTimeTicks(100L)); clock.AdvanceSeconds(3); Assert.AreEqual(100 + 3 * NodaConstants.TicksPerSecond, clock.GetCurrentInstant().ToUnixTimeTicks()); }
public void AdvanceTicks() { FakeClock clock = new FakeClock(Instant.FromUnixTimeTicks(100L)); clock.AdvanceTicks(3); Assert.AreEqual(103, clock.GetCurrentInstant().ToUnixTimeTicks()); }
public void when_creating_a_token_the_created_date_is_set_to_the_current_date_using_fake_clock() { FakeClock clock = CreateClock(); Token sut = new Token(() => clock.GetCurrentInstant().ToDateTimeOffset()); Assert.Equal(_utcNow, sut.CreatedAtUtc); }
public void Advance() { FakeClock clock = new FakeClock(Instant.FromUnixTimeTicks(100L)); Duration d = Duration.FromTicks(25); clock.Advance(d); Assert.AreEqual(125, clock.GetCurrentInstant().ToUnixTimeTicks()); }
public void Under60ScoreTest() { Instant pickupTime = InstantPattern.ExtendedIso.Parse("2018-01-02T12:34:24Z").GetValueOrThrow(); Instant nowTime = InstantPattern.ExtendedIso.Parse("2018-08-02T12:34:24Z").GetValueOrThrow(); IClock fakeClock = new FakeClock(nowTime); var fakeToday = fakeClock.GetToday(); MasterGame masterGame = new MasterGame(Guid.NewGuid(), "", "", new LocalDate(2018, 4, 20), new LocalDate(2018, 4, 20), null, null, null, new LocalDate(2018, 4, 20), null, null, 55, "", "", "", fakeClock.GetCurrentInstant(), false, false, false, false, fakeClock.GetCurrentInstant(), new List <MasterSubGame>(), new List <MasterGameTag>()); PublisherGame testGame = new PublisherGame(Guid.NewGuid(), Guid.NewGuid(), "", pickupTime, false, null, false, null, new MasterGameYear(masterGame, 2018), 1, null, null, null, null); PublisherSlot testSlot = new PublisherSlot(1, 1, false, null, testGame); decimal? fantasyPoints = testSlot.GetFantasyPoints(true, _scoringSystem, fakeToday); Assert.AreEqual(-12.5m, fantasyPoints); }
public void Under70ScoreTest() { Instant pickupTime = InstantPattern.ExtendedIso.Parse("2018-01-02T12:34:24Z").GetValueOrThrow(); Instant nowTime = InstantPattern.ExtendedIso.Parse("2018-08-02T12:34:24Z").GetValueOrThrow(); IClock fakeClock = new FakeClock(nowTime); ScoringSystem standardScoring = ScoringSystem.GetScoringSystem("Standard"); MasterGame masterGame = new MasterGame(Guid.NewGuid(), "", "", new LocalDate(2018, 4, 20), new LocalDate(2018, 4, 20), null, null, new LocalDate(2018, 4, 20), null, 65.8559m, "", "", fakeClock.GetCurrentInstant(), false, false, false, fakeClock.GetCurrentInstant(), new List <MasterSubGame>(), new List <MasterGameTag>()); PublisherGame testGame = new PublisherGame(Guid.NewGuid(), Guid.NewGuid(), "", pickupTime, false, null, false, null, new MasterGameYear(masterGame, 2018), null, null); decimal?fantasyPoints = testGame.CalculateFantasyPoints(standardScoring, fakeClock); Assert.AreEqual(-4.1441m, fantasyPoints); }
public void ManualScoreTest() { Instant pickupTime = InstantPattern.ExtendedIso.Parse("2018-01-02T12:34:24Z").GetValueOrThrow(); Instant nowTime = InstantPattern.ExtendedIso.Parse("2018-08-02T12:34:24Z").GetValueOrThrow(); IClock fakeClock = new FakeClock(nowTime); ScoringSystem diminishingScoring = ScoringSystem.GetScoringSystem("Diminishing"); MasterGame masterGame = new MasterGame(Guid.NewGuid(), "", "", new LocalDate(2018, 7, 13), new LocalDate(2018, 7, 13), null, null, new LocalDate(2018, 7, 13), null, 84.8095m, "", "", fakeClock.GetCurrentInstant(), false, false, false, fakeClock.GetCurrentInstant(), new List <MasterSubGame>(), new List <MasterGameTag>()); PublisherGame testGame = new PublisherGame(Guid.NewGuid(), Guid.NewGuid(), "", pickupTime, false, 83.8095m, false, null, new MasterGameYear(masterGame, 2018), null, null); decimal?fantasyPoints = testGame.CalculateFantasyPoints(diminishingScoring, fakeClock); Assert.AreEqual(13.8095m, fantasyPoints); }
public void AccessTokenExpiresAtUtc_should_be_the_token_created_date_plus_ExpiresIn_seconds() { // create a clock that advances a minute every time GetCurrentInstant() is called FakeClock clock = CreateClock(autoAdvance: TimeSpan.FromMinutes(1)); Token sut = new Token(() => clock.GetCurrentInstant().ToDateTimeOffset()); sut.ExpiresIn = (int)TimeSpan.FromMinutes(2).TotalSeconds; Assert.Equal(_utcNow.AddMinutes(2), sut.AccessTokenExpiresAtUtc); }
public void refresh_token_should_be_expired_when_the_current_date_equals_expiration_date() { // create a clock that advances a minute every time GetCurrentInstant() is called FakeClock clock = CreateClock(autoAdvance: TimeSpan.FromMinutes(1)); Token sut = new Token(() => clock.GetCurrentInstant().ToDateTimeOffset()); sut.RefreshTokenExpiresIn = 60 * 2; // expires in two mimutes Assert.Equal(_utcNow, sut.CreatedAtUtc); // +0:00 Assert.Equal(_utcNow.AddMinutes(2), sut.RefreshTokenExpiresAtUtc); }
public void RefreshTokenExpiresAtUtc_should_be_the_created_date_plus_RefreshTokenExpiresIn_seconds() { // create a clock that advances a minute every time GetCurrentInstant() is called FakeClock clock = CreateClock(TimeSpan.FromMinutes(1)); int expiresInSeconds = 60 * 2; Token sut = new Token(() => clock.GetCurrentInstant().ToDateTimeOffset()); sut.RefreshTokenExpiresIn = expiresInSeconds; Assert.Equal(_utcNow.AddSeconds(expiresInSeconds), sut.RefreshTokenExpiresAtUtc); }
public void ProductsShouldNotBeIncludedInMultipleDiscounts( [Frozen(Matching.ImplementedInterfaces)] FakeClock fakeClock, [Frozen(Matching.ImplementedInterfaces)] DiscountService discountService, Basket basket) { discountService.AddProductDiscount(new PieAndChipsMealDealDiscount(new DiscountPercent(20))); discountService.AddProductDiscount(new PieExpiryDiscount(fakeClock, new DiscountPercent(50))); basket.Add(new Pie(new Price(3.20m), fakeClock.GetCurrentInstant().InUtc().Date)); basket.Add(new PortionOfChips(new Price(1.80m))); basket.TotalCost.Should().Be(3.40m); }
public void ExpiredPieShouldNotBeValid( int advanceDays, [Frozen(Matching.ImplementedInterfaces)] FakeClock fakeClock, ExpiredPieValidator sut) { Pie pie = new Pie(default(Price), fakeClock.GetCurrentInstant().InUtc().LocalDateTime.Date); // Advance the clock forward so the pie is now expired. fakeClock.AdvanceDays(advanceDays); ValidationResult result = sut.Validate(pie); result.IsValid.Should().BeFalse(); }
public void UnexpiredPieShouldBeValid( int advanceDays, [Frozen(Matching.ImplementedInterfaces)] FakeClock fakeClock, ExpiredPieValidator sut) { Pie pie = new Pie(default(Price), fakeClock.GetCurrentInstant().InUtc().LocalDateTime.Date); // Roll the clock back so the pie will not have expired. fakeClock.AdvanceDays(advanceDays); ValidationResult result = sut.Validate(pie); result.IsValid.Should().BeTrue(); }
public void GetCurrent() { var julian = CalendarSystem.Julian; FakeClock underlyingClock = new FakeClock(NodaConstants.UnixEpoch); ZonedClock zonedClock = underlyingClock.InZone(SampleZone, julian); Assert.AreEqual(NodaConstants.UnixEpoch, zonedClock.GetCurrentInstant()); Assert.AreEqual(new ZonedDateTime(underlyingClock.GetCurrentInstant(), SampleZone, julian), zonedClock.GetCurrentZonedDateTime()); Assert.AreEqual(new LocalDateTime(1969, 12, 19, 2, 0, julian), zonedClock.GetCurrentLocalDateTime()); Assert.AreEqual(new LocalDateTime(1969, 12, 19, 2, 0, julian).WithOffset(Offset.FromHours(2)), zonedClock.GetCurrentOffsetDateTime()); Assert.AreEqual(new LocalDate(1969, 12, 19, julian), zonedClock.GetCurrentDate()); Assert.AreEqual(new LocalTime(2, 0, 0), zonedClock.GetCurrentTimeOfDay()); }
private TokenSet GetTestTokenSet(bool isExpired = false, bool isInvalid = false) { var fakeClock = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3)); var now = fakeClock.GetCurrentInstant(); return(new TokenSet( accessToken: isInvalid ? "testInvalidAccessToken" : "testAccessToken", tokenType: "bearer", expiresIn: 3600, apiEndpoint: new Uri("https://api.uri/api/"), orgKey: "testOrgKey", refreshToken: "testRefreshToken", userId: "1", receivedAt: isExpired ? now.Minus(Duration.FromDays(365)) : now)); }
public void PiesShouldBeDiscountedOnExpiryDate( int discountPercent, decimal totalCost, [Frozen(Matching.ImplementedInterfaces)] FakeClock fakeClock, [Frozen(Matching.ImplementedInterfaces)] DiscountService discountService, Basket basket) { discountService.AddProductDiscount(new PieExpiryDiscount(fakeClock, new DiscountPercent(discountPercent))); Pie pie = new Pie(new Price(3.20m), fakeClock.GetCurrentInstant().InUtc().Date); basket.Add(pie); basket.TotalCost.Should().Be(totalCost); }
public void UnreleasedGameTest() { Instant pickupTime = InstantPattern.ExtendedIso.Parse("2018-01-02T12:34:24Z").GetValueOrThrow(); Instant nowTime = InstantPattern.ExtendedIso.Parse("2018-08-02T12:34:24Z").GetValueOrThrow(); IClock fakeClock = new FakeClock(nowTime); ScoringSystem standardScoring = ScoringSystem.GetScoringSystem("Standard"); var eligibilitySettings = new EligibilitySettings(StandardEligibilityLevel, false, false, false, false, false); MasterGame masterGame = new MasterGame(Guid.NewGuid(), "", "", new LocalDate(2018, 10, 20), new LocalDate(2018, 10, 20), null, null, new LocalDate(2018, 1, 1), eligibilitySettings, "", fakeClock.GetCurrentInstant(), false, false, fakeClock.GetCurrentInstant()); PublisherGame testGame = new PublisherGame(Guid.NewGuid(), Guid.NewGuid(), "", pickupTime, false, null, null, new MasterGameYear(masterGame, 2018), null, null); decimal?fantasyPoints = testGame.CalculateFantasyPoints(standardScoring, fakeClock); Assert.AreEqual(null, fantasyPoints); }
public void DiscountsShouldCalculateTheLowestPrice( int mealDealDiscountPercent, int expiringPieDiscountPercent, decimal totalCost, [Frozen(Matching.ImplementedInterfaces)] FakeClock fakeClock, [Frozen(Matching.ImplementedInterfaces)] DiscountService discountService, Basket basket) { discountService.AddProductDiscount(new PieAndChipsMealDealDiscount(new DiscountPercent(mealDealDiscountPercent))); discountService.AddProductDiscount(new PieExpiryDiscount(fakeClock, new DiscountPercent(expiringPieDiscountPercent))); basket.Add(new Pie(new Price(3.20m), fakeClock.GetCurrentInstant().InUtc().Date)); basket.Add(new Pie(new Price(3.20m), LocalDate.MaxIsoValue)); for (int i = 0; i < 2; i++) { basket.Add(new PortionOfChips(new Price(1.80m))); } basket.TotalCost.Should().Be(totalCost); }
public void MessagesController_DecoratesListResponseWithPaginationHeaders() { for (int i = 0; i < 20; i++) { _state.Add(new MessageModel(Guid.NewGuid(), "Niklas", $"Message{i}", _clock.GetCurrentInstant())); } var result = _controller .Get(limit: 5, offset: 5, sort: "id"); Assert.AreEqual(StatusCodes.Status200OK, result.StatusCode); Assert.IsInstanceOfType(result.Value, typeof(Pagination <MessageModel>)); var messages = (Pagination <MessageModel>)result.Value; Assert.AreEqual(5, messages.Items.Count()); string linkHeader = _controller.Response.Headers[MessageBoardConstants.LinkHeader]; Assert.AreEqual($"<5,0,id>; rel=\"first\",<5,15,id>; rel=\"last\",<5,10,id>; rel=\"next\",<5,0,id>; rel=\"prev\"", linkHeader); }
public async void ShouldRefreshActionstepToken() { using (var authDelegatingHandler = new AuthDelegatingHandler() { InnerHandler = _handler }) using (var httpClient = new HttpClient(authDelegatingHandler)) using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { var tokenHandler = new TestTokenSetRepository(); var fakeClock = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3)); var testTokenRepository = new TestTokenSetRepository(); var options = new ActionstepServiceConfigurationOptions("clientId", "clientSecret"); var actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, testTokenRepository, fakeClock, memoryCache); // Expired token var tokenSet = new TokenSet( accessToken: "testAccessToken", tokenType: "bearer", expiresIn: 60 * 20, apiEndpoint: new Uri("https://api.uri/api/"), orgKey: "testOrgKey", refreshToken: "testRefreshToken", userId: "1", id: "tokenId", receivedAt: fakeClock.GetCurrentInstant().Minus(Duration.FromDays(365))); var response = await actionstepService.RefreshAccessTokenIfExpired(tokenSet); Assert.NotNull(response); Assert.Equal("updatedAccessToken", response.AccessToken); Assert.Equal(3600, response.ExpiresIn); Assert.Equal("updatedRefreshToken", response.RefreshToken); Assert.Equal("testOrg", response.OrgKey); Assert.Equal(new Uri("https://test-endpoint/api/"), response.ApiEndpoint); Assert.Equal("tokenId", response.Id); Assert.Equal(2, testTokenRepository.AddOrUpdateTokenSetCount); } }
public async Task RegistrationCommand_RegistrationNewUser_SuccessRegistration() { // ---- Arrange ---- const string name = "test user"; const string email = "*****@*****.**"; const string password = "******"; _authRepositoryMock.Setup(r => r.RegisterUser(It.IsAny <UserIdentityModel>())) .ReturnsAsync((UserIdentityModel user) => new UserModel { Id = user.Id, Email = user.Email, Name = user.Name, RegistrationDate = user.RegistrationDate }); var command = new RegisterUserCommand(email, name, password); var handler = new RegisterUserCommandHandler(_repositoryProviderMock.Object) { Clock = _fakeClock }; // ---- Act ---- var result = await handler.Handle(command, CancellationToken.None); // ---- Assert ---- Assert.NotNull(result); Assert.AreNotEqual(Guid.Empty, result.Id); Assert.AreEqual(email, result.Email); Assert.AreEqual(name, result.Name); Assert.AreEqual(_fakeClock.GetCurrentInstant(), result.RegistrationDate); _authRepositoryMock.Verify(r => r.IsUserIdentityExists(email), Times.Once); _authRepositoryMock.Verify(r => r.RegisterUser(It.IsAny <UserIdentityModel>()), Times.Once); }
public async Task SecondTokenRefreshWaitsForFirst() { using (var authDelegatingHandler = new AuthDelegatingHandler() { InnerHandler = _handler }) using (var httpClient = new HttpClient(authDelegatingHandler)) using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { var tokenHandler = new TestTokenSetRepository(); var fakeClock = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3)); var testTokenRepository = new TestTokenSetRepository(); var options = new ActionstepServiceConfigurationOptions("clientId", "clientSecret"); var actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, testTokenRepository, fakeClock, memoryCache); var now = fakeClock.GetCurrentInstant(); /// We're using the TokenType purely as a mechanism to talk to <see cref="TestTokenSetRepository"/>. /// This allows us to delay one refresh while queueing another to ensure the locking/retry works correctly /// with concurrent refresh requests. var tokenTypeTest1 = "bearer-test1"; var tokenTypeTest2 = "bearer-test2"; // First, store a locked expired token var tokenId = "locking test token"; var tokenSet1 = new TokenSet( "testAccessToken1", tokenTypeTest1, 3600, new Uri("https://api.uri/api/auto-increment/"), "testOrgKey", "testRefreshToken1", now.Minus(Duration.FromMinutes(120)), "testUser", tokenId); tokenSet1.LockForRefresh(now.Plus(Duration.FromMinutes(60))); var storedTokenSet1 = await testTokenRepository.AddOrUpdateTokenSet(tokenSet1); // Now we set up a second expired token with the same id. var tokenSet2 = new TokenSet( "testAccessToken2", tokenTypeTest2, 3600, new Uri("https://api.uri/api/auto-increment/"), "testOrgKey", "testRefreshToken2", now.Minus(Duration.FromMinutes(120)), "testUser", tokenId); // Try to refresh using the second token (which has the same tokenId). It should be blocked by the locked token1 from above. var tokenSet2RefreshTask = actionstepService.RefreshAccessTokenIfExpired(tokenSet2, forceRefresh: false); /// Delay to give the <see cref="RefreshAccessTokenIfExpired"/> a chance to await Task.Delay(50); // Now store a valid token of test type 1, this will unlock the token tokenSet1 = new TokenSet( "testAccessToken1", tokenTypeTest1, 3600, new Uri("https://api.uri/api/auto-increment/"), "testOrgKey", "testRefreshToken1", now, "testUser", tokenId); await testTokenRepository.AddOrUpdateTokenSet(tokenSet1); tokenSet2RefreshTask.Wait(); // The token from the refresh should be the one we put in the repository. Assert.Equal(tokenTypeTest1, tokenSet2RefreshTask.Result.TokenType); } }
public async Task ShouldCreatePEXAWorkspaceRequestFromActionstep() { var testUser = await _containerFixture.GetTestUser(); await _containerFixture.ExecuteScopeAsync(async serviceProvider => { using (var authDelegatingHandler = new AuthDelegatingHandler() { InnerHandler = _handler }) using (var httpClient = new HttpClient(authDelegatingHandler)) { var fakeClock = new FakeClock(new Instant()); var testTokenSetRepository = new TestTokenSetRepository(); await testTokenSetRepository.AddOrUpdateTokenSet(new TokenSet("accessToken", "bearer", 3600, new Uri("https://uri/api"), "testOrg", "refreshToken", fakeClock.GetCurrentInstant(), testUser.Id)); var options = new ActionstepServiceConfigurationOptions("clientId", "clientSecret"); var actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, testTokenSetRepository, fakeClock, new MemoryCache(new MemoryCacheOptions())); var mapper = serviceProvider.GetService <IMapper>(); var actionstepToWcaMapper = serviceProvider.GetService <IActionstepToWCAMapper>(); PrepareTestData(serviceProvider); var handler = new PEXAWorkspaceCreationRequestFromActionstepQueryHandler(actionstepService, mapper, actionstepToWcaMapper); var token = new CancellationToken(); var query = new PEXAWorkspaceCreationRequestFromActionstepQuery { AuthenticatedUser = testUser, MatterId = 1, ActionstepOrg = "testOrg" }; var pexaWorkspaceCreationResponse = await handler.Handle(query, token); Assert.Equal("1", pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest.SubscriberReference); Assert.Equal("Yes", pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest.FinancialSettlement); var config = new ConfigurationBuilder(); config.AddInMemoryCollection(new Dictionary <string, string>() { { "WCACoreSettings:PEXASettings:Environment", "Test" } }); var pexaService = new PEXAService(httpClient, config.Build()); var request = new WorkspaceCreationRequestCommand(pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest, "dummyToken"); var response = await pexaService.Handle <WorkspaceCreationResponse>(request, CancellationToken.None); Assert.Equal("PEXA190167645", response.WorkspaceId); Assert.Equal("In Preparation", response.WorkspaceStatus); var xmldiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes); var expectedXml = EmbeddedResource.Read("ResponseData.create-workspace-result.xml"); var actualXml = _handler.RequestContent; var expectedReader = XElement.Parse(expectedXml).CreateReader(); var actualReader = XElement.Parse(actualXml).CreateReader(); using (var diffStringWriter = new StringWriter()) using (var diffWriter = XmlWriter.Create(diffStringWriter)) { var areXmlIdentical = xmldiff.Compare(expectedReader, actualReader, diffWriter); diffWriter.Flush(); foreach (var diffLine in diffStringWriter.ToString().Split(diffStringWriter.NewLine)) { _output.WriteLine(diffLine); } Assert.True(areXmlIdentical); } } }); }
public Instant GetCurrentInstant() => _fakeClock.GetCurrentInstant();