Skip to content

Commit f4b3d6c

Browse files
committed
Add Web.Tests project.
1 parent 33c6c09 commit f4b3d6c

File tree

6 files changed

+412
-0
lines changed

6 files changed

+412
-0
lines changed

aspnet-core/AbpCompanyName.AbpProjectName.sln

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbpCompanyName.AbpProjectNa
2323
EndProject
2424
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbpCompanyName.AbpProjectName.EntityFrameworkCore", "src\AbpCompanyName.AbpProjectName.EntityFrameworkCore\AbpCompanyName.AbpProjectName.EntityFrameworkCore.csproj", "{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}"
2525
EndProject
26+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbpCompanyName.AbpProjectName.Web.Tests", "test\AbpCompanyName.AbpProjectName.Web.Tests\AbpCompanyName.AbpProjectName.Web.Tests.csproj", "{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087}"
27+
EndProject
2628
Global
2729
GlobalSection(SolutionConfigurationPlatforms) = preSolution
2830
Debug|Any CPU = Debug|Any CPU
@@ -61,6 +63,10 @@ Global
6163
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Debug|Any CPU.Build.0 = Debug|Any CPU
6264
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Release|Any CPU.ActiveCfg = Release|Any CPU
6365
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Release|Any CPU.Build.0 = Release|Any CPU
66+
{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
67+
{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087}.Debug|Any CPU.Build.0 = Debug|Any CPU
68+
{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087}.Release|Any CPU.ActiveCfg = Release|Any CPU
69+
{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087}.Release|Any CPU.Build.0 = Release|Any CPU
6470
EndGlobalSection
6571
GlobalSection(SolutionProperties) = preSolution
6672
HideSolutionNode = FALSE
@@ -74,5 +80,6 @@ Global
7480
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
7581
{A2213374-BB48-48FD-BBD4-81E6A961D866} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
7682
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
83+
{CA86CF6F-5D9E-4DAC-9CCB-0F87B519E087} = {F10AA149-2626-486E-85BB-9CD5365F3016}
7784
EndGlobalSection
7885
EndGlobal
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<VersionPrefix>1.0.0.0</VersionPrefix>
5+
<TargetFramework>netcoreapp3.1</TargetFramework>
6+
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
7+
<AssemblyName>AbpCompanyName.AbpProjectName.Web.Tests</AssemblyName>
8+
<PackageId>AbpCompanyName.AbpProjectName.Web.Tests</PackageId>
9+
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
10+
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
11+
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
12+
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
13+
</PropertyGroup>
14+
15+
<ItemGroup>
16+
<ProjectReference Include="..\..\src\AbpCompanyName.AbpProjectName.Web.Mvc\AbpCompanyName.AbpProjectName.Web.Mvc.csproj" />
17+
<ProjectReference Include="..\AbpCompanyName.AbpProjectName.Tests\AbpCompanyName.AbpProjectName.Tests.csproj" />
18+
</ItemGroup>
19+
20+
<ItemGroup>
21+
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
22+
<PackageReference Include="NSubstitute" Version="4.2.1" />
23+
<PackageReference Include="Shouldly" Version="3.0.2" />
24+
<PackageReference Include="xunit" Version="2.4.1" />
25+
<PackageReference Include="xunit.extensibility.execution" Version="2.4.1" />
26+
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
27+
<PrivateAssets>all</PrivateAssets>
28+
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
29+
</PackageReference>
30+
<PackageReference Include="Abp.AspNetCore.TestBase" Version="5.4.0" />
31+
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.0" />
32+
<PackageReference Include="Castle.Core" Version="4.4.0" />
33+
<PackageReference Include="AngleSharp" Version="0.13.0" />
34+
</ItemGroup>
35+
36+
</Project>
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
using System;
2+
using System.Linq;
3+
using System.Net;
4+
using System.Net.Http;
5+
using System.Net.Http.Headers;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
using Abp.AspNetCore.TestBase;
9+
using Abp.Authorization.Users;
10+
using Abp.Json;
11+
using Abp.MultiTenancy;
12+
using Abp.Web.Models;
13+
using AbpCompanyName.AbpProjectName.EntityFrameworkCore;
14+
using AbpCompanyName.AbpProjectName.Models.TokenAuth;
15+
using AbpCompanyName.AbpProjectName.Web.Startup;
16+
using AngleSharp.Html.Dom;
17+
using AngleSharp.Html.Parser;
18+
using Microsoft.AspNetCore.Hosting;
19+
using Newtonsoft.Json;
20+
using Newtonsoft.Json.Serialization;
21+
using Shouldly;
22+
23+
namespace AbpCompanyName.AbpProjectName.Web.Tests
24+
{
25+
public abstract class AbpProjectNameWebTestBase : AbpAspNetCoreIntegratedTestBase<Startup>
26+
{
27+
protected static readonly Lazy<string> ContentRootFolder;
28+
29+
static AbpProjectNameWebTestBase()
30+
{
31+
ContentRootFolder = new Lazy<string>(WebContentDirectoryFinder.CalculateContentRootFolder, true);
32+
}
33+
34+
protected override IWebHostBuilder CreateWebHostBuilder()
35+
{
36+
return base
37+
.CreateWebHostBuilder()
38+
.UseContentRoot(ContentRootFolder.Value)
39+
.UseSetting(WebHostDefaults.ApplicationKey, typeof(AbpProjectNameWebMvcModule).Assembly.FullName);
40+
}
41+
42+
#region Get response
43+
44+
protected async Task<T> GetResponseAsObjectAsync<T>(string url,
45+
HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
46+
{
47+
var strResponse = await GetResponseAsStringAsync(url, expectedStatusCode);
48+
return JsonConvert.DeserializeObject<T>(strResponse, new JsonSerializerSettings
49+
{
50+
ContractResolver = new CamelCasePropertyNamesContractResolver()
51+
});
52+
}
53+
54+
protected async Task<string> GetResponseAsStringAsync(string url,
55+
HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
56+
{
57+
var response = await GetResponseAsync(url, expectedStatusCode);
58+
return await response.Content.ReadAsStringAsync();
59+
}
60+
61+
protected async Task<HttpResponseMessage> GetResponseAsync(string url,
62+
HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
63+
{
64+
var response = await Client.GetAsync(url);
65+
response.StatusCode.ShouldBe(expectedStatusCode);
66+
return response;
67+
}
68+
69+
#endregion
70+
71+
#region Authenticate
72+
73+
/// <summary>
74+
/// /api/TokenAuth/Authenticate
75+
/// TokenAuthController
76+
/// </summary>
77+
/// <param name="tenancyName"></param>
78+
/// <param name="input"></param>
79+
/// <returns></returns>
80+
protected async Task AuthenticateAsync(string tenancyName, AuthenticateModel input)
81+
{
82+
var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
83+
if (tenant != null)
84+
{
85+
AbpSession.TenantId = tenant.Id;
86+
Client.DefaultRequestHeaders.Add("Abp.TenantId", tenant.Id.ToString()); //Set TenantId
87+
}
88+
89+
var response = await Client.PostAsync("/api/TokenAuth/Authenticate",
90+
new StringContent(input.ToJsonString(), Encoding.UTF8, "application/json"));
91+
response.StatusCode.ShouldBe(HttpStatusCode.OK);
92+
var result =
93+
JsonConvert.DeserializeObject<AjaxResponse<AuthenticateResultModel>>(
94+
await response.Content.ReadAsStringAsync());
95+
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Result.AccessToken);
96+
97+
AbpSession.UserId = result.Result.UserId;
98+
}
99+
100+
#endregion
101+
102+
#region Login
103+
104+
protected void LoginAsHostAdmin()
105+
{
106+
LoginAsHost(AbpUserBase.AdminUserName);
107+
}
108+
109+
protected void LoginAsDefaultTenantAdmin()
110+
{
111+
LoginAsTenant(AbpTenantBase.DefaultTenantName, AbpUserBase.AdminUserName);
112+
}
113+
114+
protected void LoginAsHost(string userName)
115+
{
116+
AbpSession.TenantId = null;
117+
118+
var user =
119+
UsingDbContext(
120+
context =>
121+
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
122+
if (user == null)
123+
{
124+
throw new Exception("There is no user: " + userName + " for host.");
125+
}
126+
127+
AbpSession.UserId = user.Id;
128+
}
129+
130+
protected void LoginAsTenant(string tenancyName, string userName)
131+
{
132+
var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
133+
if (tenant == null)
134+
{
135+
throw new Exception("There is no tenant: " + tenancyName);
136+
}
137+
138+
AbpSession.TenantId = tenant.Id;
139+
140+
var user =
141+
UsingDbContext(
142+
context =>
143+
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
144+
if (user == null)
145+
{
146+
throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
147+
}
148+
149+
AbpSession.UserId = user.Id;
150+
}
151+
152+
#endregion
153+
154+
155+
#region UsingDbContext
156+
157+
protected void UsingDbContext(Action<AbpProjectNameDbContext> action)
158+
{
159+
using (var context = IocManager.Resolve<AbpProjectNameDbContext>())
160+
{
161+
action(context);
162+
context.SaveChanges();
163+
}
164+
}
165+
166+
protected T UsingDbContext<T>(Func<AbpProjectNameDbContext, T> func)
167+
{
168+
T result;
169+
170+
using (var context = IocManager.Resolve<AbpProjectNameDbContext>())
171+
{
172+
result = func(context);
173+
context.SaveChanges();
174+
}
175+
176+
return result;
177+
}
178+
179+
protected async Task UsingDbContextAsync(Func<AbpProjectNameDbContext, Task> action)
180+
{
181+
using (var context = IocManager.Resolve<AbpProjectNameDbContext>())
182+
{
183+
await action(context);
184+
await context.SaveChangesAsync(true);
185+
}
186+
}
187+
188+
protected async Task<T> UsingDbContextAsync<T>(Func<AbpProjectNameDbContext, Task<T>> func)
189+
{
190+
T result;
191+
192+
using (var context = IocManager.Resolve<AbpProjectNameDbContext>())
193+
{
194+
result = await func(context);
195+
await context.SaveChangesAsync(true);
196+
}
197+
198+
return result;
199+
}
200+
201+
#endregion
202+
203+
#region ParseHtml
204+
205+
protected IHtmlDocument ParseHtml(string htmlString)
206+
{
207+
return new HtmlParser().ParseDocument(htmlString);
208+
}
209+
210+
#endregion
211+
}
212+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using Abp.AspNetCore;
2+
using Abp.AspNetCore.TestBase;
3+
using Abp.Modules;
4+
using Abp.Reflection.Extensions;
5+
using AbpCompanyName.AbpProjectName.EntityFrameworkCore;
6+
using AbpCompanyName.AbpProjectName.Web.Startup;
7+
using Microsoft.AspNetCore.Mvc.ApplicationParts;
8+
9+
namespace AbpCompanyName.AbpProjectName.Web.Tests
10+
{
11+
[DependsOn(
12+
typeof(AbpProjectNameWebMvcModule),
13+
typeof(AbpAspNetCoreTestBaseModule)
14+
)]
15+
public class AbpProjectNameWebTestModule : AbpModule
16+
{
17+
public AbpProjectNameWebTestModule(AbpProjectNameEntityFrameworkModule abpProjectNameEntityFrameworkModule)
18+
{
19+
abpProjectNameEntityFrameworkModule.SkipDbContextRegistration = true;
20+
}
21+
22+
public override void PreInitialize()
23+
{
24+
Configuration.UnitOfWork.IsTransactional = false; //EF Core InMemory DB does not support transactions.
25+
}
26+
27+
public override void Initialize()
28+
{
29+
IocManager.RegisterAssemblyByConvention(typeof(AbpProjectNameWebTestModule).GetAssembly());
30+
}
31+
32+
public override void PostInitialize()
33+
{
34+
IocManager.Resolve<ApplicationPartManager>()
35+
.AddApplicationPartsIfNotAddedBefore(typeof(AbpProjectNameWebMvcModule).Assembly);
36+
}
37+
}
38+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System.Threading.Tasks;
2+
using AbpCompanyName.AbpProjectName.Models.TokenAuth;
3+
using AbpCompanyName.AbpProjectName.Web.Controllers;
4+
using Shouldly;
5+
using Xunit;
6+
7+
namespace AbpCompanyName.AbpProjectName.Web.Tests.Controllers
8+
{
9+
public class HomeController_Tests: AbpProjectNameWebTestBase
10+
{
11+
[Fact]
12+
public async Task Index_Test()
13+
{
14+
await AuthenticateAsync(null, new AuthenticateModel
15+
{
16+
UserNameOrEmailAddress = "admin",
17+
Password = "123qwe"
18+
});
19+
20+
//Act
21+
var response = await GetResponseAsStringAsync(
22+
GetUrl<HomeController>(nameof(HomeController.Index))
23+
);
24+
25+
//Assert
26+
response.ShouldNotBeNullOrEmpty();
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)