Skip to content

Commit 10685d7

Browse files
committed
chore: 优化测试细节;
1 parent c66fd05 commit 10685d7

38 files changed

+139
-224
lines changed

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
<LangVersion>latest</LangVersion>
99
</PropertyGroup>
1010

11-
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
11+
<ItemGroup Condition="'$(Configuration)' == 'DEBUG'">
1212
<PackageReference Include="Cuture.CodeAnalysis.LoggingCodeFixes" Version="1.0.1" PrivateAssets="all" />
1313
</ItemGroup>
1414
</Project>

test/ResponseCaching.Test.WebHost/Controllers/HotDataCacheController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class HotDataCacheController : TestControllerBase
1010

1111
[HttpGet]
1212
[HotDataCache(50, HotDataCachePolicy.LRU)]
13-
[ResponseCaching(3,
13+
[ResponseCaching(10,
1414
Mode = CacheMode.FullPathAndQuery,
1515
StoreLocation = CacheStoreLocation.Distributed)]
1616
[ExecutingLock(ExecutingLockMode.CacheKeySingle)]
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
using System.Text;
2+
using Microsoft.AspNetCore.Authentication.Cookies;
3+
using Microsoft.AspNetCore.Authentication.JwtBearer;
4+
using Microsoft.IdentityModel.Tokens;
5+
using ResponseCaching.Test.WebHost.Test;
6+
7+
var builder = WebApplication.CreateBuilder(args);
8+
9+
builder.Configuration.AddUserSecrets<Program>();
10+
11+
builder.Logging.AddSimpleConsole(options =>
12+
{
13+
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff ";
14+
});
15+
16+
var services = builder.Services;
17+
18+
services.AddResponseCaching();
19+
20+
var redisConfigureString = builder.Configuration.GetValue<string>("ResponseCache_Test_Redis");
21+
services.AddCaching(builder.Configuration.GetSection("Caching:ResponseCaching"))
22+
//.UseRedisResponseCache(redisConfigureString, Configuration.GetSection("Caching:ResponseCaching:CacheKeyPrefix").Value)
23+
.AddDiagnosticDebugLogger();
24+
25+
//HACK 清理缓存,避免影响测试 -- 连接字符串需要添加 allowAdmin=true
26+
//{
27+
// var connectionMultiplexer = ConnectionMultiplexer.Connect(redisConfigureString);
28+
// connectionMultiplexer.GetServer(redisConfigureString.Split(',')[0]).FlushAllDatabases();
29+
//}
30+
31+
services.AddControllers();
32+
33+
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
34+
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
35+
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
36+
{
37+
x.RequireHttpsMetadata = false;
38+
x.SaveToken = true;
39+
x.TokenValidationParameters = new TokenValidationParameters
40+
{
41+
ValidateIssuerSigningKey = true,
42+
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123456789123456789_123456789123456789")),
43+
ValidIssuer = "Issuer",
44+
ValidAudience = "Audience",
45+
ValidateIssuer = false,
46+
ValidateAudience = false
47+
};
48+
});
49+
50+
services.AddTransient<TestCustomCacheKeyGenerator>();
51+
services.AddSingleton<TestCustomModelKeyParser>();
52+
53+
#if NET9_0_OR_GREATER
54+
services.AddOpenApi();
55+
#endif
56+
57+
var app = builder.Build();
58+
59+
if (app.Environment.IsDevelopment())
60+
{
61+
app.UseDeveloperExceptionPage();
62+
63+
#if NET9_0_OR_GREATER
64+
app.MapOpenApi();
65+
app.MapSwaggerUI();
66+
#endif
67+
}
68+
69+
app.EnableResponseCachingDiagnosticLogger();
70+
71+
app.UseRouting();
72+
73+
app.UseAuthorization();
74+
75+
app.MapControllers();
76+
77+
app.Run();
78+
79+
public partial class Program
80+
{ }

test/ResponseCaching.Test.WebHost/Properties/launchSettings.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"$schema": "http://json.schemastore.org/launchsettings.json",
33
"profiles": {
4-
"ResponseCaching.Test.WebHost": {
4+
"TestWebHost": {
55
"commandName": "Project",
66
"launchBrowser": false,
77
"launchUrl": "weatherforecast",
8-
"applicationUrl": "http://0.0.0.0:5000",
8+
"applicationUrl": "http://0.0.0.0:5272",
99
"environmentVariables": {
1010
"ASPNETCORE_ENVIRONMENT": "Development"
1111
}

test/ResponseCaching.Test.WebHost/ResponseCaching.Test.WebHost.csproj

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
</ItemGroup>
1515

1616
<ItemGroup Condition="'$(Configuration)' == 'DEBUG'">
17-
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.*" />
17+
<PackageReference Include="SwaggerUI.AspNetCore" Version="5.30.2" />
1818
</ItemGroup>
1919

2020
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
@@ -25,11 +25,13 @@
2525
<ItemGroup Condition="'$(TargetFramework)' == 'net9.0'">
2626
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.*" />
2727
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="9.0.*" />
28+
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.*" />
2829
</ItemGroup>
2930

3031
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
3132
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.*" />
3233
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="10.0.*" />
34+
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.*" />
3335
</ItemGroup>
3436

3537
<ItemGroup>

test/ResponseCaching.Test.WebHost/Startup.cs

Lines changed: 0 additions & 95 deletions
This file was deleted.

test/ResponseCaching.Test.WebHost/TestWebHost.cs

Lines changed: 0 additions & 36 deletions
This file was deleted.

test/ResponseCaching.Test.WebHost/appsettings.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"Logging": {
33
"LogLevel": {
44
//日志太多会影响执行时间,测试无法通过
5-
"Default": "Warning"
5+
"Default": "Warning",
6+
"Microsoft.Hosting": "Information"
67
}
78
},
89
"AllowedHosts": "*",
@@ -15,4 +16,4 @@
1516
//"DefaultCacheStoreLocation": "Distributed"
1617
}
1718
}
18-
}
19+
}

test/ResponseCaching.Test/Base/AuthenticationRequiredTestBase.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
using Cuture.Http;
22
using Cuture.Http.Util;
33

4-
using Microsoft.VisualStudio.TestTools.UnitTesting;
5-
64
namespace ResponseCaching.Test.Base;
75

86
[TestClass]

test/ResponseCaching.Test/Base/WebServerHostedTestBase.cs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
using System.Diagnostics;
22

33
using Cuture.Http;
4-
4+
using Microsoft.AspNetCore.Mvc.Testing;
55
using Microsoft.AspNetCore.TestHost;
6-
using Microsoft.Extensions.Hosting;
7-
using Microsoft.VisualStudio.TestTools.UnitTesting;
8-
9-
using ResponseCaching.Test.WebHost;
6+
using Microsoft.Extensions.DependencyInjection;
107

118
namespace ResponseCaching.Test.Base;
129

@@ -15,13 +12,15 @@ public abstract class WebServerHostedTestBase
1512
{
1613
#region Public 属性
1714

18-
public string BaseUrl { get; set; } = "http://127.0.0.1:18080";
15+
public string BaseUrl { get; set; } = "http://127.0.0.1";
1916

2017
#endregion Public 属性
2118

2219
#region Protected 属性
2320

24-
protected IHost WebHost { get; private set; }
21+
protected TestServer TestServer { get; private set; } = null!;
22+
23+
protected IAsyncDisposable WebApplication { get; private set; } = null!;
2524

2625
#endregion Protected 属性
2726

@@ -30,22 +29,27 @@ public abstract class WebServerHostedTestBase
3029
[TestCleanup]
3130
public virtual async Task CleanupAsync()
3231
{
33-
if (WebHost != null)
32+
TestServer?.Dispose();
33+
34+
if (WebApplication != null)
3435
{
35-
await WebHost.StopAsync();
36-
WebHost.Dispose();
36+
await WebApplication.DisposeAsync();
3737
}
3838
}
3939

4040
[TestInitialize]
4141
public virtual async Task InitAsync()
4242
{
43-
TestWebHost.IsTest = true;
44-
var hostBuilder = TestWebHost.CreateHostBuilder(GetHostArgs());
45-
await ConfigureWebHost(hostBuilder);
46-
WebHost = await hostBuilder.StartAsync();
43+
var webApplicationFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
44+
{
45+
builder.UseTestServer();
46+
builder.ConfigureTestServices(ConfigureServices);
47+
});
4748

48-
HttpRequestGlobalOptions.DefaultHttpMessageInvokerPool = new TestCutureHttpMessageInvokerPool(WebHost.GetTestClient());
49+
WebApplication = webApplicationFactory;
50+
TestServer = webApplicationFactory.Server;
51+
52+
HttpRequestGlobalOptions.DefaultHttpMessageInvokerPool = new TestCutureHttpMessageInvokerPool(TestServer.CreateClient());
4953

5054
HttpRequestGlobalOptions.DefaultConnectionLimit = 500;
5155
}
@@ -141,9 +145,8 @@ protected void CheckForEachOther<T>(T[][] data, bool equal) where T : IEquatable
141145

142146
protected virtual IHttpRequest ConfigureBeforeRequest(IHttpRequest request) => request;
143147

144-
protected virtual Task ConfigureWebHost(IHostBuilder hostBuilder) => Task.CompletedTask;
145-
146-
protected virtual string[] GetHostArgs() => new[] { "--urls", BaseUrl };
148+
protected virtual void ConfigureServices(IServiceCollection services)
149+
{ }
147150

148151
protected virtual async Task<T[][]> InternalRunAsync<T>(Func<Task<TextHttpOperationResult<T[]>>>[] funcs)
149152
{

0 commit comments

Comments
 (0)