1- // using System.Net.Http.Json;
2- // using Microsoft.AspNetCore.Mvc.Testing;
3- // using Microsoft.AspNetCore.TestHost;
4- // using Microsoft.EntityFrameworkCore;
5- // using Microsoft.Extensions.DependencyInjection;
6- // using Microsoft.Extensions.DependencyInjection.Extensions;
7- // using Riber.Application.Common;
8- // using Riber.Application.Features.Auths.Commands.Login;
9- // using Riber.Infrastructure.Persistence;
10- // using Riber.Infrastructure.Persistence.Interceptors;
11- // using Testcontainers.PostgreSql;
12- // using Xunit;
13- //
14- // namespace Riber.Api.Tests;
15- //
16- // public abstract class IntegrationTestBase : IAsyncLifetime
17- // {
18- // #region Fields
19- //
20- // private readonly PostgreSqlContainer _dbContainer = new PostgreSqlBuilder()
21- // .WithImage("postgres:14.1-alpine")
22- // .WithDatabase("riber_test")
23- // .WithUsername("postgres")
24- // .WithPassword("root")
25- // .Build();
26- //
27- // protected WebApplicationFactory<Program> Factory { get; private set; } = null!;
28- // protected HttpClient Client { get; private set; } = null!;
29- //
30- // #endregion
31- //
32- // #region Methods
33- //
34- // public async Task InitializeAsync()
35- // {
36- // await _dbContainer.StartAsync();
37- // Factory = new WebApplicationFactory<Program>()
38- // .WithWebHostBuilder(builder =>
39- // {
40- // builder.ConfigureTestServices(services =>
41- // {
42- // // Irá remover as injeções inseridas no contexto de banco de dados
43- // services.RemoveAll<DbContextOptions<AppDbContext>>();
44- //
45- // // Inserindo as injeções de banco de dados para testes
46- // services.AddDbContext<AppDbContext>(options =>
47- // options
48- // .UseNpgsql(_dbContainer.GetConnectionString())
49- // .AddInterceptors(new CaseInsensitiveInterceptor(), new AuditInterceptor())
50- // );
51- // });
52- // });
53- //
54- // Client = Factory.CreateClient();
55- // using var scope = Factory.Services.CreateScope();
56- // var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
57- // await context.Database.MigrateAsync();
58- // }
59- //
60- // public async Task DisposeAsync()
61- // {
62- // await _dbContainer.DisposeAsync();
63- // await Factory.DisposeAsync();
64- // Client.Dispose();
65- // }
66- //
67- // protected AppDbContext GetDbContext()
68- // {
69- // var scope = Factory.Services.CreateScope();
70- // return scope.ServiceProvider.GetRequiredService<AppDbContext>();
71- // }
72- //
73- // protected async Task ResetDatabaseAsync()
74- // {
75- // using var scope = Factory.Services.CreateScope();
76- // var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
77- //
78- // /*
79- // * Isso fará que seja desabilitado no postgres temporiamente as restrições de integridade
80- // * como: foreign key, unique key, check, etc.
81- // */
82- // await context.Database.ExecuteSqlRawAsync("SET session_replication_role = 'replica';");
83- // var tables = await context.Database
84- // .SqlQueryRaw<string>("""
85- // SELECT tablename
86- // FROM pg_tables
87- // WHERE schemaname='public'
88- // AND tablename != '__EFMigrationsHistory';
89- // """)
90- // .ToListAsync();
91- //
92- // #pragma warning disable EF1002
93- // foreach (var table in tables)
94- // await context.Database.ExecuteSqlRawAsync($"TRUNCATE TABLE \"{table}\" RESTART IDENTITY CASCADE;");
95- // #pragma warning restore EF1002
96- //
97- // await context.Database.ExecuteSqlRawAsync("SET session_replication_role = 'origin';");
98- // }
99- //
100- // protected async Task AuthenticateAsync()
101- // => Client.DefaultRequestHeaders.Authorization =
102- // new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", await GetTokenAsync());
103- //
104- // protected void ClearAuthentication()
105- // => Client.DefaultRequestHeaders.Authorization = null;
106- //
107- // private async Task<string> GetTokenAsync()
108- // {
109- // var loginResponse = await Client.PostAsJsonAsync("api/v1/auth/login",
110- // new { Username = "admin123", Password = "Admin@123" });
111- //
112- // loginResponse.EnsureSuccessStatusCode();
113- // var result = await loginResponse.Content.ReadFromJsonAsync<Result<LoginCommandResponse>>();
114- // return result?.Value.Token ?? string.Empty;
115- // }
116- //
117- // #endregion
118- // }
1+ using System . Net . Http . Json ;
2+ using Microsoft . AspNetCore . Mvc . Testing ;
3+ using Microsoft . AspNetCore . TestHost ;
4+ using Microsoft . EntityFrameworkCore ;
5+ using Microsoft . Extensions . DependencyInjection ;
6+ using Microsoft . Extensions . DependencyInjection . Extensions ;
7+ using Riber . Application . Common ;
8+ using Riber . Application . Features . Auths . Commands . Login ;
9+ using Riber . Infrastructure . Persistence ;
10+ using Riber . Infrastructure . Persistence . Interceptors ;
11+ using Testcontainers . PostgreSql ;
12+ using Xunit ;
13+
14+ namespace Riber . Api . Tests ;
15+
16+ public abstract class IntegrationTestBase : IAsyncLifetime
17+ {
18+ #region Fields
19+
20+ private readonly PostgreSqlContainer _dbContainer = new PostgreSqlBuilder ( )
21+ . WithImage ( "postgres:14.1-alpine" )
22+ . WithDatabase ( "riber_test" )
23+ . WithUsername ( "postgres" )
24+ . WithPassword ( "root" )
25+ . Build ( ) ;
26+
27+ protected WebApplicationFactory < Program > Factory { get ; private set ; } = null ! ;
28+ protected HttpClient Client { get ; private set ; } = null ! ;
29+
30+ #endregion
31+
32+ #region Methods
33+
34+ public async Task InitializeAsync ( )
35+ {
36+ await _dbContainer . StartAsync ( ) ;
37+ Factory = new WebApplicationFactory < Program > ( )
38+ . WithWebHostBuilder ( builder =>
39+ {
40+ builder . ConfigureTestServices ( services =>
41+ {
42+ // Irá remover as injeções inseridas no contexto de banco de dados
43+ services . RemoveAll < DbContextOptions < AppDbContext > > ( ) ;
44+ services . RemoveAll < Microsoft . Extensions . Diagnostics . HealthChecks . HealthCheckService > ( ) ;
45+
46+ // Inserindo as injeções de banco de dados para testes
47+ services . AddDbContext < AppDbContext > ( options =>
48+ options
49+ . UseNpgsql ( _dbContainer . GetConnectionString ( ) )
50+ . AddInterceptors ( new CaseInsensitiveInterceptor ( ) , new AuditInterceptor ( ) )
51+ ) ;
52+ } ) ;
53+ } ) ;
54+
55+ Client = Factory . CreateClient ( ) ;
56+ using var scope = Factory . Services . CreateScope ( ) ;
57+ var context = scope . ServiceProvider . GetRequiredService < AppDbContext > ( ) ;
58+ await context . Database . MigrateAsync ( ) ;
59+ }
60+
61+ public async Task DisposeAsync ( )
62+ {
63+ await _dbContainer . DisposeAsync ( ) ;
64+ await Factory . DisposeAsync ( ) ;
65+ Client . Dispose ( ) ;
66+ }
67+
68+ protected AppDbContext GetDbContext ( )
69+ {
70+ var scope = Factory . Services . CreateScope ( ) ;
71+ return scope . ServiceProvider . GetRequiredService < AppDbContext > ( ) ;
72+ }
73+
74+ protected async Task ResetDatabaseAsync ( )
75+ {
76+ using var scope = Factory . Services . CreateScope ( ) ;
77+ var context = scope . ServiceProvider . GetRequiredService < AppDbContext > ( ) ;
78+
79+ /*
80+ * Isso fará que seja desabilitado no postgres temporiamente as restrições de integridade
81+ * como: foreign key, unique key, check, etc.
82+ */
83+ await context . Database . ExecuteSqlRawAsync ( "SET session_replication_role = 'replica';" ) ;
84+ var tables = await context . Database
85+ . SqlQueryRaw < string > ( """
86+ SELECT tablename
87+ FROM pg_tables
88+ WHERE schemaname='public'
89+ AND tablename != '__EFMigrationsHistory';
90+ """ )
91+ . ToListAsync ( ) ;
92+
93+ #pragma warning disable EF1002
94+ foreach ( var table in tables )
95+ await context . Database . ExecuteSqlRawAsync ( $ "TRUNCATE TABLE \" { table } \" RESTART IDENTITY CASCADE;") ;
96+ #pragma warning restore EF1002
97+
98+ await context . Database . ExecuteSqlRawAsync ( "SET session_replication_role = 'origin';" ) ;
99+ }
100+
101+ protected async Task AuthenticateAsync ( )
102+ => Client . DefaultRequestHeaders . Authorization =
103+ new System . Net . Http . Headers . AuthenticationHeaderValue ( "Bearer" , await GetTokenAsync ( ) ) ;
104+
105+ protected void ClearAuthentication ( )
106+ => Client . DefaultRequestHeaders . Authorization = null ;
107+
108+ private async Task < string > GetTokenAsync ( )
109+ {
110+ var loginResponse = await Client . PostAsJsonAsync ( "api/v1/auth/login" ,
111+ new { Username = "admin123" , Password = "Admin@123" } ) ;
112+
113+ loginResponse . EnsureSuccessStatusCode ( ) ;
114+ var result = await loginResponse . Content . ReadFromJsonAsync < Result < LoginCommandResponse > > ( ) ;
115+ return result ? . Value . Token ?? string . Empty ;
116+ }
117+
118+ #endregion
119+ }
0 commit comments