public void CanDisposeMultipleTimes()
        {
            var output = Substitute.For <ITestOutputHelper>();

            using var sut = new TestOutputLoggerProvider(output);
            sut.Dispose();
            sut.Dispose();
        }
        public void CreateLoggerWithoutLoggingConfigReturnsOutputLogger()
        {
            var categoryName = Guid.NewGuid().ToString();

            var output = Substitute.For <ITestOutputHelper>();

            using var sut = new TestOutputLoggerProvider(output);
            var actual = sut.CreateLogger(categoryName);

            actual.Should().BeOfType <TestOutputLogger>();
        }
        public void CreateLoggerThrowsExceptionWithInvalidCategoryNameTest(string categoryName)
        {
            var output = Substitute.For <ITestOutputHelper>();

            using var sut = new TestOutputLoggerProvider(output);

            // ReSharper disable once AccessToDisposedClosure
            Action action = () => sut.CreateLogger(categoryName);

            action.Should().Throw <ArgumentException>();
        }
コード例 #4
0
        /// <summary>
        ///     Adds a logger to writes to the xUnit test output to the specified logging builder.
        /// </summary>
        /// <param name="builder">The logging builder.</param>
        /// <param name="output">The xUnit test output helper.</param>
        /// <param name="config">Optional logging configuration.</param>
        public static void AddXunit(this ILoggingBuilder builder, ITestOutputHelper output,
                                    LoggingConfig?config = null)
        {
            builder = builder ?? throw new ArgumentNullException(nameof(builder));
            output  = output ?? throw new ArgumentNullException(nameof(output));

            // Object is added as a provider to the builder and cannot be disposed of here
#pragma warning disable CA2000 // Dispose objects before losing scope
            var provider = new TestOutputLoggerProvider(output, config);
#pragma warning restore CA2000 // Dispose objects before losing scope

            builder.AddProvider(provider);
        }
コード例 #5
0
        /// <summary>
        ///     Registers the <see cref="TestOutputLoggerProvider" /> in the factory using the specified
        ///     <see cref="ITestOutputHelper" />.
        /// </summary>
        /// <param name="factory">The factory to add the provider to.</param>
        /// <param name="output">The test output reference.</param>
        /// <param name="config">Optional logging configuration.</param>
        /// <returns>The logger factory.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="factory" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="output" /> is <c>null</c>.</exception>
        public static ILoggerFactory AddXunit(this ILoggerFactory factory, ITestOutputHelper output,
                                              LoggingConfig?config = null)
        {
            factory = factory ?? throw new ArgumentNullException(nameof(factory));
            output  = output ?? throw new ArgumentNullException(nameof(output));

#pragma warning disable CA2000 // Dispose objects before losing scope
            var provider = new TestOutputLoggerProvider(output, config);
#pragma warning restore CA2000 // Dispose objects before losing scope

#pragma warning disable CA1062 // Validate arguments of public methods
            factory.AddProvider(provider);
#pragma warning restore CA1062 // Validate arguments of public methods

            return(factory);
        }
コード例 #6
0
    public TDb CreateDbContext(string model, string nameOfConnectionString, ITestOutputHelper?output = null)
    {
        if (serviceProvider is null)
        {
            ConfigureServices(services);

            string connectionString = DbConfigurationBuilder <TDb> .GetConnectionString(nameOfConnectionString);

            services.AddDbContext <TDb>((serviceProvider, options) =>
            {
                options.UseInternalServiceProvider(serviceProvider);
                if (model == "SQL")
                {
                    options.UseSqlServer(connectionString);
                }
                if (model == "MEM")
                {
                    options.UseInMemoryDatabase(connectionString, new InMemoryDatabaseRoot());
                }
                if (model == "MEME")
                {
                    options.UseInMemoryDatabase(connectionString);
                }
                if (model == "LIT")
                {
                    options.UseSqlite(connectionString);
                }
                options.EnableSensitiveDataLogging();

                if (output != null)
                {
                    var provider      = new TestOutputLoggerProvider(output);
                    var loggerFactory = new LoggerFactory(new[]
                    {
                        provider
                    });

                    options.UseLoggerFactory(loggerFactory);
                }
            });
            serviceProvider = services.BuildServiceProvider();
        }

        TDb?dbContext = serviceProvider.GetRequiredService <TDb>();

        return(dbContext);
    }
コード例 #7
0
        /// <inheritdoc />
        public WebServerFixture()
        {
            LoggerProvider = new TestOutputLoggerProvider();

            var identityServer = new TestServer(
                new WebHostBuilder()
                //.ConfigureLogging(_ => _.AddProvider(new TestOutputLoggerProvider()))
                .Configure(app =>
            {
                app.UseIdentityServer();
            })
                .ConfigureServices(
                    (context, services) =>
            {
                services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(
                    new IdentityResource[]
                    { new IdentityResources.OpenId(), new IdentityResources.Profile(), })
                .AddInMemoryApiResources(
                    new[]
                {
                    new ApiResource("api", "The API")
                    {
                        ApiSecrets = { new Secret("secret".Sha256()) },
                        /*Scopes = { new Scope("api")}*/
                    }
                })
                .AddInMemoryClients(
                    new[]
                {
                    new Client
                    {
                        ClientId          = "client",
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                        ClientSecrets     =
                        {
                            new Secret("secret".Sha256())
                        },
                        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "api"
                        },
                        AllowOfflineAccess = true
                    }
                })
                .AddTestUsers(new List <TestUser>());
            })
                );

            Server = new TestServer(
                new WebHostBuilder()
                .UseStartup <InMemoryDatabaseStartup>()
                .ConfigureLogging(_ => _.AddProvider(LoggerProvider).SetMinimumLevel(LogLevel.Trace))
                .ConfigureAppConfiguration(
                    b => b.AddInMemoryCollection(
                        new Dictionary <string, string> {
                ["IdentityServer:EnableInternalServer"] = false.ToString()
            }))
                .ConfigureServices(
                    services =>
            {
                services.AddAuthentication().AddIdentityServerAuthentication(
                    options =>
                {
                    options.ApiSecret = "secret";
                    options.ApiName   = "api";
                    options.IntrospectionDiscoveryHandler   = identityServer.CreateHandler();
                    options.IntrospectionBackChannelHandler = identityServer.CreateHandler();
                    options.JwtBackChannelHandler           = identityServer.CreateHandler();
                    options.RequireHttpsMetadata            = false;
                    options.Authority = identityServer.BaseAddress.ToString();

                    options.Validate();
                });
            })
                );

            var db = Server.Host.Services.GetRequiredService <ConsentContext>();

            db.Database.EnsureCreated();

            Client = Server.CreateClient();
            Client.GetAsync("/");

            var identityServerHttpClient = new HttpClient(identityServer.CreateHandler());

            var discoveryResponse = identityServerHttpClient
                                    .GetDiscoveryDocumentAsync(identityServer.BaseAddress.ToString()).RunSync();

            if (discoveryResponse.IsError)
            {
                throw new Exception(discoveryResponse.Error);
            }

            var response =
                identityServerHttpClient
                .RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Scope        = "api",
                Address      = discoveryResponse.TokenEndpoint,
                ClientId     = "client",
                ClientSecret = "secret",
            })
                .RunSync();

            if (response.IsError)
            {
                throw new Exception(response.ErrorDescription);
            }

            Client.SetBearerToken(response.AccessToken);

            ApiClient = new Consent.Api.Client.Api(
                Client,
                new TokenCredentials(response.AccessToken),
                disposeHttpClient: false);



            ServiceClientTracing.IsEnabled = true;
            tracingInterceptor             = new XUnitServiceClientTracingInterceptor(null);
            ServiceClientTracing.AddTracingInterceptor(tracingInterceptor);
        }