//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldWaitForALineWithoutBlocking() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: internal virtual void ShouldWaitForALineWithoutBlocking() { // given FakeClock clock = FakeClock; Stream inputStream = spy(new MockInputStream(new Ticker(clock, 5, TimeUnit.MILLISECONDS), Lines("important message"))); InputStreamAwaiter awaiter = new InputStreamAwaiter(clock, inputStream); // when awaiter.AwaitLine("important message", 5, TimeUnit.SECONDS); }
public void ReturnTrue_AfterWaitingFullInterval() { const int intervalInMinutes = 1; var fakeClock = new FakeClock(); var currencyUpdate = new CurrencyUpdate(intervalInMinutes, null, fakeClock); fakeClock.Now = fakeClock.Now.AddMinutes(intervalInMinutes); Assert.True(currencyUpdate.IsTimeToRun()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReclaimAndRecreateWhenUsageGoesDownBetweenSpikes() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReclaimAndRecreateWhenUsageGoesDownBetweenSpikes() { // given const int poolMinSize = 50; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int bellowPoolMinSize = poolMinSize / 5; int bellowPoolMinSize = poolMinSize / 5; const int poolMaxSize = 200; StatefulMonitor stateMonitor = new StatefulMonitor(this); FakeClock clock = FakeClocks; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final SomethingResourcePool pool = getResourcePool(stateMonitor, clock, poolMinSize); SomethingResourcePool pool = GetResourcePool(stateMonitor, clock, poolMinSize); AcquireResourcesAndExceedTimeout(pool, clock, poolMaxSize); // when // After the peak, stay well below concurrent usage, using up all already present resources in the process ExceedTimeout(clock); // Requires some rounds to happen, since there is constant racing between releasing and acquiring which does // not always result in reaping of resources, as there is reuse for (int i = 0; i < 30; i++) { // The latch is necessary to reduce races between batches System.Threading.CountdownEvent release = new System.Threading.CountdownEvent(bellowPoolMinSize); foreach (ResourceHolder holder in AcquireFromPool(pool, bellowPoolMinSize)) { holder.Release(release); } release.await(); ExceedTimeout(clock); } // then // currentPeakSize should not be higher than bellowPoolMinSize assertTrue(stateMonitor.CurrentPeakSize.get().ToString(), stateMonitor.CurrentPeakSize.get() <= bellowPoolMinSize); // target size should remain at pool min size assertEquals(poolMinSize, stateMonitor.TargetSize.get()); assertEquals(poolMinSize, pool.UnusedSize()); // only the excess from the pool max size down to min size must have been disposed // +1 that was used to trigger initial exceed timeout check assertEquals(poolMaxSize - poolMinSize + 1, stateMonitor.DisposedConflict.get()); stateMonitor.CreatedConflict.set(0); stateMonitor.DisposedConflict.set(0); // when // After the lull, recreate a peak AcquireResourcesAndExceedTimeout(pool, clock, poolMaxSize); // then assertEquals(poolMaxSize - poolMinSize + 1, stateMonitor.CreatedConflict.get()); assertEquals(0, stateMonitor.DisposedConflict.get()); }
public JwtServiceTests() { var mockUserService = new Mock <IUserService>(); mockUserService.Setup(db => db.GetClaimsForUser("testuser1")).Returns( Task.FromResult(new List <Claim> { new Claim("sub", "testuser1"), new Claim("role", "testrole") } as IEnumerable <Claim>)); mockUserService.Setup(db => db.GetClaimsForUser("testuser2")).Returns( Task.FromResult(new List <Claim> { new Claim("sub", "testuser2"), new Claim("role", "testrole") } as IEnumerable <Claim>)); _userService = mockUserService.Object; var mockRefreshTokenRepository = new Mock <IRefreshTokenRepository>(); var addedKeys = new List <(string, string)>(); mockRefreshTokenRepository.Setup(db => db.CreateNewToken(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Instant>())) .Callback <string, string, Instant>((key, sub, exp) => { addedKeys.Remove(addedKeys.Find(a => a.Item1 == sub)); addedKeys.Add((sub, key)); }) .Returns <string, string, Instant>((key, sub, exp) => Task.FromResult(new RefreshToken { Id = 1, Expires = exp, Key = key, Sub = sub })); mockRefreshTokenRepository.Setup(db => db.FindByKey(It.IsIn(addedKeys.Select(tuple => tuple.Item2)))) .Returns(Task.FromResult(new RefreshToken())); mockRefreshTokenRepository.Setup(db => db.FindByKey(It.IsNotIn(addedKeys.Select(tuple => tuple.Item2)))) .Returns(Task.FromResult <RefreshToken>(null)); _refreshTokenRepository = mockRefreshTokenRepository.Object; _fromUnixStartOneMinuteInterval = new FakeClock(_unixStart, Duration.FromMinutes(1)); _accessTokenValidationParameters = new TokenValidationParameters { ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(_testSecret1), ValidateAudience = false, ValidateIssuer = false, LifetimeValidator = (before, expires, securityToken, parameters) => true }; }
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 Init() { _fcf = new FakeRabbitConnectionFactory(); _logMock = new Mock <ILogger>(); _c = new FakeClock(); _mp = new SMDRParserTestShim(new FakeTCPConfiguration(), _logMock.Object, _fcf, _c); var now = DateTime.Now; _localNow = now.ToLocalTime(); _c.StopAt(Instant.FromDateTimeUtc(now.ToUniversalTime())); }
public async Task SelectNotificationsForReleaseAsync_ReturnsAllExpiredNotifications() { FakeClock.Setup(); FakeClock.Now = DateTime.Now; NotificationBuffer buffer1 = new NotificationBuffer(Guid.NewGuid(), governorId, Guid.NewGuid()); inMemoryCrudRepository.Attach(buffer1); BufferedNotification notification1 = new BufferedNotification(Guid.NewGuid(), "Notification1", "{}", buffer1, FakeClock.Now.Subtract(TimeSpan.FromMinutes(6))); inMemoryCrudRepository.Attach(notification1); BufferedNotification notification2 = new BufferedNotification(Guid.NewGuid(), "Notification2", "{}", buffer1, FakeClock.Now.Subtract(TimeSpan.FromMinutes(3))); inMemoryCrudRepository.Attach(notification2); buffer1.Notifications = new List <BufferedNotification>() { notification1, notification2 }; NotificationBuffer buffer2 = new NotificationBuffer(Guid.NewGuid(), governorId, Guid.NewGuid()); inMemoryCrudRepository.Attach(buffer2); BufferedNotification notification3 = new BufferedNotification(Guid.NewGuid(), "Notification3", "{}", buffer2, FakeClock.Now.Subtract(TimeSpan.FromMinutes(8))); inMemoryCrudRepository.Attach(notification3); buffer2.Notifications = new List <BufferedNotification>() { notification3 }; NotificationBuffer buffer3 = new NotificationBuffer(Guid.NewGuid(), governorId, Guid.NewGuid()); inMemoryCrudRepository.Attach(buffer3); BufferedNotification notification4 = new BufferedNotification(Guid.NewGuid(), "Notification3", "{}", buffer3, FakeClock.Now.Subtract(TimeSpan.FromMinutes(1))); inMemoryCrudRepository.Attach(notification4); buffer3.Notifications = new List <BufferedNotification>() { notification4 }; var notifications = await sut.SelectNotificationsForReleaseAsync(inMemoryCrudRepository); Assert.Equal(2, notifications.Keys.Count()); Assert.Equal(2, notifications[buffer1].Count); Assert.Contains(notification1, notifications[buffer1]); Assert.Contains(notification2, notifications[buffer1]); Assert.Equal(1, notifications[buffer2].Count); Assert.Contains(notification3, notifications[buffer2]); }
public void ConstructionWithAdvance() { Instant instant = Instant.FromUnixTimeTicks(100L); Duration advance = Duration.FromTicks(5); FakeClock clock = new FakeClock(instant, advance); Assert.AreEqual(advance, clock.AutoAdvance); Assert.AreEqual(instant, clock.GetCurrentInstant()); Assert.AreEqual(instant + advance, clock.GetCurrentInstant()); Assert.AreEqual(instant + advance + advance, clock.GetCurrentInstant()); }
public void FromDurationToExpiration() { var duration = Options.FromDuration(TimeSpan.FromMinutes(1)); var clock = new FakeClock(new DateTime(2018, 11, 19, 5, 56, 54, DateTimeKind.Utc)); var expiration = duration.ToExpiration(clock); Assert.NotSame(duration, expiration); Assert.Null(expiration.Duration); Assert.Equal(new DateTimeOffset(new DateTime(2018, 11, 19, 5, 56 + 1, 54, DateTimeKind.Utc)), expiration.Expiration); }
public async Task EnqeueJobAsync_Delayed() { FakeClock.Setup(); var job = new Job1(); await sut.EnqeueJobAsync(job, TimeSpan.FromSeconds(5)); var expectedScheduleTime = FakeClock.Now + TimeSpan.FromSeconds(5); schedulerProcess.Received(1).ScheduleJob(job, expectedScheduleTime, Arg.Any <Action <IJob, Exception> >()); }
public SerilogDestructuringTests(ITestOutputHelper outputHelper) : base( outputHelper, LogLevel.Information, configureLogger: configuration => configuration .Destructure.NewtonsoftJsonTypes() .Destructure.SystemTextJsonTypes() .Destructure.NetTopologySuiteTypes() .Destructure.NodaTimeTypes(DateTimeZoneProviders.Tzdb) ) { LogContext.PushProperty("SourceContext", nameof(SerilogDestructuringTests)); _clock = new FakeClock(Instant.FromUtc(2022, 1, 1, 4, 4, 4)); }
public void ConstructionWithAdvance() { Instant instant = new Instant(100L); Duration advance = Duration.FromTicks(5); FakeClock clock = new FakeClock(instant, advance); Assert.AreEqual(advance, clock.AutoAdvance); Assert.AreEqual(instant, clock.Now); Assert.AreEqual(instant + advance, clock.Now); Assert.AreEqual(instant + advance + advance, clock.Now); }
public void WithEarlierDeadline_DeadlineIsLaterThanExistingTimeout() { // Use a cancellation token to emphasize that it's not just the timing. var token = new CancellationTokenSource().Token; CallSettings settings = CallSettings.FromCancellationToken(token) .WithTimeout(TimeSpan.FromTicks(100)); var clock = new FakeClock(); DateTime?deadline = clock.GetCurrentDateTimeUtc() + TimeSpan.FromTicks(200); Assert.Same(settings, settings.WithEarlierDeadline(deadline, clock)); }
public void TestGenerateJwtString() { var registeredUser = RoleTestHelper.RegisteredUser().WithId(2).Build(); var authUser = BuildAuthUser(UserId, "User", registeredUser); var clock = FakeClock.FromUtc(2020, 01, 16, 12, 0, 0); var token = JsonWebToken.Generate(authUser, clock); string jwtString = token.ToJwtString(); jwtString.Should().Be(JWT_STRING); }
public void WithGeneralIsoZonedDateTimeSerializer_Deserialize() { var clock = FakeClock.FromUtc(2014, 05, 02, 10, 30, 45); var now = clock.Now.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()); var serialisers = new DefaultNodaSerializerSettings(DateTimeZoneProviders.Tzdb) .WithGeneralIsoZonedDateTimeSerializer(); var expected = now; var actual = serialisers.ZonedDateTimeSerializer.Deserialize(now.ToString()); Assert.Equal(expected, actual); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test @Resources.Life(STARTED) public void shouldNotEndUpInBrokenStateAfterRotationFailure() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotEndUpInBrokenStateAfterRotationFailure() { // GIVEN FakeClock clock = Clocks.fakeClock(); CallTrackingClock callTrackingClock = new CallTrackingClock(clock); CountsTracker tracker = ResourceManager.managed(NewTracker(callTrackingClock, EmptyVersionContextSupplier.EMPTY)); int labelId = 1; using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(2).get()) { tx.IncrementNodeCount(labelId, 1); // now at 1 } // WHEN System.Predicate <Thread> arrived = thread => stackTraceContains(thread, all(classNameContains("Rotation"), methodIs("rotate"))); Future <object> rotation = Threading.executeAndAwait(t => t.rotate(4), tracker, arrived, 1, SECONDS); using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(3).get()) { tx.IncrementNodeCount(labelId, 1); // now at 2 } while (callTrackingClock.CallsToNanos() == 0) { Thread.Sleep(10); } clock.Forward(Config.defaults().get(GraphDatabaseSettings.counts_store_rotation_timeout).toMillis() * 2, MILLISECONDS); try { rotation.get(); fail("Should've failed rotation due to timeout"); } catch (ExecutionException e) { // good assertTrue(e.InnerException is RotationTimeoutException); } // THEN Org.Neo4j.Register.Register_DoubleLongRegister register = Registers.newDoubleLongRegister(); tracker.Get(CountsKeyFactory.nodeKey(labelId), register); assertEquals(2, register.ReadSecond()); // and WHEN later attempting rotation again using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(4).get()) { tx.IncrementNodeCount(labelId, 1); // now at 3 } tracker.Rotate(4); // THEN tracker.Get(CountsKeyFactory.nodeKey(labelId), register); assertEquals(3, register.ReadSecond()); }
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 Day_should_equal_number_of_days_since_last_rollover() { var startInstant = Instant.MinValue; for (var i = 0; i < SeedGenerator.DaysPerSeed; i++) { var fakeClock = new FakeClock(startInstant.Plus(Duration.FromDays(i))); var seed = new SeedGenerator(fakeClock); seed.GetCurrent().DaysSinceRollover.Should().Be(i); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldReclaimAndRecreateWhenLullBetweenSpikesOccurs() internal virtual void ShouldReclaimAndRecreateWhenLullBetweenSpikesOccurs() { // given const int minSize = 50; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int BELOW_MIN_SIZE = MIN_SIZE / 5; int belowMinSize = minSize / 5; const int maxSize = 200; StatefulMonitor stateMonitor = new StatefulMonitor(); FakeClock clock = new FakeClock(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE); LinkedQueuePool <object> pool = GetLinkedQueuePool(stateMonitor, clock, minSize); IList <FlyweightHolder <object> > holders = new LinkedList <FlyweightHolder <object> >(); BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(maxSize, clock, pool, holders); // when // After the peak, stay well below concurrent usage, using up all already present Flyweights in the process clock.Forward(110, TimeUnit.MILLISECONDS); // Requires some rounds to happen, since there is constant racing between releasing and acquiring which does // not always result in reaping of Flyweights, as there is reuse for (int i = 0; i < 30; i++) { // The latch is necessary to reduce races between batches foreach (FlyweightHolder holder in AcquireFromPool(pool, belowMinSize)) { holder.release(); } clock.Forward(110, TimeUnit.MILLISECONDS); } // then // currentPeakSize should be at MIN_SIZE / 5 assertTrue(stateMonitor.CurrentPeakSize.get() <= belowMinSize, "Expected " + stateMonitor.CurrentPeakSize.get() + " <= " + belowMinSize); // target size should remain at MIN_SIZE assertEquals(minSize, stateMonitor.TargetSize.get()); // only the excess from the MAX_SIZE down to min size must have been disposed // +1 for the alarm from buildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects assertEquals(maxSize - minSize + 1, stateMonitor.DisposedConflict.get()); stateMonitor.CreatedConflict.set(0); stateMonitor.DisposedConflict.set(0); // when // After the lull, recreate a peak ((IList <FlyweightHolder <object> >)holders).AddRange(AcquireFromPool(pool, maxSize)); // then assertEquals(maxSize - minSize, stateMonitor.CreatedConflict.get()); assertEquals(0, stateMonitor.DisposedConflict.get()); }
public void DependencyInjetionTest_Diary_NegOffset() { // Pluralsight C# design strategies Instant now = Instant.FromUtc(1970, 01, 01, 0, 0); var zone = DateTimeZone.ForOffset(Offset.FromHours(-8)); var clock = new FakeClock(now); Diary diary = new Diary(clock, CalendarSystem.Iso, zone); string today = diary.FormatToday(); Assert.AreEqual("1969-12-31", today); }
public void when_not_on_a_market_day_do_thing2() { var clock = new FakeClock( Instant.FromUtc(2016, 5, 8, 0, 0)); var stock = new Stock(); var marketDay = new MarketDay( Instant.FromUtc(2016, 5, 8, 0, 0)); var myClass = new MyClassNodaTime(stock, marketDay, clock); Assert.Equal("Thing2 done!", myClass.thingState); }
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 static FakeClock SetToIso(this FakeClock clock, string offsetDateTimePatternIso) { clock.Reset( OffsetDateTimePattern .GeneralIso .Parse(offsetDateTimePatternIso) .Value .ToInstant() ); return(clock); }
public void InBclSystemDefaultZone() { // We can't replace DateTimeZoneProviders.Bcl with TimeZoneInfoReplacer, so we have to // just trust that there's a suitable system default zone. var zone = DateTimeZoneProviders.Bcl.GetSystemDefault(); var clock = new FakeClock(NodaConstants.UnixEpoch); var zonedClock = clock.InBclSystemDefaultZone(); var expected = NodaConstants.UnixEpoch.InZone(zone); Assert.AreEqual(expected, zonedClock.GetCurrentZonedDateTime()); }
public void InTzdbSystemDefaultZone() { var fakeGreenlandZone = TimeZoneInfo.CreateCustomTimeZone("Greenland Standard Time", TimeSpan.FromHours(-3), "Godthab", "Godthab"); using (TimeZoneInfoReplacer.Replace(fakeGreenlandZone, fakeGreenlandZone)) { var clock = new FakeClock(NodaConstants.UnixEpoch); var zonedClock = clock.InTzdbSystemDefaultZone(); var expected = NodaConstants.UnixEpoch.InZone(DateTimeZoneProviders.Tzdb["America/Godthab"]); Assert.AreEqual(expected, zonedClock.GetCurrentZonedDateTime()); } }
public void FromExpirationToExpiration() { var clock = new FakeClock(new DateTime(2018, 11, 19, 5, 56, 54, DateTimeKind.Utc)); var now = DateTimeOffset.UtcNow; var expiration = Options.FromExpiration(now); var anotherExpiration = expiration.ToExpiration(clock); Assert.Same(expiration, anotherExpiration); Assert.Null(anotherExpiration.Duration); Assert.Equal(now, anotherExpiration.Expiration); }
public void AuthenticateCommand_AuthUser_SuccessAuth() { // ---- Arrange ---- const string email = "*****@*****.**"; const string name = "Test user"; const string password = "******"; var passwordHash = AuthUtils.GetMd5Hash(password); var clock = new FakeClock(SystemClock.Instance.GetCurrentInstant()); var testUser = new UserIdentityModel( Guid.NewGuid(), email, name, "user", passwordHash, clock.GetCurrentInstant()); _authRepositoryMock.Setup(r => r.GetUserIdentity(email)) .ReturnsAsync(() => testUser); var command = new AuthenticateUserCommand(email, password); var handler = new AuthenticateUserCommandHandler(_repositoryProviderMock.Object, _configuration) { Clock = clock }; AuthAccessModel result = null; var lifetime = DurationUtils.FromString( _configuration[$"{AuthUtils.Jwt.ConfigKeys.Section}:{AuthUtils.Jwt.ConfigKeys.LifetimeKey}"]); // ---- Act ---- Assert.DoesNotThrowAsync(async() => { result = await handler.Handle(command, CancellationToken.None); }); clock.Advance(lifetime); // for check expires token instant // ---- Assert ---- Assert.IsNotNull(result); Assert.AreEqual(testUser.Id, result.Id); Assert.AreEqual(testUser.Email, result.Email); Assert.AreEqual(clock.GetCurrentInstant(), result.ExpiresAt); Assert.AreEqual(clock.GetCurrentInstant(), result.ExpiresAt); Assert.AreEqual("user", testUser.Role); Assert.IsNotEmpty(result.Token); _authRepositoryMock.Verify(r => r.GetUserIdentity(email), Times.Once); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldMaintainPoolAtHighWatermarkWhenConcurrentUsagePassesMinSize() internal virtual void ShouldMaintainPoolAtHighWatermarkWhenConcurrentUsagePassesMinSize() { // given const int minSize = 50; const int maxSize = 200; const int midSize = 90; StatefulMonitor stateMonitor = new StatefulMonitor(); FakeClock clock = new FakeClock(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE); LinkedQueuePool <object> pool = GetLinkedQueuePool(stateMonitor, clock, minSize); IList <FlyweightHolder <object> > holders = new LinkedList <FlyweightHolder <object> >(); // when BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(maxSize, clock, pool, holders); // then assertEquals(maxSize + 1, stateMonitor.CurrentPeakSize.get()); // the peak method above does +1 on the peak // when /* After the peak, stay at MID_SIZE concurrent usage, using up all already present Flyweights in the process * but also keeping the high watermark above the MIN_SIZE * We must do this at least twice, since the counter for disposed is incremented once per release, if appropriate, * and only after the clock has ticked. Essentially this is one loop for reducing the watermark down to * mid size and one more loop to dispose of all excess resources. That does indeed mean that there is a lag * of one clock tick before resources are disposed. If this is a bug or not remains to be seen. */ for (int i = 0; i < 2; i++) { clock.Forward(110, TimeUnit.MILLISECONDS); foreach (FlyweightHolder holder in AcquireFromPool(pool, midSize)) { holder.release(); } clock.Forward(110, TimeUnit.MILLISECONDS); foreach (FlyweightHolder holder in AcquireFromPool(pool, midSize)) { holder.release(); } } // then // currentPeakSize should be at MID_SIZE assertEquals(midSize, stateMonitor.CurrentPeakSize.get()); // target size too assertEquals(midSize, stateMonitor.TargetSize.get()); // only the excess from the MAX_SIZE down to mid size must have been disposed // +1 for the alarm from buildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects assertEquals(maxSize - midSize + 1, stateMonitor.DisposedConflict.get()); }
public void CanGetJwtPublicKeysUri() { using (var httpClient = new HttpClient()) using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { var options = new ActionstepServiceConfigurationOptions("clientId", "clientSecret"); var tokenSetRepository = new TestTokenSetRepository(); var fakeClock = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3)); var actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, tokenSetRepository, fakeClock, memoryCache); Assert.Equal(new Uri("https://cdn.actionstep.com/jwt-discovery-public.json", UriKind.Absolute), actionstepService.JwtPublicKeysUri); } }
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); }