blob: 98c0dfd86ea9c4dd478bd0a0a76a71f41a07c183 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
using System.Net;
using CrupestApi.Commons.Secrets;
using Microsoft.AspNetCore.TestHost;
namespace CrupestApi.Commons.Crud.Tests;
public abstract class CrudTestBase<TEntity> : IAsyncDisposable where TEntity : class
{
protected readonly WebApplication _app;
protected readonly string _path;
protected readonly string? _authKey;
protected readonly HttpClient _client;
public CrudTestBase(string path, string? authKey = null)
{
_path = path;
_authKey = authKey;
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
builder.Services.AddCrud<TEntity>();
ConfigureApplication(builder);
_app = builder.Build();
if (authKey is not null)
{
using (var scope = _app.Services.CreateScope())
{
var secretService = scope.ServiceProvider.GetRequiredService<ISecretService>();
secretService.CreateTestSecret(authKey, "test-secret");
}
}
_client = CreateHttpClient();
}
protected abstract void ConfigureApplication(WebApplicationBuilder builder);
public virtual async ValueTask DisposeAsync()
{
await _app.DisposeAsync();
}
public TestServer GetTestServer()
{
return _app.GetTestServer();
}
public HttpClient CreateHttpClient()
{
return GetTestServer().CreateClient();
}
public async Task TestAuth()
{
if (_authKey is null)
{
return;
}
{
using var response = await _client.GetAsync(_path);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
{
var entity = Activator.CreateInstance<TEntity>();
using var response = await _client.PostAsJsonAsync(_path, entity);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
|