public async Task MaintainOnlyOldIndexesWithNoExistingAliasesAsync()
        {
            using (TestSystemClock.Install()) {
                TestSystemClock.SetFrozenTime(SystemClock.UtcNow.EndOfYear());

                var index = new MonthlyEmployeeIndex(_configuration, 1)
                {
                    MaxIndexAge = SystemClock.UtcNow.EndOfMonth() - SystemClock.UtcNow.SubtractMonths(12).StartOfMonth()
                };

                await index.EnsureIndexAsync(SystemClock.UtcNow.SubtractMonths(12));

                var existsResponse = await _client.Indices.ExistsAsync(index.GetIndex(SystemClock.UtcNow.SubtractMonths(12)));

                _logger.LogRequest(existsResponse);
                Assert.True(existsResponse.ApiCall.Success);
                Assert.True(existsResponse.Exists);

                index.MaxIndexAge = SystemClock.UtcNow.EndOfMonth() - SystemClock.UtcNow.StartOfMonth();
                await DeleteAliasesAsync(index.GetVersionedIndex(SystemClock.UtcNow.SubtractMonths(12)));

                await index.MaintainAsync();

                existsResponse = await _client.Indices.ExistsAsync(index.GetIndex(SystemClock.UtcNow.SubtractMonths(12)));

                _logger.LogRequest(existsResponse);
                Assert.True(existsResponse.ApiCall.Success);
                Assert.False(existsResponse.Exists);
            }
        }
Esempio n. 2
0
        public async Task AsyncClientStreamingCall_DeadlineDuringSend_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var testSink          = new TestSink();
            var testLoggerFactory = new TestLoggerFactory(testSink, true);

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var content = (PushStreamContent <HelloRequest, HelloReply>)request.Content !;
                await content.PushComplete.DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker         = HttpClientCallInvokerFactory.Create(httpClient, systemClock: testSystemClock, loggerFactory: testLoggerFactory);
            var deadline        = testSystemClock.UtcNow.AddSeconds(0.1);

            // Act
            var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: deadline));

            // Assert
            var responseTask = call.ResponseAsync;

            // Update time so deadline exceeds correctly
            testSystemClock.UtcNow = deadline;

            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);

            var deadlineExceededLogCount = testSink.Writes.Count(s => s.EventId.Name == "DeadlineExceeded");

            Assert.AreEqual(1, deadlineExceededLogCount);
        }
        public async Task Start_IntervalSet_MultipleCallbacks()
        {
            // Arrange
            const int waitForCallCount = 10;
            var       currentCallCount = 0;
            var       tcs             = new TaskCompletionSource <ResolverResult>(TaskCreationOptions.RunContinuationsAsynchronously);
            var       testSystemClock = new TestSystemClock(DateTime.UtcNow);

            var dnsResolver = CreateDnsResolver(new Uri("dns:///localhost"), refreshInterval: TimeSpan.FromSeconds(0.05));

            dnsResolver.SystemClock = testSystemClock;

            // Act
            dnsResolver.Start(r =>
            {
                // Avoid rate limit.
                testSystemClock.UtcNow = testSystemClock.UtcNow + TimeSpan.FromSeconds(20);

                if (Interlocked.Increment(ref currentCallCount) >= waitForCallCount)
                {
                    tcs.SetResult(r);
                }
            });

            // Assert
            var result = await tcs.Task.DefaultTimeout();

            Assert.NotNull(result);
            Assert.Greater(result !.Addresses !.Count, 0);
        }
        public async Task AnnouncementComponent_Returns_LatestAlbum()
        {
            // Arrange
            var today = new DateTime(year: 2002, month: 10, day: 30);

            var dbContext = _serviceProvider.GetRequiredService <MusicStoreContext>();
            var cache     = _serviceProvider.GetRequiredService <IMemoryCache>();
            var clock     = new TestSystemClock()
            {
                UtcNow = today
            };

            var announcementComponent = new AnnouncementComponent(dbContext, cache, clock);

            PopulateData(dbContext, latestAlbumDate: today);

            // Action
            var result = await announcementComponent.InvokeAsync();

            // Assert
            Assert.NotNull(result);
            var viewResult = Assert.IsType <ViewViewComponentResult>(result);

            Assert.Null(viewResult.ViewName);
            var albumResult = Assert.IsType <Album>(viewResult.ViewData.Model);

            Assert.Equal(today, albumResult.Created.Date);
        }
        public virtual async Task CanSetMinMaxExpirationAsync()
        {
            var cache = GetCacheClient();

            if (cache == null)
            {
                return;
            }

            using (cache) {
                await cache.RemoveAllAsync();

                using (TestSystemClock.Install()) {
                    var now = DateTime.UtcNow;
                    TestSystemClock.SetFrozenTime(now);

                    var expires = DateTime.MaxValue - now.AddDays(1);
                    Assert.True(await cache.SetAsync("test1", 1, expires));
                    Assert.False(await cache.SetAsync("test2", 1, DateTime.MinValue));
                    Assert.True(await cache.SetAsync("test3", 1, DateTime.MaxValue));
                    Assert.True(await cache.SetAsync("test4", 1, DateTime.MaxValue - now.AddDays(-1)));

                    Assert.Equal(1, (await cache.GetAsync <int>("test1")).Value);
                    Assert.InRange((await cache.GetExpirationAsync("test1")).Value, expires.Subtract(TimeSpan.FromSeconds(10)), expires);

                    Assert.False(await cache.ExistsAsync("test2"));
                    Assert.Equal(1, (await cache.GetAsync <int>("test3")).Value);
                    Assert.False((await cache.GetExpirationAsync("test3")).HasValue);
                    Assert.Equal(1, (await cache.GetAsync <int>("test4")).Value);
                    Assert.False((await cache.GetExpirationAsync("test4")).HasValue);
                }
            }
        }
        public async Task MaintainOnlyOldIndexesWithPartialAliasesAsync()
        {
            using (TestSystemClock.Install()) {
                SystemClock.Test.SetFixedTime(SystemClock.UtcNow.EndOfYear());

                var index = new MonthlyEmployeeIndex(_configuration, 1)
                {
                    MaxIndexAge = SystemClock.UtcNow.EndOfMonth() - SystemClock.UtcNow.SubtractMonths(12).StartOfMonth()
                };

                await index.EnsureIndexAsync(SystemClock.UtcNow.SubtractMonths(11));

                await index.EnsureIndexAsync(SystemClock.UtcNow.SubtractMonths(12));

                var existsResponse = await _client.IndexExistsAsync(index.GetIndex(SystemClock.UtcNow.SubtractMonths(12)));

                _logger.Trace(() => existsResponse.GetRequest());
                Assert.True(existsResponse.IsValid);
                Assert.True(existsResponse.Exists);

                index.MaxIndexAge = SystemClock.UtcNow.EndOfMonth() - SystemClock.UtcNow.StartOfMonth();
                await DeleteAliasesAsync(index.GetVersionedIndex(SystemClock.UtcNow.SubtractMonths(12)));

                await index.MaintainAsync();

                existsResponse = await _client.IndexExistsAsync(index.GetIndex(SystemClock.UtcNow.SubtractMonths(12)));

                _logger.Trace(() => existsResponse.GetRequest());
                Assert.True(existsResponse.IsValid);
                Assert.False(existsResponse.Exists);
            }
        }
Esempio n. 7
0
        public async Task AsyncClientStreamingCall_DeadlineBeforeWrite_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var tcs        = new TaskCompletionSource <object?>(TaskCreationOptions.RunContinuationsAsynchronously);
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                await tcs.Task.DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK));
            });
            var systemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker     = HttpClientCallInvokerFactory.Create(httpClient, systemClock: systemClock);

            // Act
            var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: systemClock.UtcNow.AddMilliseconds(10)));

            // Ensure the deadline has passed
            systemClock.UtcNow = systemClock.UtcNow.AddMilliseconds(200);
            await Task.Delay(200);

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.RequestStream.WriteAsync(new HelloRequest())).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
        }
Esempio n. 8
0
        public async Task AsyncUnaryCall_SetVeryLargeDeadline_MaximumDeadlineTimeoutSent()
        {
            // Arrange
            var testSink          = new TestSink();
            var testLoggerFactory = new TestLoggerFactory(testSink, true);

            HttpRequestMessage?httpRequestMessage = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var streamContent = await ClientTestHelpers.CreateResponseContent(new HelloReply()).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var deadline        = testSystemClock.UtcNow.AddDays(2000);
            var invoker         = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory: testLoggerFactory, systemClock: testSystemClock);

            // Act
            await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline : deadline), new HelloRequest());

            // Assert
            Assert.IsNotNull(httpRequestMessage);
            Assert.AreEqual("99999999S", httpRequestMessage !.Headers.GetValues(GrpcProtocolConstants.TimeoutHeader).Single());

            var s = testSink.Writes.SingleOrDefault(w => w.EventId.Name == "DeadlineTimeoutTooLong");

            Assert.AreEqual("Deadline timeout 2000.00:00:00 is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used.", s.Message);
        }
Esempio n. 9
0
        public async Task AsyncClientStreamingCall_DeadlineDuringSend_ThrowOperationCanceledOnCancellation_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                var content = (PushStreamContent <HelloRequest, HelloReply>)request.Content;
                await content.PushComplete.DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker         = HttpClientCallInvokerFactory.Create(httpClient, systemClock: testSystemClock, configure: o => o.ThrowOperationCanceledOnCancellation = true);
            var deadline        = testSystemClock.UtcNow.AddSeconds(0.1);

            // Act
            var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: deadline));

            // Assert
            var responseTask = call.ResponseAsync;

            // Update time so deadline exceeds correctly
            testSystemClock.UtcNow = deadline;

            await ExceptionAssert.ThrowsAsync <OperationCanceledException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
        }
Esempio n. 10
0
        public async Task AsyncUnaryCall_Http3ServerResetsCancelCodeAfterDeadline_DeadlineStatus()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddNUnitLogger();
            var serviceProvider = services.BuildServiceProvider();

            var syncPoint = new SyncPoint(runContinuationsAsynchronously: true);

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                await syncPoint.WaitToContinue();
                throw new QuicStreamAbortedException("Stream aborted by peer (268).");
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker         = HttpClientCallInvokerFactory.Create(
                httpClient,
                systemClock: testSystemClock,
                loggerFactory: serviceProvider.GetRequiredService <ILoggerFactory>());
            var deadline = invoker.Channel.Clock.UtcNow.AddSeconds(1);

            // Act
            var responseTask = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: deadline), new HelloRequest()).ResponseAsync;

            await syncPoint.WaitForSyncPoint().DefaultTimeout();

            testSystemClock.UtcNow = deadline;
            syncPoint.Continue();

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
        }
Esempio n. 11
0
        public async Task AsyncUnaryCall_ServerResetsCancelCodeBeforeDeadline_CancelStatus()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddNUnitLogger();
            var serviceProvider = services.BuildServiceProvider();

            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return(Task.FromException <HttpResponseMessage>(new Http2StreamException("The HTTP/2 server reset the stream. HTTP/2 error code 'CANCEL' (0x8).")));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker         = HttpClientCallInvokerFactory.Create(
                httpClient,
                systemClock: testSystemClock,
                loggerFactory: serviceProvider.GetRequiredService <ILoggerFactory>());

            // Act
            var responseTask = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: invoker.Channel.Clock.UtcNow.AddSeconds(1)), new HelloRequest()).ResponseAsync;

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
        }
Esempio n. 12
0
 public EventIndexTests(ITestOutputHelper output) : base(output)
 {
     TestSystemClock.SetFrozenTime(new DateTime(2015, 2, 13, 0, 0, 0, DateTimeKind.Utc));
     _repository = GetService <IEventRepository>();
     _validator  = GetService <PersistentEventQueryValidator>();
     CreateEventsAsync().GetAwaiter().GetResult();
 }
        public async Task GetDateOffsetAggregationsAsync(DateTime utcNow)
        {
            using (TestSystemClock.Install()) {
                SystemClock.Test.SetFixedTime(utcNow);

                var today = SystemClock.OffsetNow.Floor(TimeSpan.FromMilliseconds(1));

                await _employeeRepository.AddAsync(new List <Employee> {
                    EmployeeGenerator.Generate(nextReview: today.SubtractDays(2)),
                    EmployeeGenerator.Generate(nextReview: today.SubtractDays(1)),
                    EmployeeGenerator.Generate(nextReview: today)
                }, o => o.ImmediateConsistency());

                const string aggregations = "min:nextReview max:nextReview date:nextReview";
                var          result       = await _employeeRepository.GetCountByQueryAsync(q => q.AggregationsExression(aggregations));

                Assert.Equal(3, result.Total);
                Assert.Equal(3, result.Aggregations.Count);

                // Dates are always returned in utc.
                AssertEqual(DateTime.SpecifyKind(today.UtcDateTime.SubtractDays(2), DateTimeKind.Utc), result.Aggregations.Min <DateTime>("min_nextReview")?.Value);
                AssertEqual(DateTime.SpecifyKind(today.UtcDateTime, DateTimeKind.Utc), result.Aggregations.Max <DateTime>("max_nextReview")?.Value);

                var dateHistogramAgg = result.Aggregations.DateHistogram("date_nextReview");
                Assert.Equal(3, dateHistogramAgg.Buckets.Count);
                var oldestDate = DateTime.SpecifyKind(today.UtcDateTime.Date.SubtractDays(2), DateTimeKind.Utc);
                foreach (var bucket in dateHistogramAgg.Buckets)
                {
                    AssertEqual(oldestDate, bucket.Date);
                    Assert.Equal(1, bucket.Total);
                    oldestDate = oldestDate.AddDays(1);
                }
            }
        }
Esempio n. 14
0
        public async Task AsyncUnaryCall_StartPastDeadline_RequestMessageContainsMinDeadlineHeader()
        {
            // Arrange
            var testSink          = new TestSink();
            var testLoggerFactory = new TestLoggerFactory(testSink, true);

            HttpRequestMessage?httpRequestMessage = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var streamContent = await ClientTestHelpers.CreateResponseContent(new HelloReply()).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker         = HttpClientCallInvokerFactory.Create(
                httpClient,
                systemClock: testSystemClock,
                loggerFactory: testLoggerFactory);

            // Act
            var responseTask = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: invoker.Channel.Clock.UtcNow.AddSeconds(-1)), new HelloRequest()).ResponseAsync;

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => responseTask).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);

            // Ensure no HTTP request
            Assert.IsNull(httpRequestMessage);

            // Ensure deadline timer wasn't started
            Assert.IsFalse(testSink.Writes.Any(w => w.EventId.Name == "StartingDeadlineTimeout"));
        }
Esempio n. 15
0
    public EventStackFilterTests(ITestOutputHelper output, AppWebHostFactory factory) : base(output, factory)
    {
        TestSystemClock.SetFrozenTime(new DateTime(2015, 2, 13, 0, 0, 0, DateTimeKind.Utc));
        _stackRepository = GetService <IStackRepository>();
        _eventRepository = GetService <IEventRepository>();

        Log.SetLogLevel <EventRepository>(LogLevel.Trace);
        Log.SetLogLevel <StackRepository>(LogLevel.Trace);
    }
Esempio n. 16
0
 public void CanGetTime()
 {
     using (TestSystemClock.Install()) {
         var now = DateTime.UtcNow;
         TestSystemClock.SetFrozenTime(now);
         Assert.Equal(now, SystemClock.UtcNow);
         Assert.Equal(now.ToLocalTime(), SystemClock.Now);
         Assert.Equal(now, SystemClock.OffsetUtcNow);
         Assert.Equal(now.ToLocalTime(), SystemClock.OffsetNow);
         Assert.Equal(DateTimeOffset.Now.Offset, SystemClock.TimeZoneOffset);
     }
 }
Esempio n. 17
0
        public async Task CanCancelContinuousJobs()
        {
            using (TestSystemClock.Install()) {
                var job = new HelloWorldJob();
                job.RunContinuous(TimeSpan.FromSeconds(1), 5, TimeSpan.FromMilliseconds(100).ToCancellationToken());
                Assert.Equal(1, job.RunCount);

                var runnerTask = new JobRunner(job, Log, instanceCount: 5, iterationLimit: 10000, interval: TimeSpan.FromMilliseconds(1)).RunAsync(TimeSpan.FromMilliseconds(500).ToCancellationToken());
                await SystemClock.SleepAsync(TimeSpan.FromSeconds(1));

                await runnerTask;
            }
        }
Esempio n. 18
0
        public void CanSetLocalFixedTime()
        {
            using (TestSystemClock.Install()) {
                var now    = DateTime.Now;
                var utcNow = now.ToUniversalTime();
                TestSystemClock.SetFrozenTime(now);

                Assert.Equal(now, SystemClock.Now);
                Assert.Equal(now, SystemClock.OffsetNow);
                Assert.Equal(utcNow, SystemClock.UtcNow);
                Assert.Equal(utcNow, SystemClock.OffsetUtcNow);
                Assert.Equal(DateTimeOffset.Now.Offset, SystemClock.TimeZoneOffset);
            }
        }
Esempio n. 19
0
        public void CanSetUtcFixedTime()
        {
            using (TestSystemClock.Install()) {
                var utcNow = DateTime.UtcNow;
                var now    = utcNow.ToLocalTime();
                SystemClock.Test.SetFixedTime(utcNow);

                Assert.Equal(now, SystemClock.Now);
                Assert.Equal(now, SystemClock.OffsetNow);
                Assert.Equal(utcNow, SystemClock.UtcNow);
                Assert.Equal(utcNow, SystemClock.OffsetUtcNow);
                Assert.Equal(DateTimeOffset.Now.Offset, SystemClock.TimeZoneOffset);
            }
        }
Esempio n. 20
0
        public void CanSetTimeZone()
        {
            using (TestSystemClock.Install()) {
                var utcNow = DateTime.UtcNow;
                var now    = new DateTime(utcNow.AddHours(1).Ticks, DateTimeKind.Local);
                TestSystemClock.SetFrozenTime(utcNow);
                TestSystemClock.SetTimeZoneOffset(TimeSpan.FromHours(1));

                Assert.Equal(utcNow, SystemClock.UtcNow);
                Assert.Equal(utcNow, SystemClock.OffsetUtcNow);
                Assert.Equal(now, SystemClock.Now);
                Assert.Equal(new DateTimeOffset(now.Ticks, TimeSpan.FromHours(1)), SystemClock.OffsetNow);
                Assert.Equal(TimeSpan.FromHours(1), SystemClock.TimeZoneOffset);
            }
        }
Esempio n. 21
0
        public async Task CanRunJobsWithIntervalBetweenFailingJob()
        {
            using (TestSystemClock.Install()) {
                var time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                TestSystemClock.SetFrozenTime(time);
                TestSystemClock.UseFakeSleep();

                var job      = new FailingJob(Log);
                var interval = TimeSpan.FromHours(.75);

                await job.RunContinuousAsync(iterationLimit : 2, interval : interval);

                Assert.Equal(2, job.RunCount);
                Assert.Equal(interval, (SystemClock.UtcNow - time));
            }
        }
        public async Task CanRoundTripById()
        {
            using var _ = TestSystemClock.Install();
            TestSystemClock.SetFrozenTime(new DateTime(2020, 6, 16, 20, 0, 0, DateTimeKind.Local));

            Assert.Equal(0, await _dailyRepository.CountAsync());

            var utcNow   = SystemClock.UtcNow;
            var logEvent = await _dailyRepository.AddAsync(LogEventGenerator.Generate(createdUtc: utcNow, date: utcNow.SubtractDays(1)), o => o.ImmediateConsistency());

            Assert.NotNull(logEvent?.Id);

            var ev = await _dailyRepository.GetByIdAsync(logEvent.Id);

            Assert.NotNull(ev);
            Assert.Equal(ev.Date, ObjectId.Parse(ev.Id).CreationTime);
            Assert.NotEqual(ev.Date, ev.CreatedUtc);
        }
Esempio n. 23
0
        public async Task CanCancelContinuousJobs()
        {
            using (TestSystemClock.Install()) {
                var job = new HelloWorldJob(Log);
                using (var timeoutCancellationTokenSource = new CancellationTokenSource(100)) {
                    await job.RunContinuousAsync(TimeSpan.FromSeconds(1), 5, timeoutCancellationTokenSource.Token);
                }

                Assert.Equal(1, job.RunCount);

                using (var timeoutCancellationTokenSource = new CancellationTokenSource(500)) {
                    var runnerTask = new JobRunner(job, Log, instanceCount: 5, iterationLimit: 10000, interval: TimeSpan.FromMilliseconds(1)).RunAsync(timeoutCancellationTokenSource.Token);
                    await SystemClock.SleepAsync(TimeSpan.FromSeconds(1));

                    await runnerTask;
                }
            }
        }
        public async Task MonthlyIndexMaxAgeAsync(DateTime utcNow)
        {
            using (TestSystemClock.Install()) {
                SystemClock.Test.SetFixedTime(utcNow);

                var index = new MonthlyEmployeeIndex(_configuration, 1)
                {
                    MaxIndexAge = SystemClock.UtcNow.EndOfMonth() - SystemClock.UtcNow.StartOfMonth()
                };
                await index.DeleteAsync();

                using (new DisposableAction(() => index.DeleteAsync().GetAwaiter().GetResult())) {
                    await index.ConfigureAsync();

                    await index.EnsureIndexAsync(utcNow);

                    var existsResponse = await _client.IndexExistsAsync(index.GetIndex(utcNow));

                    _logger.Trace(() => existsResponse.GetRequest());
                    Assert.True(existsResponse.IsValid);
                    Assert.True(existsResponse.Exists);

                    await index.EnsureIndexAsync(utcNow.Subtract(index.MaxIndexAge.GetValueOrDefault()));

                    existsResponse = await _client.IndexExistsAsync(index.GetIndex(utcNow.Subtract(index.MaxIndexAge.GetValueOrDefault())));

                    _logger.Trace(() => existsResponse.GetRequest());
                    Assert.True(existsResponse.IsValid);
                    Assert.True(existsResponse.Exists);

                    var endOfTwoMonthsAgo = utcNow.SubtractMonths(2).EndOfMonth();
                    if (utcNow - endOfTwoMonthsAgo >= index.MaxIndexAge.GetValueOrDefault())
                    {
                        await Assert.ThrowsAsync <ArgumentException>(async() => await index.EnsureIndexAsync(endOfTwoMonthsAgo));

                        existsResponse = await _client.IndexExistsAsync(index.GetIndex(endOfTwoMonthsAgo));

                        _logger.Trace(() => existsResponse.GetRequest());
                        Assert.True(existsResponse.IsValid);
                        Assert.False(existsResponse.Exists);
                    }
                }
            }
        }
Esempio n. 25
0
        public async Task AsyncServerStreamingCall_DeadlineStatusResponse_ThrowOperationCanceledOnCancellation_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.OK, new StringContent(string.Empty), StatusCode.DeadlineExceeded));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker = HttpClientCallInvokerFactory.Create(httpClient, systemClock: testSystemClock, configure: o => o.ThrowOperationCanceledOnCancellation = true, disableClientDeadline: true);

            // Act
            var call = invoker.AsyncServerStreamingCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: testSystemClock.UtcNow.AddSeconds(0.5)), new HelloRequest());

            // Assert
            var moveNextTask = call.ResponseStream.MoveNext(CancellationToken.None);

            await ExceptionAssert.ThrowsAsync<OperationCanceledException>(() => moveNextTask).DefaultTimeout();
            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
        }
Esempio n. 26
0
        public async Task AsyncClientStreamingCall_DeadlineStatusResponse_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                return Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.OK, new StringContent(string.Empty), StatusCode.DeadlineExceeded));
            });
            var testSystemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker = HttpClientCallInvokerFactory.Create(httpClient, systemClock: testSystemClock, disableClientDeadline: true);

            // Act
            var call = invoker.AsyncClientStreamingCall<HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: testSystemClock.UtcNow.AddSeconds(0.5)));

            // Assert
            var responseTask = call.ResponseAsync;

            var ex = await ExceptionAssert.ThrowsAsync<RpcException>(() => responseTask).DefaultTimeout();
            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
        }
Esempio n. 27
0
        public async Task AsyncClientStreamingCall_DeadlineDuringWrite_ResponseThrowsDeadlineExceededStatus()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(request =>
            {
                var stream  = new SyncPointMemoryStream();
                var content = new StreamContent(stream);
                return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.OK, content, grpcStatusCode: null)));
            });
            var systemClock = new TestSystemClock(DateTime.UtcNow);
            var invoker     = HttpClientCallInvokerFactory.Create(httpClient, systemClock: systemClock);

            // Act
            var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline: systemClock.UtcNow.AddMilliseconds(10)));

            // Assert
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.RequestStream.WriteAsync(new HelloRequest())).DefaultTimeout();

            Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode);
            Assert.AreEqual(StatusCode.DeadlineExceeded, call.GetStatus().StatusCode);
        }
Esempio n. 28
0
        public void CanSleep()
        {
            using (TestSystemClock.Install()) {
                var sw = Stopwatch.StartNew();
                SystemClock.Sleep(250);
                sw.Stop();
                Assert.InRange(sw.ElapsedMilliseconds, 225, 400);

                TestSystemClock.UseFakeSleep();

                var now = SystemClock.UtcNow;
                sw.Restart();
                SystemClock.Sleep(1000);
                sw.Stop();
                var afterSleepNow = SystemClock.UtcNow;

                Assert.InRange(sw.ElapsedMilliseconds, 0, 30);
                Assert.True(afterSleepNow > now);
                Assert.InRange(afterSleepNow.Subtract(now).TotalMilliseconds, 950, 1100);
            }
        }
        public async Task SetCreatedAndModifiedTimesAsync()
        {
            using (TestSystemClock.Install()) {
                SystemClock.Test.SubtractTime(TimeSpan.FromMilliseconds(100));
                var nowUtc   = SystemClock.UtcNow;
                var employee = await _employeeRepository.AddAsync(EmployeeGenerator.Default);

                Assert.True(employee.CreatedUtc >= nowUtc);
                Assert.True(employee.UpdatedUtc >= nowUtc);

                var createdUtc = employee.CreatedUtc;
                var updatedUtc = employee.UpdatedUtc;

                employee.Name = Guid.NewGuid().ToString();
                SystemClock.Test.AddTime(TimeSpan.FromMilliseconds(100));
                employee = await _employeeRepository.SaveAsync(employee);

                Assert.Equal(createdUtc, employee.CreatedUtc);
                Assert.True(updatedUtc < employee.UpdatedUtc, $"Previous UpdatedUtc: {updatedUtc} Current UpdatedUtc: {employee.UpdatedUtc}");
            }
        }
        public async Task CanCreateMonthlyAliasesAsync(DateTime utcNow)
        {
            using (TestSystemClock.Install()) {
                SystemClock.Test.SetFixedTime(utcNow);

                var index = new MonthlyEmployeeIndex(_configuration, 1);
                await index.DeleteAsync();

                using (new DisposableAction(() => index.DeleteAsync().GetAwaiter().GetResult())) {
                    await index.ConfigureAsync();

                    var repository = new EmployeeRepository(index.Employee);

                    for (int i = 0; i < 4; i++)
                    {
                        var employee = await repository.AddAsync(EmployeeGenerator.Generate(createdUtc: utcNow.SubtractMonths(i)));

                        Assert.NotNull(employee?.Id);

                        Assert.Equal(1, await index.GetCurrentVersionAsync());
                        var existsResponse = await _client.IndexExistsAsync(index.GetIndex(employee.CreatedUtc));

                        _logger.Trace(() => existsResponse.GetRequest());
                        Assert.True(existsResponse.IsValid);
                        Assert.True(existsResponse.Exists);

                        var aliasesResponse = await _client.GetAliasAsync(a => a.Index(index.GetIndex(employee.CreatedUtc)));

                        _logger.Trace(() => aliasesResponse.GetRequest());
                        Assert.True(aliasesResponse.IsValid);
                        Assert.Equal(1, aliasesResponse.Indices.Count);

                        var aliases = aliasesResponse.Indices.Values.Single().Select(s => s.Name).ToList();
                        aliases.Sort();

                        Assert.Equal(GetExpectedEmployeeMonthlyAliases(index, utcNow, employee.CreatedUtc), String.Join(", ", aliases));
                    }
                }
            }
        }
        public async Task AnnouncementComponent_Returns_LatestAlbum()
        {
            // Arrange
            var today = new DateTime(year: 2002, month: 10, day: 30);

            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cache = _serviceProvider.GetRequiredService<IMemoryCache>();
            var clock = new TestSystemClock() { UtcNow = today };

            var announcementComponent = new AnnouncementComponent(dbContext, cache, clock);

            PopulateData(dbContext, latestAlbumDate: today);

            // Action
            var result = await announcementComponent.InvokeAsync();

            // Assert
            Assert.NotNull(result);
            var viewResult = Assert.IsType<ViewViewComponentResult>(result);
            Assert.Null(viewResult.ViewName);
            var albumResult = Assert.IsType<Album>(viewResult.ViewData.Model);
            Assert.Equal(today, albumResult.Created.Date);
        }