public void Should_use_the_clocks_now() { var testClock = new TestClock(); var subject = new TimeStampedMessage(testClock); Assert.IsTrue(testClock.NowWasCalled); Assert.That(subject.TimeStamp, Is.EqualTo(TestDateTime)); }
public void ExpiredLazyTokenRemovesItemInBackground() { var clock = new TestClock(); var cache = CreateCache(clock); string key = "myKey"; var value = new object(); var callbackInvoked = new ManualResetEvent(false); var expirationToken = new TestExpirationToken() { ActiveChangeCallbacks = false }; cache.Set(key, value, new MemoryCacheEntryOptions() .AddExpirationToken(expirationToken) .RegisterPostEvictionCallback((subkey, subValue, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, state: callbackInvoked)); var found = cache.TryGetValue(key, out value); Assert.True(found); clock.Add(TimeSpan.FromMinutes(2)); expirationToken.HasChanged = true; var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity. Assert.True(callbackInvoked.WaitOne(TimeSpan.FromSeconds(30)), "Callback"); found = cache.TryGetValue(key, out value); Assert.False(found); }
public void AbsoluteExpiration_WorksAcrossLink() { var clock = new TestClock(); var cache = CreateCache(clock); var obj = new object(); string key = "myKey"; string key1 = "myKey1"; var expirationToken = new TestExpirationToken() { ActiveChangeCallbacks = true }; using (var link = cache.CreateLinkingScope()) { cache.Set(key, obj, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(5))); cache.Set(key1, obj, new MemoryCacheEntryOptions().AddEntryLink(link)); } Assert.Same(obj, cache.Get(key)); Assert.Same(obj, cache.Get(key1)); clock.Add(TimeSpan.FromSeconds(10)); object value; Assert.False(cache.TryGetValue(key1, out value)); Assert.False(cache.TryGetValue(key, out value)); }
public void CanMakeTimeStandStill() { var init = new DateTimeOffset(new DateTime(1984, 5, 10)); var clock = new TestClock(init, x => x); for (var i = 0; i < 100; i++) Assert.AreEqual(clock.Now, init); }
public void TestClockWithIncrementTimeSpan() { var init = new DateTimeOffset(new DateTime(1984, 5, 10)); var clock = new TestClock(init, 1.Weeks()); for (var i = 0; i < 100; i++) Assert.AreEqual(clock.Now, init + i.Weeks()); }
public void FixedExpiryTimeExpires() { TestClock clock = new TestClock {Now = DateTime.Now}; InMemorySessionCache cache = new InMemorySessionCache(clock); cache.Duration = 1; cache.ExpiryMode = SessionExpiryMode.Fixed; string sessionToken = cache.AddToCache("johndoe"); clock.TimePasses(TimeSpan.FromSeconds(61)); string userName = cache.RetrieveFromCache(sessionToken); Assert.IsNull(userName); }
public void TestClockIsThreadSafe() { const int n = 10000; var clock = new TestClock(DateTimeOffset.Now, 1.Milliseconds()); var nows = System.Linq.Enumerable.Range(0, n) .AsParallel() .Select(x => clock.Now) .Distinct() .Count(); Assert.AreEqual(n, nows); }
public void TimerCanTrackTime() { TestClock clock = new TestClock(); TestScheduler scheduler = new TestScheduler(clock); TimerMetric timer = new TimerMetric(SamplingType.LongTerm, new MeterMetric(clock, scheduler), clock); using (timer.NewContext()) { clock.Advance(TimeUnit.Milliseconds, 100); } timer.Value.Histogram.Count.Should().Be(1); timer.Value.Histogram.Max.Should().Be(TimeUnit.Milliseconds.ToNanoseconds(100)); }
public void SlidingExpiryTimeDoesntExpire() { TestClock clock = new TestClock {Now = DateTime.Now}; InMemorySessionCache cache = new InMemorySessionCache(clock); cache.Duration = 1; cache.ExpiryMode = SessionExpiryMode.Sliding; string sessionToken = cache.AddToCache("johndoe"); clock.TimePasses(TimeSpan.FromSeconds(31)); string userName = cache.RetrieveFromCache(sessionToken); Assert.AreEqual("johndoe", userName); clock.TimePasses(TimeSpan.FromSeconds(31)); userName = cache.RetrieveFromCache(sessionToken); Assert.AreEqual("johndoe", userName); }
public void MeterCanCalculateMeanRate() { TestClock clock = new TestClock(); TestScheduler scheduler = new TestScheduler(clock); var meter = new MeterMetric(clock, scheduler); meter.Mark(); clock.Advance(TimeUnit.Seconds, 1); meter.Value.MeanRate.Should().Be(1); clock.Advance(TimeUnit.Seconds, 1); meter.Value.MeanRate.Should().Be(0.5); }
public void TimerContextRecordsTimeOnlyOnFirstDispose() { TestClock clock = new TestClock(); TestScheduler scheduler = new TestScheduler(clock); TimerMetric timer = new TimerMetric(SamplingType.LongTerm, new MeterMetric(clock, scheduler), clock); var context = timer.NewContext(); clock.Advance(TimeUnit.Milliseconds, 100); using (context) { } clock.Advance(TimeUnit.Milliseconds, 100); using (context) { } timer.Value.Histogram.Count.Should().Be(1); timer.Value.Histogram.Max.Should().Be(TimeUnit.Milliseconds.ToNanoseconds(100)); }
public void FireFiresAfterTimePeriodHasExpired() { var innerTrigger = this.mocks.StrictMock<ITrigger>(); Expect.Call(() => { innerTrigger.IntegrationCompleted(); }); var expected = new IntegrationRequest(BuildCondition.IfModificationExists, "Test", null); Expect.Call(innerTrigger.Fire()).Return(expected); var clock = new TestClock { Now = DateTime.Now }; var trigger = new RollUpTrigger(clock); trigger.MinimumTime = new Timeout(10, TimeUnits.MINUTES); trigger.InnerTrigger = innerTrigger; mocks.ReplayAll(); trigger.IntegrationCompleted(); clock.TimePasses(new TimeSpan(0, 11, 0)); var actual = trigger.Fire(); Assert.AreSame(expected, actual); mocks.VerifyAll(); }
public TestModule(TestClock clock) : base("/test") { Get["/action"] = _ => { clock.Advance(TimeUnit.Milliseconds, 100); return Response.AsText("response"); }; Post["/post"] = _ => { clock.Advance(TimeUnit.Milliseconds, 200); return HttpStatusCode.OK; }; Get["/error"] = _ => { throw new InvalidOperationException(); }; }
public void MeterCanComputeRates() { TestClock clock = new TestClock(); TestScheduler scheduler = new TestScheduler(clock); var meter = new MeterMetric(clock, scheduler); meter.Mark(); clock.Advance(TimeUnit.Seconds, 10); meter.Mark(2); var value = meter.Value; value.MeanRate.Should().BeApproximately(0.3, 0.001); value.OneMinuteRate.Should().BeApproximately(0.1840, 0.001); value.FiveMinuteRate.Should().BeApproximately(0.1966, 0.001); value.FifteenMinuteRate.Should().BeApproximately(0.1988, 0.001); }
public TestModule(TestClock clock) : base("/test") { this.MetricForRequestTimeAndResponseSize("Action Request", "Get", "/"); this.MetricForRequestSize("Request Size", "Put", "/"); Get["/action"] = _ => { clock.Advance(TimeUnit.Milliseconds, 100); return Response.AsText("response"); }; Get["/contentWithLength"] = _ => { clock.Advance(TimeUnit.Milliseconds, 100); return Response.AsText("response").WithHeader("Content-Length", "100"); }; Put["/size"] = _ => HttpStatusCode.OK; }
public void EDRlongPeriodsOfInactivityShouldNotCorruptSamplingState() { TestClock clock = new TestClock(); TestScheduler scheduler = new TestScheduler(clock); ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(10, 0.015, clock, scheduler); // add 1000 values at a rate of 10 values/second for (int i = 0; i < 1000; i++) { reservoir.Update(1000 + i); clock.Advance(TimeUnit.Milliseconds, 100); } reservoir.Snapshot.Size.Should().Be(10); reservoir.Snapshot.Values.Should().OnlyContain(v => 1000 <= v && v < 2000); // wait for 15 hours and add another value. // this should trigger a rescale. Note that the number of samples will be reduced to 2 // because of the very small scaling factor that will make all existing priorities equal to // zero after rescale. clock.Advance(TimeUnit.Hours, 15); reservoir.Update(2000); var snapshot = reservoir.Snapshot; snapshot.Size.Should().Be(2); snapshot.Values.Should().OnlyContain(v => 1000 <= v && v < 3000); // add 1000 values at a rate of 10 values/second for (int i = 0; i < 1000; i++) { reservoir.Update(3000 + i); clock.Advance(TimeUnit.Milliseconds, 100); } var finalSnapshot = reservoir.Snapshot; finalSnapshot.Size.Should().Be(10); // TODO: double check the Skip first value - sometimes first value is 2000 - which might or not be correct finalSnapshot.Values.Skip(1).Should().OnlyContain(v => 3000 <= v && v < 4000); }
public void can_report_apdex_with_tags() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var gauge = new DefaultApdexMetric(_defaultReservoir, clock, false); var apdexValueSource = new ApdexValueSource( "test apdex", ConstantValue.Provider(gauge.Value), new MetricTags(new[] { "key1", "key2" }, new[] { "value1", "value2" }), false); var payloadBuilder = new TestPayloadBuilder(); var reporter = new TestReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", apdexValueSource); payloadBuilder.PayloadFormatted(). Should(). Be( "test__test_apdex key1=value1 key2=value2 mtype=apdex samples=0i score=0 satisfied=0i tolerating=0i frustrating=0i" + Environment.NewLine); }
public async Task CookieIsRenewedWithSlidingExpiration() { var clock = new TestClock(); var server = CreateServer(options => { options.SystemClock = clock; options.ExpireTimeSpan = TimeSpan.FromMinutes(10); options.SlidingExpiration = true; }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction2.SetCookie.ShouldBe(null); FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice"); clock.Add(TimeSpan.FromMinutes(4)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction3.SetCookie.ShouldBe(null); FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice"); clock.Add(TimeSpan.FromMinutes(4)); // transaction4 should arrive with a new SetCookie value var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction4.SetCookie.ShouldNotBe(null); FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe("Alice"); clock.Add(TimeSpan.FromMinutes(4)); var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue); transaction5.SetCookie.ShouldBe(null); FindClaimValue(transaction5, ClaimTypes.Name).ShouldBe("Alice"); }
public void can_report_apdex_with_tags_when_multidimensional() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var gauge = new DefaultApdexMetric(_defaultReservoir, clock, false); var apdexValueSource = new ApdexValueSource( "test apdex" + MultidimensionalMetricNameSuffix, ConstantValue.Provider(gauge.Value), MetricTags.Concat(_tags, new MetricTags("anothertag", "thevalue")), resetOnReporting: false); var payloadBuilder = new GraphitePayloadBuilder(_settings.GraphiteSettings.MetricNameFormatter, _settings.DataKeys, Origin); var reporter = CreateReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", apdexValueSource); payloadBuilder.PayloadFormatted(). Should(). Be( "env.staging.apdex.test.test_apdex.host.server1.anothertag.thevalue.Samples 0 0\nenv.staging.apdex.test.test_apdex.host.server1.anothertag.thevalue.Score 0.00 0\nenv.staging.apdex.test.test_apdex.host.server1.anothertag.thevalue.Satisfied 0 0\nenv.staging.apdex.test.test_apdex.host.server1.anothertag.thevalue.Tolerating 0 0\nenv.staging.apdex.test.test_apdex.host.server1.anothertag.thevalue.Frustrating 0 0\n"); }
public async Task CookieContainsRoleClaim() { var clock = new TestClock(); var server = await CreateServer(null, null, null, testCore : true); var transaction1 = await SendAsync(server, "http://example.com/createMe"); Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode); Assert.Null(transaction1.SetCookie); var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false"); Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode); Assert.NotNull(transaction2.SetCookie); Assert.DoesNotContain("; expires=", transaction2.SetCookie); var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue); Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name)); Assert.Equal("role", FindClaimValue(transaction3, ClaimTypes.Role)); Assert.Null(transaction3.SetCookie); }
public async Task TwoFactorRememberCookieClearedBySecurityStampChange(bool testCore) { var clock = new TestClock(); var server = await CreateServer(services => services.AddSingleton <ISystemClock>(clock), testCore : testCore); var transaction1 = await SendAsync(server, "http://example.com/createMe"); Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode); Assert.Null(transaction1.SetCookie); var transaction2 = await SendAsync(server, "http://example.com/twofactorRememeber"); Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode); var setCookie = transaction2.SetCookie; Assert.Contains(IdentityConstants.TwoFactorRememberMeScheme + "=", setCookie); Assert.Contains("; expires=", setCookie); var transaction3 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue); Assert.Equal(HttpStatusCode.OK, transaction3.Response.StatusCode); var transaction4 = await SendAsync(server, "http://example.com/signoutEverywhere", transaction2.CookieNameValue); Assert.Equal(HttpStatusCode.OK, transaction4.Response.StatusCode); // Doesn't validate until after interval has passed var transaction5 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue); Assert.Equal(HttpStatusCode.OK, transaction5.Response.StatusCode); // Wait for validation interval clock.Add(TimeSpan.FromMinutes(30)); var transaction6 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue); Assert.Equal(HttpStatusCode.InternalServerError, transaction6.Response.StatusCode); }
public void can_report_meters_when_multidimensional() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var meter = new DefaultMeterMetric(clock); meter.Mark(1); var meterValueSource = new MeterValueSource( "test meter" + MultidimensionalMetricNameSuffix, ConstantValue.Provider(meter.Value), Unit.None, TimeUnit.Milliseconds, _tags); var items = CreateReporterAndPayloadBuilder(); items.Item1.StartReportRun(metricsMock.Object); items.Item1.ReportMetric("test", meterValueSource); items.Item2.PayloadFormatted(). Should(). Be("test__test_meter host=server1 env=staging mtype=meter unit=none unit_rate=ms count.meter=1i rate1m=0 rate5m=0 rate15m=0" + Environment.NewLine); }
public void SlidingExpirationExpiresIfNotAccessed() { var clock = new TestClock(); var cache = CreateCache(clock); var key = "myKey"; var value = new object(); var result = cache.Set(key, value, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))); Assert.Same(value, result); var found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(value, result); clock.Add(TimeSpan.FromMinutes(2)); found = cache.TryGetValue(key, out result); Assert.False(found); Assert.Null(result); }
public async Task SetCacheItem_UpdatesAbsoluteExpirationTime() { // Arrange var testClock = new TestClock(); var key = Guid.NewGuid().ToString(); var cache = GetSQLiteCache(GetCacheOptions(testClock)); var expectedValue = Encoding.UTF8.GetBytes("Hello, World!"); var absoluteExpiration = testClock.UtcNow.Add(TimeSpan.FromSeconds(10)); // Act & Assert // Creates a new item await cache.SetAsync( key, expectedValue, new DistributedCacheEntryOptions().SetAbsoluteExpiration(absoluteExpiration)); await AssertGetCacheItemFromDatabaseAsync( cache, key, expectedValue, slidingExpiration : null, absoluteExpiration : absoluteExpiration, expectedExpirationTime : absoluteExpiration); // Updates an existing item with new absolute expiration time absoluteExpiration = testClock.UtcNow.Add(TimeSpan.FromMinutes(30)); await cache.SetAsync( key, expectedValue, new DistributedCacheEntryOptions().SetAbsoluteExpiration(absoluteExpiration)); await AssertGetCacheItemFromDatabaseAsync( cache, key, expectedValue, slidingExpiration : null, absoluteExpiration : absoluteExpiration, expectedExpirationTime : absoluteExpiration); }
public async Task SetCacheItem_SucceedsFor_NullAbsoluteAndSlidingExpirationTimes() { // Arrange var key = Guid.NewGuid().ToString(); var testClock = new TestClock(); var expectedValue = Encoding.UTF8.GetBytes("Hello, World!"); var cacheOptions = GetCacheOptions(testClock); var cache = GetSQLiteCache(cacheOptions); var expectedExpirationTime = testClock.UtcNow.Add(cacheOptions.DefaultSlidingExpiration); // Act await cache.SetAsync(key, expectedValue, new DistributedCacheEntryOptions() { AbsoluteExpiration = null, AbsoluteExpirationRelativeToNow = null, SlidingExpiration = null }); // Assert await AssertGetCacheItemFromDatabaseAsync( cache, key, expectedValue, cacheOptions.DefaultSlidingExpiration, absoluteExpiration : null, expectedExpirationTime : expectedExpirationTime); var cacheItem = await GetCacheItemFromDatabaseAsync(key); Assert.Equal(expectedValue, cacheItem.Value); // Act await cache.RemoveAsync(key); // Assert var cacheItemInfo = await GetCacheItemFromDatabaseAsync(key); Assert.Null(cacheItemInfo); }
public async Task SetWithSlidingExpiration_ReturnsNullValue_ForExpiredCacheItem( int slidingExpirationWindow, int accessItemAt) { // Arrange var testClock = new TestClock(); var key = Guid.NewGuid().ToString(); var sqlServerCache = await GetCacheAndConnectAsync(testClock); await sqlServerCache.SetAsync( key, Encoding.UTF8.GetBytes("Hello, World!"), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(10))); // set the clock's UtcNow far in future testClock.Add(TimeSpan.FromHours(10)); // Act var value = await sqlServerCache.GetAsync(key); // Assert Assert.Null(value); }
public void can_report_apdex_with_tags_when_multidimensional() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var gauge = new DefaultApdexMetric(_defaultReservoir, clock, false); var apdexValueSource = new ApdexValueSource( "test apdex" + MultidimensionalMetricNameSuffix, ConstantValue.Provider(gauge.Value), MetricTags.Concat(_tags, new MetricTags("anothertag", "thevalue")), resetOnReporting: false); var payloadBuilder = new TestPayloadBuilder(); var reporter = new TestReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", apdexValueSource); payloadBuilder.PayloadFormatted(). Should(). Be( "test__test_apdex host=server1 env=staging anothertag=thevalue mtype=apdex samples=0i score=0 satisfied=0i tolerating=0i frustrating=0i" + Environment.NewLine); }
public void can_report_meters() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var meter = new DefaultMeterMetric(clock); meter.Mark(1); var meterValueSource = new MeterValueSource( "test meter", ConstantValue.Provider(meter.Value), Unit.None, TimeUnit.Milliseconds, MetricTags.Empty); var payloadBuilder = new GraphitePayloadBuilder(_settings.GraphiteSettings.MetricNameFormatter, _settings.DataKeys, Origin); var reporter = CreateReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", meterValueSource); payloadBuilder.PayloadFormatted().Should().Be("meter.test.test_meter.Total 1 0\nmeter.test.test_meter.Rate-1-Min 0.00 0\nmeter.test.test_meter.Rate-5-Min 0.00 0\nmeter.test.test_meter.Rate-15-Min 0.00 0\n"); }
public async Task CookieExpirationCanBeOverridenInSignin() { var clock = new TestClock(); TestServer server = CreateServer(options => { options.SystemClock = clock; options.ExpireTimeSpan = TimeSpan.FromMinutes(10); options.SlidingExpiration = false; }, context => { context.Response.SignIn("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), new AuthenticationProperties() { ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)) }); return(Task.FromResult <object>(null)); }); Transaction transaction1 = await SendAsync(server, "http://example.com/testpath"); Transaction transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); Transaction transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); Transaction transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction2.SetCookie.ShouldBe(null); FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice"); transaction3.SetCookie.ShouldBe(null); FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice"); transaction4.SetCookie.ShouldBe(null); FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null); }
public void AbsoluteExpirationExpires() { var clock = new TestClock(); var cache = CreateCache(clock); var key = "myKey"; var value = new object(); var result = cache.Set(key, value, clock.UtcNow + TimeSpan.FromMinutes(1)); Assert.Same(value, result); var found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(value, result); clock.Add(TimeSpan.FromMinutes(2)); found = cache.TryGetValue(key, out result); Assert.False(found); Assert.Null(result); }
public HealthCheckRegistryTests() { _metircsSetup = healthCheckFactory => { var clock = new TestClock(); var options = new AppMetricsOptions(); IMetricContextRegistry NewContextRegistry(string name) => new DefaultMetricContextRegistry(name); var registry = new DefaultMetricsRegistry( LoggerFactory, options, clock, new EnvironmentInfoProvider(), NewContextRegistry); var metricBuilderFactory = new DefaultMetricsBuilderFactory(); var filter = new DefaultMetricsFilter(); var healthManager = new DefaultHealthProvider(new Lazy <IMetrics>(() => _metrics), LoggerFactory.CreateLogger <DefaultHealthProvider>(), healthCheckFactory); var dataManager = new DefaultMetricValuesProvider( filter, registry); var metricsManagerFactory = new DefaultMeasureMetricsProvider(registry, metricBuilderFactory, clock); var metricsManagerAdvancedFactory = new DefaultMetricsProvider(registry, metricBuilderFactory, clock); var metricsManager = new DefaultMetricsManager(registry, LoggerFactory.CreateLogger <DefaultMetricsManager>()); _metrics = new DefaultMetrics( clock, filter, metricsManagerFactory, metricBuilderFactory, metricsManagerAdvancedFactory, dataManager, metricsManager, healthManager); return(_metrics); }; }
public async Task CookieExpirationCanBeOverridenInEvent() { var clock = new TestClock(); var server = CreateServer(options => { options.SystemClock = clock; options.ExpireTimeSpan = TimeSpan.FromMinutes(10); options.SlidingExpiration = false; options.Notifications = new CookieAuthenticationNotifications() { OnResponseSignIn = context => { context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)); } }; }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction2.SetCookie.ShouldBe(null); FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice"); clock.Add(TimeSpan.FromMinutes(3)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction3.SetCookie.ShouldBe(null); FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice"); clock.Add(TimeSpan.FromMinutes(3)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); transaction4.SetCookie.ShouldBe(null); FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null); }
public void FireFiresAfterTimePeriodHasExpired() { var innerTrigger = this.mocks.StrictMock <ITrigger>(); Expect.Call(() => { innerTrigger.IntegrationCompleted(); }); var expected = new IntegrationRequest(BuildCondition.IfModificationExists, "Test", null); Expect.Call(innerTrigger.Fire()).Return(expected); var clock = new TestClock { Now = DateTime.Now }; var trigger = new RollUpTrigger(clock); trigger.MinimumTime = new Timeout(10, TimeUnits.MINUTES); trigger.InnerTrigger = innerTrigger; mocks.ReplayAll(); trigger.IntegrationCompleted(); clock.TimePasses(new TimeSpan(0, 11, 0)); var actual = trigger.Fire(); Assert.AreSame(expected, actual); mocks.VerifyAll(); }
public void can_report_timers() { var expected = StringReporterSamples.Timers.ExtractStringReporterSampleFromResourceFile(); var sr = new StringReporter(); var clock = new TestClock(); var histogram = new DefaultHistogramMetric(_defaultReservoir); var metric = new DefaultTimerMetric(histogram, clock); metric.Record(1000, TimeUnit.Milliseconds, "value1"); metric.Record(2000, TimeUnit.Milliseconds, "value2"); sr.ReportMetric( "test", new TimerValueSource( "timer_name", metric, Unit.None, TimeUnit.Milliseconds, TimeUnit.Milliseconds, MetricTags.None)); AssertReportResult(sr.Result, expected); }
public void can_report_meters_when_multidimensional() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var meter = new DefaultMeterMetric(clock); meter.Mark(1); var meterValueSource = new MeterValueSource( "test meter" + MultidimensionalMetricNameSuffix, ConstantValue.Provider(meter.Value), Unit.None, TimeUnit.Milliseconds, _tags); var payloadBuilder = new LineProtocolPayloadBuilder(); var reporter = CreateReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", meterValueSource); payloadBuilder.PayloadFormatted(). Should(). Be("test__test_meter,host=server1,env=staging count.meter=1i,rate1m=0,rate5m=0,rate15m=0\n"); }
public void Apdex_score_should_be_between_zero_and_one() { const double apdexTSeconds = 0.5; const int fromMilliSeconds = 20; const int toMilliSeconds = 5000; var random = new Random(); var clock = new TestClock(); IApdexMetric apdexMetric = new DefaultApdexMetric(new DefaultForwardDecayingReservoir(), apdexTSeconds, clock, false); foreach (var unused in Enumerable.Range(0, 1000)) { using (apdexMetric.NewContext()) { clock.Advance(TimeUnit.Milliseconds, random.Next(fromMilliSeconds, toMilliSeconds)); } } var score = apdexMetric.GetValue().Score; score.Should().BeGreaterOrEqualTo(0); score.Should().BeLessOrEqualTo(1); }
public void can_report_meters() { var metricsMock = new Mock <IMetrics>(); var clock = new TestClock(); var meter = new DefaultMeterMetric(clock); meter.Mark(1); var meterValueSource = new MeterValueSource( "test meter", ConstantValue.Provider(meter.Value), Unit.None, TimeUnit.Milliseconds, MetricTags.Empty); var payloadBuilder = new TestPayloadBuilder(); var reporter = new TestReporter(payloadBuilder); reporter.StartReportRun(metricsMock.Object); reporter.ReportMetric("test", meterValueSource); payloadBuilder.PayloadFormatted(). Should(). Be("test__test_meter mtype=meter count.meter=1i rate1m=0 rate5m=0 rate15m=0" + Environment.NewLine); }
public void FireFiresAfterTimePeriodHasExpired() { var innerTrigger = this.mocks.Create <ITrigger>(MockBehavior.Strict).Object; Mock.Get(innerTrigger).Setup(_innerTrigger => _innerTrigger.IntegrationCompleted()).Verifiable(); var expected = new IntegrationRequest(BuildCondition.IfModificationExists, "Test", null); Mock.Get(innerTrigger).Setup(_innerTrigger => _innerTrigger.Fire()) .Returns(expected).Verifiable(); var clock = new TestClock { Now = DateTime.Now }; var trigger = new RollUpTrigger(clock); trigger.MinimumTime = new Timeout(10, TimeUnits.MINUTES); trigger.InnerTrigger = innerTrigger; trigger.IntegrationCompleted(); clock.TimePasses(new TimeSpan(0, 11, 0)); var actual = trigger.Fire(); Assert.AreSame(expected, actual); mocks.VerifyAll(); }
public async Task ProperTerminationTest() { using var clock = new TestClock(); var failed = false; async Task <int> Test() { await clock !.DelayAsync(10).ConfigureAwait(false); return((int)await clock ! .IntervalAsync(TimeSpan.FromMilliseconds(10)) .Select(i => { if (i > 2) { failed = true; } return i; }) .Take(2) .Count() .ConfigureAwait(false)); } var tasks = Enumerable.Range(0, 100).Select(i => Task.Run(Test)).ToArray(); var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(1)); var whenAllTask = Task.WhenAll(tasks); await Task.WhenAny(whenAllTask, timeoutCts.Token.ToTask(false)) .ConfigureAwait(false); Assert.False(timeoutCts.Token.IsCancellationRequested); var results = whenAllTask.Result; Assert.False(failed); Assert.True(results.All(r => r == 2)); }
public void AbsoluteExpirationWorksAcrossLink() { var clock = new TestClock(); var cache = CreateCache(clock); var obj = new object(); string key = "myKey"; string key1 = "myKey1"; var link = new EntryLink(); var trigger = new TestTrigger() { ActiveExpirationCallbacks = true }; cache.Set(key, link, context => { context.SetAbsoluteExpiration(TimeSpan.FromSeconds(5)); return(obj); }); cache.Set(key1, context => { context.AddEntryLink(link); return(obj); }); Assert.StrictEqual(obj, cache.Get(key)); Assert.StrictEqual(obj, cache.Get(key1)); clock.Add(TimeSpan.FromSeconds(10)); object value; Assert.False(cache.TryGetValue(key1, out value)); Assert.False(cache.TryGetValue(key, out value)); }
public async Task SetWithSlidingExpiration_ExtendsExpirationTime(int accessItemAt, int expected) { // Arrange var testClock = new TestClock(); var slidingExpirationWindow = TimeSpan.FromSeconds(10); var key = Guid.NewGuid().ToString(); var cache = GetSqlServerCache(GetCacheOptions(testClock)); var expectedValue = Encoding.UTF8.GetBytes("Hello, World!"); var expectedExpirationTime = testClock.UtcNow.AddSeconds(expected); await cache.SetAsync( key, expectedValue, new DistributedCacheEntryOptions().SetSlidingExpiration(slidingExpirationWindow)); testClock.Add(TimeSpan.FromSeconds(accessItemAt)); // Act await AssertGetCacheItemFromDatabaseAsync( cache, key, expectedValue, slidingExpirationWindow, absoluteExpiration : null, expectedExpirationTime : expectedExpirationTime); }
public void ExpiredLazyTriggerRemovesItemInBackground() { var clock = new TestClock(); var cache = CreateCache(clock); string key = "myKey"; var obj = new object(); var callbackInvoked = new ManualResetEvent(false); var trigger = new TestTrigger() { ActiveExpirationCallbacks = false }; cache.Set(key, context => { context.AddExpirationTrigger(trigger); context.RegisterPostEvictionCallback((subkey, value, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, state: callbackInvoked); return(obj); }); var found = cache.TryGetValue(key, out obj); Assert.True(found); clock.Add(TimeSpan.FromMinutes(2)); trigger.IsExpired = true; var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity. Assert.True(callbackInvoked.WaitOne(100), "Callback"); found = cache.TryGetValue(key, out obj); Assert.False(found); }
public async Task CookieExpirationCanBeOverridenInSignin() { var clock = new TestClock(); var server = CreateServer(options => { options.SystemClock = clock; options.ExpireTimeSpan = TimeSpan.FromMinutes(10); options.SlidingExpiration = false; }, context => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), new AuthenticationProperties() { ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)) })); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.Null(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); Assert.Null(transaction4.SetCookie); Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name)); }
public void AbsoluteExpirationExpiresInBackground() { var clock = new TestClock(); var cache = CreateCache(clock); var key = "myKey"; var obj = new object(); var callbackInvoked = new ManualResetEvent(false); var result = cache.Set(key, context => { context.SetAbsoluteExpiration(clock.UtcNow + TimeSpan.FromMinutes(1)); context.RegisterPostEvictionCallback((subkey, value, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, state: callbackInvoked); return(obj); }); Assert.Same(obj, result); var found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(obj, result); clock.Add(TimeSpan.FromMinutes(2)); var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity. Assert.True(callbackInvoked.WaitOne(100), "Callback"); found = cache.TryGetValue(key, out result); Assert.False(found); Assert.Null(result); }
public void NestedLinkContextsCanAggregate() { var clock = new TestClock(); var cache = CreateCache(clock); var obj = new object(); string key2 = "myKey2"; string key3 = "myKey3"; var expirationToken2 = new TestExpirationToken() { ActiveChangeCallbacks = true }; var expirationToken3 = new TestExpirationToken() { ActiveChangeCallbacks = true }; IEntryLink link1 = null; IEntryLink link2 = null; using (link1 = cache.CreateLinkingScope()) { cache.Set(key2, obj, new MemoryCacheEntryOptions() .AddExpirationToken(expirationToken2) .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))); using (link2 = cache.CreateLinkingScope()) { cache.Set(key3, obj, new MemoryCacheEntryOptions() .AddExpirationToken(expirationToken3) .SetAbsoluteExpiration(TimeSpan.FromSeconds(15))); } } Assert.Equal(1, link1.ExpirationTokens.Count()); Assert.NotNull(link1.AbsoluteExpiration); Assert.Equal(clock.UtcNow + TimeSpan.FromSeconds(10), link1.AbsoluteExpiration); Assert.Equal(1, link2.ExpirationTokens.Count()); Assert.NotNull(link2.AbsoluteExpiration); Assert.Equal(clock.UtcNow + TimeSpan.FromSeconds(15), link2.AbsoluteExpiration); }
public void SlidingExpirationRenewedByAccessUntilAbsoluteExpiration() { var clock = new TestClock(); var cache = CreateCache(clock); var key = "myKey"; var obj = new object(); var result = cache.Set(key, context => { context.SetSlidingExpiration(TimeSpan.FromMinutes(1)); context.SetAbsoluteExpiration(TimeSpan.FromMinutes(2)); return(obj); }); Assert.Same(obj, result); var found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(obj, result); for (int i = 0; i < 7; i++) { clock.Add(TimeSpan.FromSeconds(15)); found = cache.TryGetValue(key, out result); Assert.True(found); Assert.Same(obj, result); } clock.Add(TimeSpan.FromSeconds(15)); found = cache.TryGetValue(key, out result); Assert.False(found); Assert.Null(result); }
public async Task CookieExpirationCanBeOverridenInSignin() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = false }, context => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), new AuthenticationProperties() { ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)) })); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(3)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.Null(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); Assert.Null(transaction4.SetCookie); Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name)); }
public OAuth2TestServer(Action<OAuth2TestServer> configure = null) { var clock = new TestClock(); Options = new OAuthAuthorizationServerOptions { AuthorizeEndpointPath = new PathString("/authorize"), TokenEndpointPath = new PathString("/token"), Provider = new OAuthAuthorizationServerProvider { OnGrantAuthorizationCode = ctx => { if (ctx.Ticket != null && ctx.Ticket.Identity != null && ctx.Ticket.Identity.IsAuthenticated) { ctx.Validated(); } return Task.FromResult(0); }, OnGrantRefreshToken = ctx => { if (ctx.Ticket != null && ctx.Ticket.Identity != null && ctx.Ticket.Identity.IsAuthenticated) { ctx.Validated(); } return Task.FromResult(0); }, OnValidateClientRedirectUri = ctx => { if (ctx.ClientId == "alpha") { ctx.Validated("https://gamma.com/return"); } else if (ctx.ClientId == "alpha2") { ctx.Validated("https://gamma2.com/return"); } else if (ctx.ClientId == "alpha3") { ctx.Validated("https://gamma3.com/return"); } return Task.FromResult(0); }, OnValidateClientAuthentication = ctx => { string clientId; string clientSecret; if (ctx.TryGetBasicCredentials(out clientId, out clientSecret) || ctx.TryGetFormCredentials(out clientId, out clientSecret)) { if (clientId == "alpha" && clientSecret == "beta") { ctx.Validated(); } else if (clientId == "alpha2" && clientSecret == "beta2") { ctx.Validated(); } else if (clientId == "alpha3" && String.IsNullOrEmpty(clientSecret)) { ctx.Validated(); } } return Task.FromResult(0); } }, AuthorizationCodeProvider = new InMemorySingleUseReferenceProvider(), SystemClock = clock, }; BearerOptions = new OAuthBearerAuthenticationOptions { Provider = new OAuthBearerAuthenticationProvider(), AccessTokenProvider = Options.AccessTokenProvider, SystemClock = clock, }; if (configure != null) { configure(this); } Configure(app => { app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.UseOAuthBearerAuthentication(BearerOptions); app.UseOAuthAuthorizationServer(Options); app.Use(async (ctx, next) => { if (ctx.Request.Path == Options.AuthorizeEndpointPath && OnAuthorizeEndpoint != null) { await OnAuthorizeEndpoint(ctx); } else if (ctx.Request.Path == new PathString("/testpath") && OnTestpathEndpoint != null) { await OnTestpathEndpoint(ctx); } else if (ctx.Request.Path == new PathString("/me")) { await MeEndpoint(ctx); } else { await next(); } }); }); }
public async Task CookieCanBeRejectedAndSignedOutByValidator() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = false, Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.RejectPrincipal(); ctx.HttpContext.Authentication.SignOutAsync("Cookies"); return Task.FromResult(0); } } }, context => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))))); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Contains(".AspNetCore.Cookies=; expires=", transaction2.SetCookie); Assert.Null(FindClaimValue(transaction2, ClaimTypes.Name)); }
public async Task CookieValidatorOnlyCalledOnce() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = false, Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { ctx.ShouldRenew = true; return Task.FromResult(0); } } }, context => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))))); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.NotNull(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(5)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue); Assert.NotNull(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(6)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction4.SetCookie); Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(5)); var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue); Assert.Null(transaction5.SetCookie); Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name)); }
public async Task CookieTurns401ToAccessDeniedWhenSetWithCookie() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, AccessDeniedPath = new PathString("/accessdenied") }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/challenge", transaction1.CookieNameValue); Assert.Equal(HttpStatusCode.Redirect, transaction2.Response.StatusCode); var location = transaction2.Response.Headers.Location; Assert.Equal("/accessdenied", location.LocalPath); }
public async Task CookieIsRenewedWithSlidingExpiration() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = true }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(4)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(4)); // transaction4 should arrive with a new SetCookie value var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.NotNull(transaction4.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(4)); var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue); Assert.Null(transaction5.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name)); }
public async Task CookieUsesPathBaseByDefault() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions(), context => { Assert.Equal(new PathString("/base"), context.Request.PathBase); return context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))); }, new Uri("http://example.com/base")); var transaction1 = await SendAsync(server, "http://example.com/base/testpath"); Assert.True(transaction1.SetCookie.Contains("path=/base")); }
public async Task CookieTurnsChallengeIntoForbidWithCookie(bool automatic) { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { AutomaticAuthenticate = automatic, SystemClock = clock }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var url = "http://example.com/challenge"; var transaction2 = await SendAsync(server, url, transaction1.CookieNameValue); Assert.Equal(HttpStatusCode.Redirect, transaction2.Response.StatusCode); var location = transaction2.Response.Headers.Location; Assert.Equal("/Account/AccessDenied", location.LocalPath); Assert.Equal("?ReturnUrl=%2Fchallenge", location.Query); }
public async Task CookieForbidRedirectsWithoutCookie(bool automatic) { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { AutomaticAuthenticate = automatic, SystemClock = clock }, SignInAsAlice); var url = "http://example.com/forbid"; var transaction = await SendAsync(server, url); Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode); var location = transaction.Response.Headers.Location; Assert.Equal("/Account/AccessDenied", location.LocalPath); }
public async Task CookieAppliesClaimsTransform() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock }, SignInAsAlice, baseAddress: null, claimsTransform: new ClaimsTransformationOptions { Transformer = new ClaimsTransformer { OnTransform = context => { if (!context.Principal.Identities.Any(i => i.AuthenticationType == "xform")) { // REVIEW: Xform runs twice, once on Authenticate, and then once from the middleware var id = new ClaimsIdentity("xform"); id.AddClaim(new Claim("xform", "yup")); context.Principal.AddIdentity(id); } return Task.FromResult(context.Principal); } } }); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.Equal("yup", FindClaimValue(transaction2, "xform")); Assert.Null(FindClaimValue(transaction2, "sync")); }
public async Task CookieExpirationCanBeOverridenInEvent() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = false, Events = new CookieAuthenticationEvents() { OnSigningIn = context => { context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)); return Task.FromResult(0); } } }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(3)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(3)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction4.SetCookie); Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name)); }
public async Task ShouldRenewUpdatesIssuedExpiredUtc(bool sliding) { var clock = new TestClock(); DateTimeOffset? lastValidateIssuedDate = null; DateTimeOffset? lastExpiresDate = null; var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = sliding, Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => { lastValidateIssuedDate = ctx.Properties.IssuedUtc; lastExpiresDate = ctx.Properties.ExpiresUtc; ctx.ShouldRenew = true; return Task.FromResult(0); } } }, context => context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))))); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.NotNull(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.NotNull(lastValidateIssuedDate); Assert.NotNull(lastExpiresDate); var firstIssueDate = lastValidateIssuedDate; var firstExpiresDate = lastExpiresDate; clock.Add(TimeSpan.FromMinutes(1)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue); Assert.NotNull(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); clock.Add(TimeSpan.FromMinutes(2)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue); Assert.NotNull(transaction4.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name)); Assert.NotEqual(lastValidateIssuedDate, firstIssueDate); Assert.NotEqual(firstExpiresDate, lastExpiresDate); }
public async Task CookieStopsWorkingAfterExpiration() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, ExpireTimeSpan = TimeSpan.FromMinutes(10), SlidingExpiration = false }, SignInAsAlice); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(7)); var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); clock.Add(TimeSpan.FromMinutes(7)); var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue); Assert.Null(transaction2.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name)); Assert.Null(transaction3.SetCookie); Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name)); Assert.Null(transaction4.SetCookie); Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name)); }
public async Task CookieChallengeWithUnauthorizedRedirectsToLoginIfNotAuthenticated() { var clock = new TestClock(); var server = CreateServer(new CookieAuthenticationOptions { SystemClock = clock, LoginPath = new PathString("/page") }); var transaction1 = await SendAsync(server, "http://example.com/testpath"); var transaction2 = await SendAsync(server, "http://example.com/unauthorized", transaction1.CookieNameValue); Assert.Equal(HttpStatusCode.Redirect, transaction2.Response.StatusCode); }