public async Task SaveChanges_logs_DataStoreErrorLogState(bool async)
        {
            var loggerFactory = new TestLoggerFactory();
            var serviceProvider = new ServiceCollection()
                .AddEntityFramework()
                .AddInMemoryStore()
                .ServiceCollection()
                .AddInstance<ILoggerFactory>(loggerFactory)
                .BuildServiceProvider();

            using (var context = new BloggingContext(serviceProvider))
            {
                context.Blogs.Add(new BloggingContext.Blog(jimSaysThrow: false) { Url = "http://sample.com" });
                context.SaveChanges();
                context.ChangeTracker.Entries().Single().State = EntityState.Added;

                Exception ex;
                if (async)
                {
                    ex = await Assert.ThrowsAsync<ArgumentException>(() => context.SaveChangesAsync());
                }
                else
                {
                    ex = Assert.Throws<ArgumentException>(() => context.SaveChanges());
                }

                Assert.Same(ex, loggerFactory.Logger.LastDataStoreErrorException);
                Assert.Same(typeof(BloggingContext), loggerFactory.Logger.LastDataStoreErrorState.ContextType);
                Assert.EndsWith(ex.ToString(), loggerFactory.Logger.LastDataStoreErrorFormatter(loggerFactory.Logger.LastDataStoreErrorState, ex));
            }
        }
Exemplo n.º 2
0
        public async void SelectAsync_AmbiguousActions_LogIsCorrect()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor() { DisplayName = "A1" },
                new ActionDescriptor() { DisplayName = "A2" },
            };
            var selector = CreateSelector(actions, loggerFactory);

            var routeContext = CreateRouteContext("POST");
            var actionNames = string.Join(Environment.NewLine, actions.Select(action => action.DisplayName));
            var expectedMessage = "Request matched multiple actions resulting in " +
                $"ambiguity. Matching actions: {actionNames}";

            // Act
            await Assert.ThrowsAsync<AmbiguousActionException>(async () =>
            {
                await selector.SelectAsync(routeContext);
            });

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Exemplo n.º 3
0
        public async Task RouteAsync_FailOnNoAction_LogsCorrectValues()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var mockActionSelector = new Mock<IActionSelector>();
            mockActionSelector.Setup(a => a.SelectAsync(It.IsAny<RouteContext>()))
                .Returns(Task.FromResult<ActionDescriptor>(null));

            var context = CreateRouteContext(
                actionSelector: mockActionSelector.Object,
                loggerFactory: loggerFactory);

            var handler = new MvcRouteHandler();
            var expectedMessage = "No actions matched the current request.";

            // Act
            await handler.RouteAsync(context);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Exemplo n.º 4
0
        public async void AttributeRoute_RouteAsyncNotHandled_LogsCorrectValues()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink);

            var entry = CreateMatchingEntry("api/Store");
            var route = CreateRoutingAttributeRoute(loggerFactory, entry);

            var context = CreateRouteContext("/");

            // Act
            await route.RouteAsync(context);

            // Assert
            Assert.Equal(1, sink.Scopes.Count);
            var scope = sink.Scopes[0];
            Assert.Equal(typeof(AttributeRoute).FullName, scope.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", scope.Scope);

            // There is a record for IsEnabled and one for WriteCore.
            Assert.Equal(2, sink.Writes.Count);

            var enabled = sink.Writes[0];
            Assert.Equal(typeof(AttributeRoute).FullName, enabled.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", enabled.Scope);
            Assert.Null(enabled.State);

            var write = sink.Writes[1];
            Assert.Equal(typeof(AttributeRoute).FullName, write.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", write.Scope);
            var values = Assert.IsType<AttributeRouteRouteAsyncValues>(write.State);
            Assert.Equal("AttributeRoute.RouteAsync", values.Name);
            Assert.Equal(false, values.Handled);
        }
        public RelationalDatabaseModelFactoryTest()
        {
            var factory = new TestLoggerFactory();
            _logger = factory.Logger;

            _factory = new FakeScaffoldingModelFactory(factory);
        }
        public void ActionDiscovery()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink);

            // Act
            CreateActionDescriptors(loggerFactory, 
                                    typeof(SimpleController).GetTypeInfo(), 
                                    typeof(BasicController).GetTypeInfo());

            // Assert
            // 2 controllers, 3 actions
            Assert.Equal(5, sink.Writes.Count);
            Assert.IsType<ControllerModelValues>(sink.Writes[0].State);
            Assert.IsType<ControllerModelValues>(sink.Writes[1].State);

            var actionDescriptorValues = Assert.IsType<ActionDescriptorValues>(sink.Writes[2].State);
            Assert.NotNull(actionDescriptorValues);
            Assert.Equal("EmptyAction", actionDescriptorValues.Name);
            Assert.Equal("Simple", actionDescriptorValues.ControllerName);
            Assert.Equal(typeof(SimpleController), actionDescriptorValues.ControllerTypeInfo);
            Assert.Null(actionDescriptorValues.AttributeRouteInfo.Name);
            Assert.Null(actionDescriptorValues.ActionConstraints);
            Assert.Empty(actionDescriptorValues.FilterDescriptors);
            Assert.Empty(actionDescriptorValues.Parameters);

            actionDescriptorValues = Assert.IsType<ActionDescriptorValues>(sink.Writes[3].State);
            Assert.NotNull(actionDescriptorValues);
            Assert.Equal("Basic", actionDescriptorValues.Name);
            Assert.Equal("Basic", actionDescriptorValues.ControllerName);
            Assert.Equal(typeof(BasicController), actionDescriptorValues.ControllerTypeInfo);
            Assert.Null(actionDescriptorValues.AttributeRouteInfo.Name);
            Assert.NotEmpty(actionDescriptorValues.ActionConstraints);
            Assert.Equal(2, actionDescriptorValues.FilterDescriptors.Count);
            Assert.Empty(actionDescriptorValues.Parameters);

            actionDescriptorValues = Assert.IsType<ActionDescriptorValues>(sink.Writes[4].State);
            Assert.NotNull(actionDescriptorValues);
            Assert.Equal("Basic", actionDescriptorValues.Name);
            Assert.Equal("Basic", actionDescriptorValues.ControllerName);
            Assert.Equal(typeof(BasicController), actionDescriptorValues.ControllerTypeInfo);
            Assert.Null(actionDescriptorValues.AttributeRouteInfo.Name);
            Assert.NotEmpty(actionDescriptorValues.ActionConstraints);
            Assert.Single(actionDescriptorValues.FilterDescriptors);
            Assert.Single(actionDescriptorValues.RouteConstraints);
            Assert.Single(actionDescriptorValues.Parameters);
        }
Exemplo n.º 7
0
        public async Task SessionStart_LogsInformation()
        {
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var builder       = new WebHostBuilder()
                                .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    context.Session.SetString("Key", "Value");
                    return(Task.FromResult(0));
                });
            })
                                .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), loggerFactory);

                services.AddMemoryCache();
                services.AddDistributedMemoryCache();

                services.AddSession();
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync(string.Empty);

                response.EnsureSuccessStatusCode();

                var sessionLogMessages = sink.Writes.OnlyMessagesFromSource <DistributedSession>().ToArray();

                Assert.Equal(2, sessionLogMessages.Length);
                Assert.Contains("started", sessionLogMessages[0].State.ToString());
                Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
                Assert.Contains("stored", sessionLogMessages[1].State.ToString());
                Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
            }
        }
Exemplo n.º 8
0
        public void NamedFormatterGoldenPath()
        {
            // expected output
            TestLoggerFactory expected = BuildNamedOptionsExpectedResult();

            // actual output
            var services = new ServiceCollection();

            services.AddOptions();
            services.AddSingleton <TestLoggerFactory>();
            services.AddSingleton <ILoggerFactory>(sp => sp.GetRequiredService <TestLoggerFactory>());
            services.AddSingleton(typeof(ILogger <>), typeof(TestLogger <>));
            services.AddSingleton <OptionsLogger, TestOptionsLogger>();
            services.ConfigureFormatterResolver <TestOptions, TestOptionsFormatter.Resolver>();
            Enumerable
            .Range(1, 3)
            .ToList()
            .ForEach(i =>
            {
                string name = i.ToString();
                services.Configure <TestOptions>(name, (options => options.IntField = i));
                services.ConfigureNamedOptionForLogging <TestOptions>(name);
            });
            var servicesProvider = services.BuildServiceProvider();

            servicesProvider.GetRequiredService <OptionsLogger>().LogOptions();

            var logFormatters = servicesProvider.GetServices <IOptionFormatter>();

            Assert.Equal(3, logFormatters.Count());
            Assert.True(logFormatters.First() is TestOptionsFormatter);
            Assert.True(logFormatters.ElementAt(1) is TestOptionsFormatter);
            Assert.True(logFormatters.ElementAt(2) is TestOptionsFormatter);
            var logFormatter = servicesProvider.GetService <IOptionFormatterResolver <TestOptions> >();

            Assert.True(logFormatter is TestOptionsFormatter.Resolver);
            var actual = servicesProvider.GetRequiredService <TestLoggerFactory>();

            Assert.Equal(expected.ToString(), actual.ToString());
        }
Exemplo n.º 9
0
        public async Task AsyncUnaryCall_Success_LogToFactory()
        {
            // Arrange
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                // Trigger request stream serialization
                await request.Content !.ReadAsStreamAsync().DefaultTimeout();

                var streamContent = await ClientTestHelpers.CreateResponseContent(new HelloReply
                {
                    Message = "Hello world"
                }).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });

            var testSink      = new TestSink();
            var loggerFactory = new TestLoggerFactory(testSink, true);

            var invoker = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory);

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

            // Assert
            Assert.AreEqual("Hello world", rs.Message);

            var logs = testSink.Writes.Where(w => w.LogLevel >= Microsoft.Extensions.Logging.LogLevel.Debug).ToList();

            Assert.AreEqual("Starting gRPC call. Method type: 'Unary', URI: 'https://localhost/ServiceName/MethodName'.", logs[0].State.ToString());
            AssertScope(logs[0]);

            Assert.AreEqual("Sending message.", logs[1].State.ToString());
            AssertScope(logs[1]);

            Assert.AreEqual("Reading message.", logs[2].State.ToString());
            AssertScope(logs[2]);

            Assert.AreEqual("Finished gRPC call.", logs[3].State.ToString());
            AssertScope(logs[3]);
Exemplo n.º 10
0
        public async Task SessionLogsCacheRefreshException()
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName <SessionMiddleware>,
                TestSink.EnableWithTypeName <SessionMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var builder       = new WebHostBuilder()
                                .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    // The middleware calls context.Session.CommitAsync() once per request
                    return(Task.FromResult(0));
                });
            })
                                .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
                services.AddSingleton <IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
                {
                    DisableRefreshAsync = true
                });
                services.AddCouchbaseSession();
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync(string.Empty);

                response.EnsureSuccessStatusCode();
            }

            var sessionLogMessages = sink.Writes;

            Assert.Equal(1, sessionLogMessages.Count);
            Assert.Contains("Error closing the session.", sessionLogMessages[0].State.ToString());
            Assert.Equal(LogLevel.Error, sessionLogMessages[0].LogLevel);
        }
Exemplo n.º 11
0
        public async Task SessionLoadAsyncCanceledException()
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName <DistributedSession>,
                TestSink.EnableWithTypeName <DistributedSession>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var builder       = new WebHostBuilder()
                                .Configure(app =>
            {
                app.UseSession();
                app.Run(async context =>
                {
                    var cts   = new CancellationTokenSource();
                    var token = cts.Token;
                    cts.Cancel();
                    await Assert.ThrowsAsync <OperationCanceledException>(() => context.Session.LoadAsync(token));
                });
            })
                                .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
                services.AddSingleton <IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
                {
                    DelayGetAsync = true
                });
                services.AddSession();
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync(string.Empty);

                response.EnsureSuccessStatusCode();
            }

            var sessionLogMessages = sink.Writes;

            Assert.Empty(sessionLogMessages);
        }
Exemplo n.º 12
0
        public void LogsFilters_OnlyWhenLogger_IsEnabled()
        {
            // Arrange
            var authFilter           = Mock.Of <IAuthorizationFilter>();
            var asyncAuthFilter      = Mock.Of <IAsyncAuthorizationFilter>();
            var actionFilter         = Mock.Of <IActionFilter>();
            var asyncActionFilter    = Mock.Of <IAsyncActionFilter>();
            var exceptionFilter      = Mock.Of <IExceptionFilter>();
            var asyncExceptionFilter = Mock.Of <IAsyncExceptionFilter>();
            var resultFilter         = Mock.Of <IResultFilter>();
            var asyncResultFilter    = Mock.Of <IAsyncResultFilter>();
            var resourceFilter       = Mock.Of <IResourceFilter>();
            var asyncResourceFilter  = Mock.Of <IAsyncResourceFilter>();
            var filters = new IFilterMetadata[]
            {
                actionFilter,
                asyncActionFilter,
                authFilter,
                asyncAuthFilter,
                exceptionFilter,
                asyncExceptionFilter,
                resultFilter,
                asyncResultFilter,
                resourceFilter,
                asyncResourceFilter
            };
            var testSink      = new TestSink();
            var loggerFactory = new TestLoggerFactory(testSink, enabled: false);
            var logger        = loggerFactory.CreateLogger("test");

            // Act
            logger.AuthorizationFiltersExecutionPlan(filters);
            logger.ResourceFiltersExecutionPlan(filters);
            logger.ActionFiltersExecutionPlan(filters);
            logger.ExceptionFiltersExecutionPlan(filters);
            logger.ResultFiltersExecutionPlan(filters);

            // Assert
            Assert.Empty(testSink.Writes);
        }
Exemplo n.º 13
0
        public async Task AsyncClientStreamingCall_DeadlineLargerThanMaxTimerDueTime_DeadlineExceeded()
        {
            // 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, maxTimerPeriod: 20, loggerFactory: testLoggerFactory);
            var timeout         = TimeSpan.FromSeconds(0.2);
            var deadline        = testSystemClock.UtcNow.Add(timeout);

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

            // Assert
            var responseTask = call.ResponseAsync;

            await Task.Delay(timeout);

            // 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 write = testSink.Writes.First(w => w.EventId.Name == "DeadlineTimerRescheduled");

            Assert.AreEqual(LogLevel.Trace, write.LogLevel);
            Assert.AreEqual("Deadline timer triggered but 00:00:00.2000000 remaining before deadline exceeded. Deadline timer rescheduled.", write.Message);
        }
Exemplo n.º 14
0
        public void ValidatePath_WhenPathIsValidSCL_ReturnsSuccess()
        {
            const string path = @"c:\temp\file.scl";

            var factory = TestLoggerFactory.Create(x => x.SetMinimumLevel(LogLevel.Debug));
            var fs      = new MockFileSystem();

            fs.AddFile(path, $"- Log '{TheUltimateTestString}'");

            var sp = GetDefaultServiceProvider(factory, fs, null);

            var result = new AppRunner <EDRMethods>()
                         .UseMicrosoftDependencyInjection(sp)
                         .UseDefaultMiddleware()
                         .RunInMem($"validate {path}");

            result.ExitCode.Should().Be(0);

            factory.Sink.LogEntries.Select(x => x.Message)
            .Should()
            .BeEquivalentTo("Successfully validated SCL");
        }
Exemplo n.º 15
0
        public async void AttributeRoute_RouteAsyncNotHandled_LogsCorrectValues()
        {
            // Arrange
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink);

            var entry = CreateMatchingEntry("api/Store");
            var route = CreateRoutingAttributeRoute(loggerFactory, entry);

            var context = CreateRouteContext("/");

            // Act
            await route.RouteAsync(context);

            // Assert
            Assert.Equal(1, sink.Scopes.Count);
            var scope = sink.Scopes[0];

            Assert.Equal(typeof(AttributeRoute).FullName, scope.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", scope.Scope);

            // There is a record for IsEnabled and one for WriteCore.
            Assert.Equal(2, sink.Writes.Count);

            var enabled = sink.Writes[0];

            Assert.Equal(typeof(AttributeRoute).FullName, enabled.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", enabled.Scope);
            Assert.Null(enabled.State);

            var write = sink.Writes[1];

            Assert.Equal(typeof(AttributeRoute).FullName, write.LoggerName);
            Assert.Equal("AttributeRoute.RouteAsync", write.Scope);
            var values = Assert.IsType <AttributeRouteRouteAsyncValues>(write.State);

            Assert.Equal("AttributeRoute.RouteAsync", values.Name);
            Assert.Equal(false, values.Handled);
        }
        public void Logs_warning_when_using_invalid_config_with_custom_settings_and_formatters()
        {
            var expectedLogMessage = $"ResponseSerialization {nameof(ResponseSerializationOptions.UseOutputFormatters)} is set to true, " +
                                     $"and it's also configured to use either a custom response casing or custom json serializer settings. " +
                                     $"When using output formatters, custom settings are ignored.";

            var loggerFactory = TestLoggerFactory.Create();
            var logger        = loggerFactory.CreateLogger <ResponseSerializationOptions>();

            var options = new ResponseSerializationOptions(new ServiceCollection())
            {
                UseOutputFormatters = true
            };

            options.UseCustomJsonSerializerSettings(request => new JsonSerializerSettings());
            options.ValidateConfiguration(logger);

            var log = Assert.Single(loggerFactory.Sink.LogEntries);

            Assert.Equal(expectedLogMessage, log.Message);
            Assert.Equal(LogLevel.Warning, log.LogLevel);
        }
Exemplo n.º 17
0
        public void TestDefaultLogLevel()
        {
            using (var writer = new StringWriter())
            {
                ConnectLoggingActionToLogger(message => writer.Write(message));

                var configuration = new ConfigurationBuilder()
                                    .AddJsonFile(GetAppSettingsPath("appsettings.json"))
                                    .Build();

                var loggerOptions = new LambdaLoggerOptions(configuration);
                var loggerfactory = new TestLoggerFactory()
                                    .AddLambdaLogger(loggerOptions);

                // act
                // creating named logger, `Default` category is set to "Debug"
                // (Default category has special treatment - it's not actually stored, named logger just falls to default)
                var defaultLogger = loggerfactory.CreateLogger("Default");
                defaultLogger.LogTrace(SHOULD_NOT_APPEAR);
                defaultLogger.LogDebug(SHOULD_APPEAR);
                defaultLogger.LogInformation(SHOULD_APPEAR);

                // `Dummy` category is not specified, we should use `Default` category instead
                var dummyLogger = loggerfactory.CreateLogger("Dummy");
                dummyLogger.LogTrace(SHOULD_NOT_APPEAR);
                dummyLogger.LogDebug(SHOULD_APPEAR);
                dummyLogger.LogInformation(SHOULD_APPEAR);

                // `Microsoft` category is specified, log accordingly
                var msLogger = loggerfactory.CreateLogger("Microsoft");
                msLogger.LogTrace(SHOULD_NOT_APPEAR);
                msLogger.LogDebug(SHOULD_NOT_APPEAR);
                msLogger.LogInformation(SHOULD_APPEAR);

                // assert
                var text = writer.ToString();
                Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
            }
        }
Exemplo n.º 18
0
        public async Task SetNullAddressFeature_DoesNotThrow()
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName <HttpsRedirectionMiddleware>,
                TestSink.EnableWithTypeName <HttpsRedirectionMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var builder       = new WebHostBuilder()
                                .ConfigureServices(services =>
            {
                services.AddSingleton <ILoggerFactory>(loggerFactory);
            })
                                .Configure(app =>
            {
                app.UseHttpsRedirection();
                app.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello world"));
                });
            });

            var featureCollection = new FeatureCollection();

            featureCollection.Set <IServerAddressesFeature>(null);
            var server = new TestServer(builder, featureCollection);

            var client   = server.CreateClient();
            var request  = new HttpRequestMessage(HttpMethod.Get, "");
            var response = await client.SendAsync(request);

            Assert.Equal(200, (int)response.StatusCode);

            var logMessages = sink.Writes.ToList();

            Assert.Single(logMessages);
            var message = logMessages.First();

            Assert.Equal(LogLevel.Warning, message.LogLevel);
            Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString());
        }
Exemplo n.º 19
0
        public async Task WhenRequestIsSecure_AddsHstsHeader()
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName <HstsMiddleware>,
                TestSink.EnableWithTypeName <HstsMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                services.AddSingleton <ILoggerFactory>(loggerFactory);
            })
                          .Configure(app =>
            {
                app.UseHsts();
                app.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello world"));
                });
            });
            var server = new TestServer(builder);
            var client = server.CreateClient();

            client.BaseAddress = new Uri("https://example.com:5050");
            var request = new HttpRequestMessage(HttpMethod.Get, "");

            var response = await client.SendAsync(request);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Contains(response.Headers, x => x.Key == HeaderNames.StrictTransportSecurity);

            var logMessages = sink.Writes.ToList();

            Assert.Single(logMessages);
            var message = logMessages.Single();

            Assert.Equal(LogLevel.Trace, message.LogLevel);
            Assert.Equal("Adding HSTS header to response.", message.State.ToString());
        }
        public void ControllerDiscovery()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink);

            // Act
            var provider = GetProvider(
                loggerFactory, 
                typeof(SimpleController).GetTypeInfo(),
                typeof(BasicController).GetTypeInfo());
            provider.GetDescriptors();

            // Assert
            // 2 controllers
            Assert.Equal(2, sink.Writes.Count);

            var controllerModelValues = Assert.IsType<ControllerModelValues>(sink.Writes[0].State);
            Assert.NotNull(controllerModelValues);
            Assert.Equal("Simple", controllerModelValues.ControllerName);
            Assert.Equal(typeof(SimpleController), controllerModelValues.ControllerType);
            Assert.Single(controllerModelValues.Actions);
            Assert.Empty(controllerModelValues.AttributeRoutes);
            Assert.Empty(controllerModelValues.RouteConstraints);
            Assert.Empty(controllerModelValues.Attributes);
            Assert.Empty(controllerModelValues.Filters);

            controllerModelValues = Assert.IsType<ControllerModelValues>(sink.Writes[1].State);
            Assert.NotNull(controllerModelValues);
            Assert.Equal("Basic", controllerModelValues.ControllerName);
            Assert.Equal(typeof(BasicController), controllerModelValues.ControllerType);
            Assert.Equal(2, controllerModelValues.Actions.Count);
            Assert.Equal("GET", controllerModelValues.Actions[0].HttpMethods.FirstOrDefault());
            Assert.Equal("POST", controllerModelValues.Actions[1].HttpMethods.FirstOrDefault());
            Assert.Empty(controllerModelValues.AttributeRoutes);
            Assert.Empty(controllerModelValues.RouteConstraints);
            Assert.NotEmpty(controllerModelValues.Attributes);
            Assert.Single(controllerModelValues.Filters);
        }
Exemplo n.º 21
0
        public void EvaluatePolicy_LoggingForPreflightRequests_HasOriginHeader_PolicyFailed(LogData logData)
        {
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var corsService    = new CorsService(new TestCorsOptions(), loggerFactory);
            var requestContext = GetHttpContext(method: "OPTIONS", origin: logData.Origin, accessControlRequestMethod: logData.Method, accessControlRequestHeaders: logData.Headers);
            var policy         = new CorsPolicy();

            policy.Origins.Add("http://allowed.example.com");
            policy.Methods.Add("PUT");

            // Act
            var result = corsService.EvaluatePolicy(requestContext, policy);

            var writeList = sink.Writes.ToList();

            Assert.Equal("The request is a preflight request.", writeList[0].State.ToString());
            Assert.Equal(logData.OriginLogMessage, writeList[1].State.ToString());
            Assert.Equal(logData.PolicyLogMessage, writeList[2].State.ToString());
            Assert.Equal(logData.FailureReason, writeList[3].State.ToString());
        }
Exemplo n.º 22
0
        public void CopyRequestHeader(bool copyRequestHeaders)
        {
            var loggerFactory    = new TestLoggerFactory();
            var transformBuilder = CreateTransformBuilder(loggerFactory);
            var transforms       = new List <IDictionary <string, string> >()
            {
                new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { "RequestHeadersCopy", copyRequestHeaders.ToString() }
                }
            };

            var valid = transformBuilder.Validate(transforms, "routeId");

            Assert.True(valid);
            Assert.Empty(loggerFactory.Logger.Errors);

            var results = transformBuilder.Build(transforms);

            Assert.NotNull(results);
            Assert.Equal(copyRequestHeaders, results.CopyRequestHeaders);
        }
        public async Task CheckHealthAsync_SetsUpALoggerScopeForEachCheck()
        {
            // Arrange
            var sink  = new TestSink();
            var check = new DelegateHealthCheck(cancellationToken =>
            {
                Assert.Collection(sink.Scopes,
                                  actual =>
                {
                    Assert.Equal(actual.LoggerName, typeof(DefaultHealthCheckService).FullName);
                    Assert.Collection((IEnumerable <KeyValuePair <string, object> >)actual.Scope,
                                      item =>
                    {
                        Assert.Equal("HealthCheckName", item.Key);
                        Assert.Equal("TestScope", item.Value);
                    });
                });
                return(Task.FromResult(HealthCheckResult.Healthy()));
            });

            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var service       = CreateHealthChecksService(b =>
            {
                // Override the logger factory for testing
                b.Services.AddSingleton <ILoggerFactory>(loggerFactory);

                b.AddCheck("TestScope", check);
            });

            // Act
            var results = await service.CheckHealthAsync();

            // Assert
            Assert.Collection(results.Entries, actual =>
            {
                Assert.Equal("TestScope", actual.Key);
                Assert.Equal(HealthStatus.Healthy, actual.Value.Status);
            });
        }
Exemplo n.º 24
0
        public async Task RouteAsync_Success_LogsCorrectValues()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var displayName = "A.B.C";
            var actionDescriptor = new Mock<ActionDescriptor>();
            actionDescriptor.SetupGet(ad => ad.DisplayName)
                            .Returns(displayName);
            var context = CreateRouteContext(actionDescriptor: actionDescriptor.Object, loggerFactory: loggerFactory);
            var handler = new MvcRouteHandler();
            var expectedMessage = $"Executing action {displayName}";

            // Act
            await handler.RouteAsync(context);

            // Assert
            Assert.Single(sink.Scopes);
            Assert.StartsWith("ActionId: ", sink.Scopes[0].Scope?.ToString());
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Exemplo n.º 25
0
        public async Task BindModelAsync_LogsNoFormatterSelectedAndRemoveFromBodyAttribute()
        {
            // Arrange
            var sink            = new TestSink();
            var loggerFactory   = new TestLoggerFactory(sink, enabled: true);
            var inputFormatters = new List <IInputFormatter>()
            {
                new TestInputFormatter(canRead: false),
                new TestInputFormatter(canRead: false),
            };

            var provider = new TestModelMetadataProvider();

            provider.ForType <Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);
            var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);

            bindingContext.HttpContext.Request.ContentType = "multipart/form-data";
            bindingContext.BinderModelName = bindingContext.ModelName;
            var binder = new BodyModelBinder(inputFormatters, new TestHttpRequestStreamReaderFactory(), loggerFactory);

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.Collection(
                sink.Writes,
                write => Assert.Equal(
                    $"Attempting to bind model of type '{typeof(Person)}' using the name 'someName' in request data ...", write.State.ToString()),
                write => Assert.Equal(
                    $"Rejected input formatter '{typeof(TestInputFormatter)}' for content type 'multipart/form-data'.", write.State.ToString()),
                write => Assert.Equal(
                    $"Rejected input formatter '{typeof(TestInputFormatter)}' for content type 'multipart/form-data'.", write.State.ToString()),
                write => Assert.Equal(
                    "No input formatter was found to support the content type 'multipart/form-data' for use with the [FromBody] attribute.", write.State.ToString()),
                write => Assert.Equal(
                    $"To use model binding, remove the [FromBody] attribute from the property or parameter named '{bindingContext.ModelName}' with model type '{bindingContext.ModelType}'.", write.State.ToString()),
                write => Assert.Equal(
                    $"Done attempting to bind model of type '{typeof(Person)}' using the name 'someName'.", write.State.ToString()));
        }
Exemplo n.º 26
0
        public async Task BindModelAsync_EnforcesTopLevelRequiredAndLogsSuccessfully_WithEmptyPrefix(
            RequiredAttribute attribute,
            ParameterDescriptor parameterDescriptor,
            ModelMetadata metadata)
        {
            // Arrange
            var expectedKey       = string.Empty;
            var expectedFieldName = metadata.Name ?? nameof(Person);

            var actionContext = GetControllerContext();
            var validator     = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer: null);

            var sink               = new TestSink();
            var loggerFactory      = new TestLoggerFactory(sink, enabled: true);
            var parameterBinder    = CreateParameterBinder(metadata, validator, loggerFactory: loggerFactory);
            var modelBindingResult = ModelBindingResult.Success(null);

            // Act
            var result = await parameterBinder.BindModelAsync(
                actionContext,
                CreateMockModelBinder(modelBindingResult),
                CreateMockValueProvider(),
                parameterDescriptor,
                metadata,
                "ignoredvalue");

            // Assert
            Assert.False(actionContext.ModelState.IsValid);
            var modelState = Assert.Single(actionContext.ModelState);

            Assert.Equal(expectedKey, modelState.Key);
            var error = Assert.Single(modelState.Value.Errors);

            Assert.Equal(attribute.FormatErrorMessage(expectedFieldName), error.ErrorMessage);
            Assert.Equal(4, sink.Writes.Count());
        }
Exemplo n.º 27
0
        public void DoExceptionalLogsException()
        {
            // Arrange
            var loggerFactory = TestLoggerFactory.Create();
            var logger        = loggerFactory.CreateLogger <Sample>();
            var sample        = new Sample(logger);

            // Act
            sample.DoExceptional();

            // Assert
            var log = Assert.Single(loggerFactory.Sink.LogEntries);

            // Assert the message rendered by a default formatter
            Assert.Equal("There was a problem", log.Message);
            // Assert specific parameters in the log entry
            LoggingAssert.Contains("error", "problem", log.Properties);
            // Assert the exception
            var exception = Assert.IsType <ArgumentNullException>(log.Exception);

            Assert.Equal("foo", exception.ParamName);
        }
Exemplo n.º 28
0
        public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string host)
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName <HstsMiddleware>,
                TestSink.EnableWithTypeName <HstsMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                services.AddSingleton <ILoggerFactory>(loggerFactory);
            })
                          .Configure(app =>
            {
                app.UseHsts();
                app.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello world"));
                });
            });
            var server = new TestServer(builder);
            var client = server.CreateClient();

            client.BaseAddress = new Uri($"https://{host}:5050");
            var request = new HttpRequestMessage(HttpMethod.Get, "");

            var response = await client.SendAsync(request);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Empty(response.Headers);

            var logMessages = sink.Writes.ToList();

            Assert.Single(logMessages);
            var message = logMessages.Single();

            Assert.Equal(LogLevel.Debug, message.LogLevel);
            Assert.Equal($"The host '{host}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true);
        }
Exemplo n.º 29
0
        public void LogsFeatureIsReadOnly()
        {
            // Arrange
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var disableRequestSizeLimitResourceFilter = new DisableRequestSizeLimitFilter(loggerFactory);
            var authorizationFilterContext            = CreateAuthorizationFilterContext(new IFilterMetadata[] { disableRequestSizeLimitResourceFilter });

            var httpMaxRequestBodySize = new TestHttpMaxRequestBodySizeFeature();

            httpMaxRequestBodySize.IsReadOnly = true;
            authorizationFilterContext.HttpContext.Features.Set <IHttpMaxRequestBodySizeFeature>(httpMaxRequestBodySize);

            // Act
            disableRequestSizeLimitResourceFilter.OnAuthorization(authorizationFilterContext);

            // Assert
            var write = Assert.Single(sink.Writes);

            Assert.Equal($"A request body size limit could not be applied. The IHttpRequestBodySizeFeature for the server is read-only.", write.State.ToString());
        }
Exemplo n.º 30
0
    public void ParsePathByAddresss_HasMatches_ReturnsFirstSuccessfulParse()
    {
        // Arrange
        var endpoint0 = EndpointFactory.CreateRouteEndpoint("{controller}/{action}", displayName: "Test1", metadata: new object[] { new IntMetadata(0), });
        var endpoint1 = EndpointFactory.CreateRouteEndpoint("{controller}/{action}/{id}", displayName: "Test2", metadata: new object[] { new IntMetadata(0), });
        var endpoint2 = EndpointFactory.CreateRouteEndpoint("{controller}/{action}/{id2}", displayName: "Test3", metadata: new object[] { new IntMetadata(0), });

        var sink          = new TestSink();
        var loggerFactory = new TestLoggerFactory(sink, enabled: true);
        var parser        = CreateLinkParser(services => { services.AddSingleton <ILoggerFactory>(loggerFactory); }, endpoint0, endpoint1, endpoint2);

        // Act
        var values = parser.ParsePathByAddress(0, "/Home/Index/17");

        // Assert
        MatcherAssert.AssertRouteValuesEqual(new { controller = "Home", action = "Index", id = "17" }, values);

        Assert.Collection(
            sink.Writes,
            w => Assert.Equal("Found the endpoints Test1, Test2, Test3 for address 0", w.Message),
            w => Assert.Equal("Path parsing succeeded for endpoint Test2 and URI path /Home/Index/17", w.Message));
    }
Exemplo n.º 31
0
        public async Task MoveNext_TokenCancelledDuringMoveNext_CancelTask()
        {
            // Arrange
            var ms = new SyncPointMemoryStream();

            var testSink          = new TestSink();
            var testLoggerFactory = new TestLoggerFactory(testSink, enabled: true);

            var httpContext = new DefaultHttpContext();

            httpContext.Features.Set <IRequestBodyPipeFeature>(new TestRequestBodyPipeFeature(PipeReader.Create(ms)));
            var serverCallContext = HttpContextServerCallContextHelper.CreateServerCallContext(httpContext, logger: testLoggerFactory.CreateLogger("Test"));
            var reader            = new HttpContextStreamReader <HelloReply>(serverCallContext, MessageHelpers.ServiceMethod.ResponseMarshaller.ContextualDeserializer);

            var cts = new CancellationTokenSource();

            var nextTask = reader.MoveNext(cts.Token);

            Assert.IsFalse(nextTask.IsCompleted);
            Assert.IsFalse(nextTask.IsCanceled);

            cts.Cancel();

            try
            {
                await nextTask;
                Assert.Fail();
            }
            catch (TaskCanceledException)
            {
            }

            Assert.IsTrue(nextTask.IsCompleted);
            Assert.IsTrue(nextTask.IsCanceled);

            Assert.AreEqual(1, testSink.Writes.Count);
            Assert.AreEqual("ReadingMessage", testSink.Writes.First().EventId.Name);
        }
Exemplo n.º 32
0
        public void LogsMaxRequestBodySizeSet()
        {
            // Arrange
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var requestSizeLimitResourceFilter = new RequestSizeLimitFilter(loggerFactory);

            requestSizeLimitResourceFilter.Bytes = 12345;
            var authorizationFilterContext = CreateAuthorizationFilterContext(new IFilterMetadata[] { requestSizeLimitResourceFilter });

            var httpMaxRequestBodySize = new TestHttpMaxRequestBodySizeFeature();

            authorizationFilterContext.HttpContext.Features.Set <IHttpMaxRequestBodySizeFeature>(httpMaxRequestBodySize);

            // Act
            requestSizeLimitResourceFilter.OnAuthorization(authorizationFilterContext);

            // Assert
            var write = Assert.Single(sink.Writes);

            Assert.Equal($"The maximum request body size has been set to 12345.", write.State.ToString());
        }
Exemplo n.º 33
0
        public void LogError_WhenErrorHasException_LogsMessage()
        {
            var loggerFactory = TestLoggerFactory.Create();
            var logger        = loggerFactory.CreateLogger("Test");

            var error = new SingleError(
                ErrorLocation.EmptyLocation,
                new Exception("Test"),
                ErrorCode.WrongVariableType
                );

            logger.LogError(error);

            var logMessages = loggerFactory.Sink.LogEntries.ToList();

            Assert.NotNull(logMessages[0].Exception);

            Assert.Contains(
                logMessages,
                l => l.LogLevel == LogLevel.Error &&
                l.Message !.Equals("Test (Step: n/a)")
                );
        }
Exemplo n.º 34
0
        public void RequestHeader(bool append, string value)
        {
            var loggerFactory    = new TestLoggerFactory();
            var transformBuilder = CreateTransformBuilder(loggerFactory);
            var transforms       = new List <IDictionary <string, string> >()
            {
                new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { "RequestHeader", "HeaderName" },
                    { append ? "Append" : "Set", value }
                }
            };

            var valid = transformBuilder.Validate(transforms, "routeId");

            Assert.True(valid);
            Assert.Empty(loggerFactory.Logger.Errors);

            var results = transformBuilder.Build(transforms);

            Assert.IsType <RequestHeaderValueTransform>(results.RequestHeaderTransforms["heaDerName"]);
            // TODO: How to check Append/Set and the value?
        }
Exemplo n.º 35
0
        public async Task GetOrCreateNuixConnection_OnStartExternalProcessFailure_ReturnsError()
        {
            var fakeExternalProcess =
                new ExternalProcessMock(1, ConnectionTestsHelper.GetCreateCaseAction())
            {
                ProcessPath = "WrongPath", ValidateArguments = false
            };

            var loggerFactory = TestLoggerFactory.Create();

            IStateMonad state =
                ConnectionTestsHelper.GetStateMonad(
                    fakeExternalProcess,
                    loggerFactory
                    );

            var createConnection = await state.GetOrCreateNuixConnection(null, true);

            createConnection.ShouldBeFailure();

            createConnection.Error.AsString.Should()
            .Be($"External Process Failed: 'Could not start '{Constants.NuixConsoleExe}''");
        }
Exemplo n.º 36
0
        public async Task SendDoneCommand_WritesDoneToExternalProcess()
        {
            var logFactory     = TestLoggerFactory.Create();
            var action         = ConnectionTestsHelper.GetDoneAction();
            var nuixConnection = ConnectionTestsHelper.GetNuixConnection(logFactory, action);

            var fakeExternalProcess = new ExternalProcessMock(
                1,
                ConnectionTestsHelper.GetCreateCaseAction()
                );

            var state = ConnectionTestsHelper.GetStateMonad(
                fakeExternalProcess,
                logFactory
                );

            var ct = new CancellationToken();

            await nuixConnection.SendDoneCommand(state, null, ct);

            logFactory.Sink.LogEntries.Should()
            .Contain(x => x.Message != null && x.Message.Equals("Finished"));
        }
Exemplo n.º 37
0
        public async Task RouteAsync_Success_LogsCorrectValues()
        {
            // Arrange
            var sink             = new TestSink();
            var loggerFactory    = new TestLoggerFactory(sink, enabled: true);
            var displayName      = "A.B.C";
            var actionDescriptor = new Mock <ActionDescriptor>();

            actionDescriptor.SetupGet(ad => ad.DisplayName)
            .Returns(displayName);
            var context         = CreateRouteContext(actionDescriptor: actionDescriptor.Object, loggerFactory: loggerFactory);
            var handler         = new MvcRouteHandler();
            var expectedMessage = $"Executing action {displayName}";

            // Act
            await handler.RouteAsync(context);

            // Assert
            Assert.Single(sink.Scopes);
            Assert.StartsWith("ActionId: ", sink.Scopes[0].Scope?.ToString());
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Exemplo n.º 38
0
    public async Task AuthenticationManager_DoesNotThrowExceptionOnDisplaysUI_WhenPathsAreMissing(UIValidator validator)
    {
        // Arrange
        var renderer = new TestRenderer(new ServiceCollection().BuildServiceProvider());
        var testNavigationManager = new TestNavigationManager("https://www.example.com/", "Some error message.", "https://www.example.com/");
        var logger        = new TestLoggerFactory(new TestSink(), false).CreateLogger <RemoteAuthenticatorViewCore <RemoteAuthenticationState> >();
        var authenticator = new TestRemoteAuthenticatorView(new RemoteAuthenticationApplicationPathsOptions(), testNavigationManager);

        authenticator.Logger = logger;
        renderer.Attach(authenticator);
        validator.SetupFakeRender(authenticator);

        var parameters = ParameterView.FromDictionary(new Dictionary <string, object>
        {
            [_action] = validator.Action
        });

        // Act
        Task result = await renderer.Dispatcher.InvokeAsync <Task>(() => authenticator.SetParametersAsync(parameters));

        // Assert
        Assert.Null(result.Exception);
    }
Exemplo n.º 39
0
        public async Task ExpiredSession_LogsWarning()
        {
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            using (var server = TestServer.Create(app =>
            {
                app.UseServices(services =>
                {
                    services.AddOptions();
                    services.AddInstance(typeof(ILoggerFactory), loggerFactory);
                });
                app.UseInMemorySession(configure: o => {
                    o.IdleTimeout = TimeSpan.FromMilliseconds(30);
                });
                app.Run(context =>
                {
                    int? value = context.Session.GetInt("Key");
                    if (context.Request.Path == new PathString("/first"))
                    {
                        Assert.False(value.HasValue);
                        value = 1;
                        context.Session.SetInt("Key", 1);
                    }
                    else if (context.Request.Path == new PathString("/second"))
                    {
                        Assert.False(value.HasValue);
                        value = 2;
                    }
                    return context.Response.WriteAsync(value.Value.ToString());
                });
            }))
            {
                var client = server.CreateClient();
                var response = await client.GetAsync("/first");
                response.EnsureSuccessStatusCode();

                client = server.CreateClient();
                client.DefaultRequestHeaders.Add("Cookie", response.Headers.GetValues("Set-Cookie"));
                Thread.Sleep(50);
                Assert.Equal("2", await client.GetStringAsync("/second"));
                Assert.Equal(2, sink.Writes.Count);
                Assert.True(sink.Writes[0].State.ToString().Contains("started"));
                Assert.True(sink.Writes[1].State.ToString().Contains("expired"));
                Assert.Equal(LogLevel.Information, sink.Writes[0].LogLevel);
                Assert.Equal(LogLevel.Warning, sink.Writes[1].LogLevel);
            }
        }
        public void Query_logs_DataStoreErrorLogState(Action<BloggingContext> test)
        {
            var loggerFactory = new TestLoggerFactory();
            var serviceProvider = new ServiceCollection()
                .AddEntityFramework()
                .AddInMemoryStore()
                .ServiceCollection()
                .AddInstance<ILoggerFactory>(loggerFactory)
                .BuildServiceProvider();

            using (var context = new BloggingContext(serviceProvider))
            {
                context.Blogs.Add(new BloggingContext.Blog(false) { Url = "http://sample.com" });
                context.SaveChanges();
                var entry = ((IAccessor<InternalEntityEntry>)context.ChangeTracker.Entries().Single()).Service;
                ((IAccessor<IStateManager>)context.ChangeTracker).Service.StopTracking(entry);

                var ex = Assert.ThrowsAny<Exception>(() => test(context));
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                Assert.Equal("Jim said to throw from ctor!", ex.Message);
                Assert.Same(ex, loggerFactory.Logger.LastDataStoreErrorException);
                Assert.Same(typeof(BloggingContext), loggerFactory.Logger.LastDataStoreErrorState.ContextType);
                Assert.EndsWith(ex.ToString(), loggerFactory.Logger.LastDataStoreErrorFormatter(loggerFactory.Logger.LastDataStoreErrorState, ex));
            }
        }
Exemplo n.º 41
0
 public async Task SessionStart_LogsInformation()
 {
     var sink = new TestSink();
     var loggerFactory = new TestLoggerFactory(sink, enabled: true);
     using (var server = TestServer.Create(app =>
     {
         app.UseServices(services => 
         {
             services.AddOptions();
             services.AddInstance(typeof(ILoggerFactory), loggerFactory);
         });
         app.UseInMemorySession();
         app.Run(context =>
         {
             context.Session.SetString("Key", "Value");
             return Task.FromResult(0);
         });
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync("/");
         response.EnsureSuccessStatusCode();
         Assert.Single(sink.Writes);
         Assert.True(sink.Writes[0].State.ToString().Contains("started"));
         Assert.Equal(LogLevel.Information, sink.Writes[0].LogLevel);
     }
 }