单元测试:使用Collection重构单元测试,提高效率

This commit is contained in:
Argo-Surface 2019-01-21 17:33:20 +08:00
parent 775ad02c29
commit f019c2a49b
36 changed files with 1018 additions and 825 deletions

55
UnitTest/BAWebHost.cs Normal file
View File

@ -0,0 +1,55 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Mvc.Testing.Handlers;
using System;
using System.Net;
using System.Net.Http;
using UnitTest;
using Xunit;
namespace Bootstrap.Admin
{
[CollectionDefinition("BootstrapAdminTestContext")]
public class BootstrapAdminTestContext : ICollectionFixture<BAWebHost>
{
}
/// <summary>
///
/// </summary>
public class BAWebHost : WebApplicationFactory<Startup>
{
/// <summary>
///
/// </summary>
static BAWebHost()
{
// Copy license
TestHelper.CopyLicense();
}
public BAWebHost()
{
var client = CreateClient("Account/Login");
var login = client.LoginAsync();
login.Wait();
}
/// <summary>
/// 获得已经登录的HttpClient
/// </summary>
/// <param name="baseAddress"></param>
/// <returns></returns>
public HttpClient CreateClient(string baseAddress) => CreateDefaultClient(new Uri($"http://localhost/{baseAddress}/"), new RedirectHandler(7), new CookieContainerHandler(_cookie));
private readonly CookieContainer _cookie = new CookieContainer();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
TestHelper.ConfigureWebHost(builder);
}
}
}

View File

@ -0,0 +1,17 @@
using System.Collections.Generic;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class CategoryTest : ControllerTest
{
public CategoryTest(BAWebHost factory) : base(factory, "api/Category") { }
[Fact]
public async void Get_Ok()
{
var cates = await Client.GetAsJsonAsync<IEnumerable<string>>();
Assert.NotEmpty(cates);
}
}
}

View File

@ -0,0 +1,36 @@
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Longbow.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class DictTest : ControllerTest
{
public DictTest(BAWebHost factory) : base(factory, "api/Dicts") { }
[Fact]
public async void Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "?sort=Category&order=asc&offset=0&limit=20&category=%E8%8F%9C%E5%8D%95&name=%E7%B3%BB%E7%BB%9F%E8%8F%9C%E5%8D%95&define=0&_=1547608210979";
var qd = await Client.GetAsJsonAsync<QueryData<BootstrapDict>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void PostAndDelete_Ok()
{
var dict = new Dict();
dict.Delete(new Dict().RetrieveDicts().Where(d => d.Category == "UnitTest-Category").Select(d => d.Id));
var ret = await Client.PostAsJsonAsync<BootstrapDict, bool>("", new BootstrapDict() { Name = "UnitTest-Dict", Category = "UnitTest-Category", Code = "0", Define = 0 });
Assert.True(ret);
var ids = dict.RetrieveDicts().Where(d => d.Name == "UnitTest-Dict").Select(d => d.Id);
Assert.True(await Client.DeleteAsJsonAsync<IEnumerable<string>, bool>(ids));
}
}
}

View File

@ -0,0 +1,49 @@
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Longbow.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using static Bootstrap.Admin.Controllers.Api.ExceptionsController;
namespace Bootstrap.Admin.Api
{
public class ExceptionsTest : ControllerTest
{
public ExceptionsTest(BAWebHost factory) : base(factory, "api/Exceptions") { }
[Fact]
public async void Get_Ok()
{
// insert exception
var excep = new Exceptions();
Assert.True(excep.Log(new Exception("UnitTest"), null));
// 菜单 系统菜单 系统使用条件
var query = "?sort=LogTime&order=desc&offset=0&limit=20&StartTime=&EndTime=&_=1547610349796";
var qd = await Client.GetAsJsonAsync<QueryData<BootstrapDict>>(query);
Assert.NotEmpty(qd.rows);
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
[Fact]
public async void Post_Ok()
{
var files = await Client.PostAsJsonAsync<string, IEnumerable<string>>(string.Empty);
Assert.NotNull(files);
var fileName = files.FirstOrDefault();
if (!string.IsNullOrEmpty(fileName))
{
var resp = await Client.PutAsJsonAsync<ExceptionFileQuery, string>(new ExceptionFileQuery() { FileName = fileName });
Assert.NotNull(resp);
}
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
}
}

View File

@ -0,0 +1,65 @@
using Bootstrap.DataAccess;
using Longbow.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class GroupsTest : ControllerTest
{
public GroupsTest(BAWebHost factory) : base(factory, "api/Groups") { }
[Fact]
public async void Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "?sort=GroupName&order=asc&offset=0&limit=20&groupName=Admin&description=%E7%B3%BB%E7%BB%9F%E9%BB%98%E8%AE%A4%E7%BB%84&_=1547614230481";
var qd = await Client.GetAsJsonAsync<QueryData<Group>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void GetById_Ok()
{
var id = new Group().Retrieves().Where(gp => gp.GroupName == "Admin").First().Id;
var g = await Client.GetAsJsonAsync<Group>(id);
Assert.Equal("Admin", g.GroupName);
}
[Fact]
public async void PostAndDelete_Ok()
{
var ret = await Client.PostAsJsonAsync<Group, bool>("", new Group() { GroupName = "UnitTest-Group", Description = "UnitTest-Desc" });
Assert.True(ret);
var ids = new Group().Retrieves().Where(d => d.GroupName == "UnitTest-Group").Select(d => d.Id);
Assert.True(await Client.DeleteAsJsonAsync<IEnumerable<string>, bool>(ids));
}
[Fact]
public async void PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await Client.PostAsJsonAsync<string, IEnumerable<Group>>($"{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await Client.PostAsJsonAsync<string, IEnumerable<Group>>($"{rid}?type=role", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void PutById_Ok()
{
var ids = new Group().Retrieves().Select(g => g.Id);
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{uid}?type=user", ids);
Assert.True(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{rid}?type=role", ids);
Assert.True(ret);
}
}
}

View File

@ -0,0 +1,46 @@
using Bootstrap.Security;
using System.Collections.Generic;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class InterfaceTest : ControllerTest
{
public InterfaceTest(BAWebHost factory) : base(factory, "api/Interface") { }
[Fact]
public async void RetrieveDicts_Ok()
{
var ret = await Client.PostAsJsonAsync<string, IEnumerable<BootstrapDict>>("RetrieveDicts", "");
Assert.NotEmpty(ret);
}
[Fact]
public async void RetrieveRolesByUrl_Ok()
{
var ret = await Client.PostAsJsonAsync<string, IEnumerable<string>>("RetrieveRolesByUrl", "~/Admin/Index");
Assert.NotEmpty(ret);
}
[Fact]
public async void RetrieveRolesByUserName_Ok()
{
var ret = await Client.PostAsJsonAsync<string, IEnumerable<string>>("RetrieveRolesByUserName", "Admin");
Assert.NotEmpty(ret);
}
[Fact]
public async void RetrieveUserByUserName_Ok()
{
var ret = await Client.PostAsJsonAsync<string, BootstrapUser>("RetrieveUserByUserName", "Admin");
Assert.Equal("Admin", ret.UserName);
}
[Fact]
public async void RetrieveAppMenus_Ok()
{
var ret = await Client.PostAsJsonAsync<AppMenuOption, IEnumerable<BootstrapMenu>>("RetrieveAppMenus", new AppMenuOption() { AppId = "0", UserName = "Admin", Url = "~/Admin/Index" });
Assert.NotEmpty(ret);
}
}
}

View File

@ -0,0 +1,25 @@
using System.Net.Http;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class LoginTest : ControllerTest
{
public LoginTest(BAWebHost factory) : base(factory, "api/Login") { }
[Fact]
public async void Login_Ok()
{
var resq = await Client.PostAsJsonAsync("", new { userName = "Admin", password = "123789" });
var _token = await resq.Content.ReadAsStringAsync();
Assert.NotNull(_token);
}
[Fact]
public async void Option_Ok()
{
var req = new HttpRequestMessage(HttpMethod.Options, "");
var resp = await Client.SendAsync(req);
}
}
}

View File

@ -0,0 +1,37 @@
using Bootstrap.DataAccess;
using Longbow.Web.Mvc;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class LogsTest : ControllerTest
{
public LogsTest(BAWebHost factory) : base(factory, "api/Logs") { }
[Fact]
public async void Get_Ok()
{
var log = new Log() { CRUD = "UnitTest", ClientAgent = "UnitTest", ClientIp = "::1", RequestUrl = "~/UnitTest", UserName = "UnitTest" };
log.Save(log);
// 菜单 系统菜单 系统使用条件
var query = "?sort=LogTime&order=desc&offset=0&limit=20&operateType=&OperateTimeStart=&OperateTimeEnd=&_=1547617573596";
var qd = await Client.GetAsJsonAsync<QueryData<Log>>(query);
Assert.NotEmpty(qd.rows);
// clean
DbManager.Create().Execute("Delete from Logs where CRUD = @0", log.CRUD);
}
[Fact]
public async void Post_Ok()
{
Client.DefaultRequestHeaders.Add("user-agent", "UnitTest");
var resp = await Client.PostAsJsonAsync<Log, bool>("", new Log() { CRUD = "UnitTest", RequestUrl = "~/UnitTest" });
Assert.True(resp);
// clean
DbManager.Create().Execute("delete from Logs where CRUD = @0", "UnitTest");
}
}
}

View File

@ -0,0 +1,56 @@
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Longbow.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class MenusTest : ControllerTest
{
public MenusTest(BAWebHost factory) : base(factory, "api/Menus") { }
[Fact]
public async void Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "?sort=Order&order=asc&offset=0&limit=20&parentName=&name=%E5%90%8E%E5%8F%B0%E7%AE%A1%E7%90%86&category=0&isresource=0&_=1547619684999";
var qd = await Client.GetAsJsonAsync<QueryData<object>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void PostAndDelete_Ok()
{
var ret = await Client.PostAsJsonAsync<BootstrapMenu, bool>(new BootstrapMenu() { Name = "UnitTest-Menu", Application = "0", Category = "0", ParentId = "0", Url = "#", Target = "_self", IsResource = 0 });
Assert.True(ret);
var menu = new Menu();
var ids = menu.RetrieveAllMenus("Admin").Where(d => d.Name == "UnitTest-Menu").Select(d => d.Id);
Assert.True(await Client.DeleteAsJsonAsync<IEnumerable<string>, bool>("", ids));
}
[Fact]
public async void PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{rid}?type=role", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void PutById_Ok()
{
var ids = new Menu().RetrieveAllMenus("Admin").Select(g => g.Id);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
var ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{rid}", ids);
Assert.True(ret);
}
}
}

View File

@ -0,0 +1,30 @@
using Bootstrap.Admin.Models;
using Bootstrap.DataAccess;
using System.Collections.Generic;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class MessagesTest : ControllerTest
{
public MessagesTest(BAWebHost factory) : base(factory, "api/Messages") { }
[Theory]
[InlineData("inbox")]
[InlineData("sendmail")]
[InlineData("mark")]
[InlineData("trash")]
public async void Get_Ok(string action)
{
var resp = await Client.GetAsJsonAsync<IEnumerable<Message>>(action);
Assert.NotNull(resp);
}
[Fact]
public async void GetCount_Ok()
{
var resp = await Client.GetAsJsonAsync<MessageCountModel>();
Assert.NotNull(resp);
}
}
}

View File

@ -0,0 +1,62 @@
using Bootstrap.DataAccess;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class NewTest : ControllerTest
{
public NewTest(BAWebHost factory) : base(factory, "api/New") { }
[Fact]
public async void Get_Ok()
{
var nusr = InsertNewUser();
var resp = await Client.GetAsJsonAsync<IEnumerable<object>>();
Assert.NotEmpty(resp);
// 删除新用户
DeleteUnitTestUser();
}
[Fact]
public async void Put_Ok()
{
DeleteUnitTestUser();
var nusr = InsertNewUser();
// Approve
nusr.UserStatus = UserStates.ApproveUser;
var resp = await Client.PutAsJsonAsync<User, bool>(nusr);
Assert.True(resp);
// 删除新用户
nusr.Delete(new string[] { nusr.Id });
// Reject
nusr = InsertNewUser();
nusr.UserStatus = UserStates.RejectUser;
resp = await Client.PutAsJsonAsync<User, bool>(nusr);
Assert.True(resp);
// 删除新用户
DeleteUnitTestUser();
}
private User InsertNewUser()
{
// 插入新用户
var nusr = new User() { UserName = "UnitTest-Register", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
Assert.True(new User().Save(nusr));
return nusr;
}
private void DeleteUnitTestUser()
{
var ids = new User().RetrieveNewUsers().Where(u => u.UserName == "UnitTest-Register").Select(u => u.Id);
new User().Delete(ids);
}
}
}

View File

@ -0,0 +1,16 @@
using Xunit;
namespace Bootstrap.Admin.Api
{
public class NotificationsTest : ControllerTest
{
public NotificationsTest(BAWebHost factory) : base(factory, "api/Notifications") { }
[Fact]
public async void Get_Ok()
{
var resp = await Client.GetAsJsonAsync<object>();
Assert.NotNull(resp);
}
}
}

View File

@ -0,0 +1,29 @@
using Bootstrap.DataAccess;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class RegisterTest : ControllerTest
{
public RegisterTest(BAWebHost factory) : base(factory, "api/Register") { }
[Fact]
public async void Get_Ok()
{
var resp = await Client.GetAsJsonAsync<bool>("?userName=Admin");
Assert.False(resp);
}
[Fact]
public async void Post_Ok()
{
// register new user
var nusr = new User() { UserName = "UnitTest-RegisterController", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
var resp = await Client.PostAsJsonAsync<User, bool>(nusr);
Assert.True(resp);
nusr.Delete(nusr.RetrieveNewUsers().Where(u => u.UserName == nusr.UserName).Select(u => u.Id));
}
}
}

View File

@ -0,0 +1,67 @@
using Bootstrap.DataAccess;
using Longbow.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class RolesTest : ControllerTest
{
public RolesTest(BAWebHost factory) : base(factory, "api/Roles") { }
[Fact]
public async void Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "?sort=RoleName&order=asc&offset=0&limit=20&roleName=Administrators&description=%E7%B3%BB%E7%BB%9F%E7%AE%A1%E7%90%86%E5%91%98&_=1547625202230";
var qd = await Client.GetAsJsonAsync<QueryData<Group>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void PostAndDelete_Ok()
{
var ret = await Client.PostAsJsonAsync<Role, bool>(new Role() { RoleName = "UnitTest-Role", Description = "UnitTest-Desc" });
Assert.True(ret);
var ids = new Role().Retrieves().Where(d => d.RoleName == "UnitTest-Role").Select(d => d.Id);
Assert.True(await Client.DeleteAsJsonAsync<IEnumerable<string>, bool>(ids));
}
[Fact]
public async void PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var gid = new Group().Retrieves().Where(g => g.GroupName == "Admin").First().Id;
var mid = new Menu().RetrieveAllMenus("Admin").Where(m => m.Url == "~/Admin/Index").First().Id;
var ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{gid}?type=group", string.Empty);
Assert.NotEmpty(ret);
ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{mid}?type=menu", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void PutById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var gid = new Group().Retrieves().Where(g => g.GroupName == "Admin").First().Id;
var mid = new Menu().RetrieveAllMenus("Admin").Where(m => m.Url == "~/Admin/Index").First().Id;
var ids = new Role().Retrieves().Select(r => r.Id);
var ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{uid}?type=user", ids);
Assert.True(ret);
ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{gid}?type=group", ids);
Assert.True(ret);
ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{mid}?type=menu", ids);
Assert.True(ret);
}
}
}

View File

@ -0,0 +1,44 @@
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Longbow.Cache;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class SettingsTest : ControllerTest
{
public SettingsTest(BAWebHost factory) : base(factory, "api/Settings") { }
[Fact]
public async void Get_Ok()
{
var resp = await Client.GetAsJsonAsync<IEnumerable<ICacheCorsItem>>();
Assert.NotNull(resp);
}
[Fact]
public async void Post_Ok()
{
var dict = new Dict();
var dicts = dict.RetrieveDicts();
var ids = dicts.Where(d => d.Category == "UnitTest-Settings").Select(d => d.Id);
dict.Delete(ids);
Assert.True(dict.Save(new Dict() { Category = "UnitTest-Settings", Name = "UnitTest", Code = "0", Define = 0 }));
// 获得原来值
var resp = await Client.PostAsJsonAsync<BootstrapDict, bool>(new Dict() { Category = "UnitTest-Settings", Name = "UnitTest", Code = "UnitTest" });
Assert.True(resp);
var code = dict.RetrieveDicts().FirstOrDefault(d => d.Category == "UnitTest-Settings").Code;
Assert.Equal("UnitTest", code);
// Delete
ids = dict.RetrieveDicts().Where(d => d.Category == "UnitTest-Settings").Select(d => d.Id);
dict.Delete(ids);
}
}
}

View File

@ -0,0 +1,18 @@
using Bootstrap.DataAccess;
using System.Collections.Generic;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class TasksTest : ControllerTest
{
public TasksTest(BAWebHost factory) : base(factory, "api/Tasks") { }
[Fact]
public async void Get_Ok()
{
var resp = await Client.GetAsJsonAsync<IEnumerable<Task>>();
Assert.NotNull(resp);
}
}
}

View File

@ -0,0 +1,117 @@
using Bootstrap.DataAccess;
using Longbow.Data;
using Longbow.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Xunit;
using DbManager = Longbow.Data.DbManager;
namespace Bootstrap.Admin.Api
{
public class UsersTest : ControllerTest
{
public UsersTest(BAWebHost factory) : base(factory, "api/Users") { }
[Fact]
public async void Option_Ok()
{
var req = new HttpRequestMessage(HttpMethod.Options, "Users");
var resp = await Client.SendAsync(req);
}
[Fact]
public async void Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "?sort=DisplayName&order=asc&offset=0&limit=20&name=Admin&displayName=Administrator&_=1547628247338";
var qd = await Client.GetAsJsonAsync<QueryData<object>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void PostAndDelete_Ok()
{
var user = new User();
user.Delete(user.Retrieves().Where(usr => usr.UserName == "UnitTest-Delete").Select(usr => usr.Id));
var nusr = new User { UserName = "UnitTest-Delete", Password = "1", DisplayName = "DisplayName", ApprovedBy = "System", ApprovedTime = DateTime.Now, Description = "Desc", Icon = "default.jpg" };
var resp = await Client.PostAsJsonAsync<User, bool>("", nusr);
Assert.True(resp);
nusr.Id = user.Retrieves().First(u => u.UserName == nusr.UserName).Id;
resp = await Client.PostAsJsonAsync<User, bool>(nusr);
Assert.True(resp);
var ids = user.Retrieves().Where(d => d.UserName == nusr.UserName).Select(d => d.Id);
Assert.True(await Client.DeleteAsJsonAsync<IEnumerable<string>, bool>(ids));
}
[Fact]
public async void PostById_Ok()
{
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
var ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{rid}?type=role", string.Empty);
Assert.NotNull(ret);
var gid = new Group().Retrieves().Where(r => r.GroupName == "Admin").First().Id;
ret = await Client.PostAsJsonAsync<string, IEnumerable<object>>($"{gid}?type=group", string.Empty);
Assert.NotNull(ret);
}
[Fact]
public async void PutById_Ok()
{
var ids = new User().Retrieves().Where(u => u.UserName == "Admin").Select(u => u.Id);
var gid = new Group().Retrieves().Where(r => r.GroupName == "Admin").First().Id;
var ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{gid}?type=group", ids);
Assert.True(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await Client.PutAsJsonAsync<IEnumerable<string>, bool>($"{rid}?type=role", ids);
Assert.True(ret);
}
[Fact]
public async void Put_Ok()
{
var usr = new User { UserName = "UnitTest-Change", Password = "1", DisplayName = "DisplayName", ApprovedBy = "System", ApprovedTime = DateTime.Now, Description = "Desc", Icon = "default.jpg" };
usr.Delete(usr.Retrieves().Where(u => u.UserName == usr.UserName).Select(u => u.Id));
Assert.True(usr.Save(usr));
// Add author
DbManager.Create().Execute("delete from NavigationRole where RoleID in (select ID from Roles where RoleName = 'Default')");
var rid = DbManager.Create().ExecuteScalar<string>("select ID from Roles where RoleName = 'Default'");
DbManager.Create().InsertBatch("NavigationRole", new Menu().RetrieveAllMenus("Admin").Select(m => new { RoleID = rid, NavigationID = m.Id }));
// change theme
usr.UserStatus = UserStates.ChangeTheme;
var resp = await Client.PutAsJsonAsync<User, bool>(usr);
Assert.False(resp);
// Login as new user
var client = Host.CreateClient();
client.BaseAddress = new Uri("http://localhost/api/Users");
await client.LoginAsync("UnitTest-Change", "1");
resp = await client.PutAsJsonAsync<User, bool>(usr);
Assert.True(resp);
// change password
usr.UserStatus = UserStates.ChangePassword;
usr.NewPassword = "1";
usr.Password = "1";
resp = await client.PutAsJsonAsync<User, bool>(usr);
Assert.True(resp);
// change displayname
usr.UserStatus = UserStates.ChangeDisplayName;
resp = await client.PutAsJsonAsync<User, bool>(usr);
Assert.True(resp);
// delete
usr.Delete(usr.Retrieves().Where(u => u.UserName == usr.UserName).Select(u => u.Id));
}
}
}

View File

@ -1,546 +0,0 @@
using Bootstrap.Admin.Models;
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Longbow.Cache;
using Longbow.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Xunit;
using static Bootstrap.Admin.Controllers.Api.ExceptionsController;
using static Longbow.Data.IPetaPocoExtensions;
namespace Bootstrap.Admin.Api
{
public class ApiTest : IClassFixture<BAWebHost>
{
private HttpClient _client;
protected BAWebHost _host;
public ApiTest(BAWebHost factory)
{
_host = factory;
_client = factory.CreateClient();
}
[Fact]
public async void Users_Option_Ok()
{
var req = new HttpRequestMessage(HttpMethod.Options, "Users");
var resp = await _client.SendAsync(req);
}
[Fact]
public async void Users_Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "Users?sort=DisplayName&order=asc&offset=0&limit=20&name=Admin&displayName=Administrator&_=1547628247338";
var qd = await _client.GetAsJsonAsync<QueryData<object>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void Users_PostAndDelete_Ok()
{
var user = new User();
user.Delete(user.Retrieves().Where(usr => usr.UserName == "UnitTest-Delete").Select(usr => usr.Id));
var nusr = new User { UserName = "UnitTest-Delete", Password = "1", DisplayName = "DisplayName", ApprovedBy = "System", ApprovedTime = DateTime.Now, Description = "Desc", Icon = "default.jpg" };
var resp = await _client.PostAsJsonAsync<User, bool>("Users", nusr);
Assert.True(resp);
nusr.Id = user.Retrieves().First(u => u.UserName == nusr.UserName).Id;
resp = await _client.PostAsJsonAsync<User, bool>("Users", nusr);
Assert.True(resp);
var ids = user.Retrieves().Where(d => d.UserName == nusr.UserName).Select(d => d.Id);
Assert.True(await _client.DeleteAsJsonAsync<IEnumerable<string>, bool>("Users", ids));
}
[Fact]
public async void Users_PostById_Ok()
{
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
var ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Users/{rid}?type=role", string.Empty);
Assert.NotNull(ret);
var gid = new Group().Retrieves().Where(r => r.GroupName == "Admin").First().Id;
ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Users/{gid}?type=group", string.Empty);
Assert.NotNull(ret);
}
[Fact]
public async void Users_PutById_Ok()
{
var ids = new User().Retrieves().Where(u => u.UserName == "Admin").Select(u => u.Id);
var gid = new Group().Retrieves().Where(r => r.GroupName == "Admin").First().Id;
var ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Users/{gid}?type=group", ids);
Assert.True(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Users/{rid}?type=role", ids);
Assert.True(ret);
}
[Fact]
public async void Users_Put_Ok()
{
var usr = new User { UserName = "UnitTest-Change", Password = "1", DisplayName = "DisplayName", ApprovedBy = "System", ApprovedTime = DateTime.Now, Description = "Desc", Icon = "default.jpg" };
usr.Delete(usr.Retrieves().Where(u => u.UserName == usr.UserName).Select(u => u.Id));
Assert.True(usr.Save(usr));
// Add author
DbManager.Create().Execute("delete from NavigationRole where RoleID in (select ID from Roles where RoleName = 'Default')");
var rid = DbManager.Create().ExecuteScalar<string>("select ID from Roles where RoleName = 'Default'");
DbManager.Create().InsertBatch("NavigationRole", new Menu().RetrieveAllMenus("Admin").Select(m => new { RoleID = rid, NavigationID = m.Id }));
// change theme
usr.UserStatus = UserStates.ChangeTheme;
var resp = await _client.PutAsJsonAsync<User, bool>("Users", usr);
Assert.False(resp);
// Login as new user
_host.Logout();
_host.Login("UnitTest-Change", "1");
_client = _host.CreateClient();
resp = await _client.PutAsJsonAsync<User, bool>("Users", usr);
Assert.True(resp);
// change password
usr.UserStatus = UserStates.ChangePassword;
usr.NewPassword = "1";
usr.Password = "1";
resp = await _client.PutAsJsonAsync<User, bool>("Users", usr);
Assert.True(resp);
// change displayname
usr.UserStatus = UserStates.ChangeDisplayName;
resp = await _client.PutAsJsonAsync<User, bool>("Users", usr);
Assert.True(resp);
// delete
usr.Delete(usr.Retrieves().Where(u => u.UserName == usr.UserName).Select(u => u.Id));
_host.Logout();
_host.Login();
}
[Fact]
public async void Category_Get_Ok()
{
var cates = await _client.GetAsJsonAsync<IEnumerable<string>>("Category");
Assert.NotEmpty(cates);
}
[Fact]
public async void Dicts_Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "Dicts?sort=Category&order=asc&offset=0&limit=20&category=%E8%8F%9C%E5%8D%95&name=%E7%B3%BB%E7%BB%9F%E8%8F%9C%E5%8D%95&define=0&_=1547608210979";
var qd = await _client.GetAsJsonAsync<QueryData<BootstrapDict>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void Dicts_PostAndDelete_Ok()
{
var dict = new Dict();
dict.Delete(new Dict().RetrieveDicts().Where(d => d.Category == "UnitTest-Category").Select(d => d.Id));
var ret = await _client.PostAsJsonAsync<BootstrapDict, bool>("Dicts", new BootstrapDict() { Name = "UnitTest-Dict", Category = "UnitTest-Category", Code = "0", Define = 0 });
Assert.True(ret);
var ids = dict.RetrieveDicts().Where(d => d.Name == "UnitTest-Dict").Select(d => d.Id);
Assert.True(await _client.DeleteAsJsonAsync<IEnumerable<string>, bool>("Dicts", ids));
}
[Fact]
public async void Exceptions_Get_Ok()
{
// insert exception
var excep = new Exceptions();
Assert.True(excep.Log(new Exception("UnitTest"), null));
// 菜单 系统菜单 系统使用条件
var query = "Exceptions?sort=LogTime&order=desc&offset=0&limit=20&StartTime=&EndTime=&_=1547610349796";
var qd = await _client.GetAsJsonAsync<QueryData<BootstrapDict>>(query);
Assert.NotEmpty(qd.rows);
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
[Fact]
public async void Exceptions_Post_Ok()
{
var files = await _client.PostAsJsonAsync<string, IEnumerable<string>>("Exceptions", string.Empty);
Assert.NotNull(files);
var fileName = files.FirstOrDefault();
if (!string.IsNullOrEmpty(fileName))
{
var resp = await _client.PutAsJsonAsync<ExceptionFileQuery, string>("Exceptions", new ExceptionFileQuery() { FileName = fileName });
Assert.NotNull(resp);
}
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
[Fact]
public async void Groups_Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "Groups?sort=GroupName&order=asc&offset=0&limit=20&groupName=Admin&description=%E7%B3%BB%E7%BB%9F%E9%BB%98%E8%AE%A4%E7%BB%84&_=1547614230481";
var qd = await _client.GetAsJsonAsync<QueryData<Group>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void Groups_GetById_Ok()
{
var id = new Group().Retrieves().Where(gp => gp.GroupName == "Admin").First().Id;
var g = await _client.GetAsJsonAsync<Group>($"Groups/{id}");
Assert.Equal("Admin", g.GroupName);
}
[Fact]
public async void Groups_PostAndDelete_Ok()
{
var ret = await _client.PostAsJsonAsync<Group, bool>("Groups", new Group() { GroupName = "UnitTest-Group", Description = "UnitTest-Desc" });
Assert.True(ret);
var ids = new Group().Retrieves().Where(d => d.GroupName == "UnitTest-Group").Select(d => d.Id);
Assert.True(await _client.DeleteAsJsonAsync<IEnumerable<string>, bool>("Groups", ids));
}
[Fact]
public async void Groups_PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await _client.PostAsJsonAsync<string, IEnumerable<Group>>($"Groups/{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await _client.PostAsJsonAsync<string, IEnumerable<Group>>($"Groups/{rid}?type=role", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void Groups_PutById_Ok()
{
var ids = new Group().Retrieves().Select(g => g.Id);
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Groups/{uid}?type=user", ids);
Assert.True(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Groups/{rid}?type=role", ids);
Assert.True(ret);
}
[Fact]
public async void Interface_RetrieveDicts_Ok()
{
var ret = await _client.PostAsJsonAsync<string, IEnumerable<BootstrapDict>>("Interface/RetrieveDicts", "");
Assert.NotEmpty(ret);
}
[Fact]
public async void Interface_RetrieveRolesByUrl_Ok()
{
var ret = await _client.PostAsJsonAsync<string, IEnumerable<string>>("Interface/RetrieveRolesByUrl", "~/Admin/Index");
Assert.NotEmpty(ret);
}
[Fact]
public async void Interface_RetrieveRolesByUserName_Ok()
{
var ret = await _client.PostAsJsonAsync<string, IEnumerable<string>>("Interface/RetrieveRolesByUserName", "Admin");
Assert.NotEmpty(ret);
}
[Fact]
public async void Interface_RetrieveUserByUserName_Ok()
{
var ret = await _client.PostAsJsonAsync<string, BootstrapUser>("Interface/RetrieveUserByUserName", "Admin");
Assert.Equal("Admin", ret.UserName);
}
[Fact]
public async void Interface_RetrieveAppMenus_Ok()
{
var ret = await _client.PostAsJsonAsync<AppMenuOption, IEnumerable<BootstrapMenu>>("Interface/RetrieveAppMenus", new AppMenuOption() { AppId = "0", UserName = "Admin", Url = "~/Admin/Index" });
Assert.NotEmpty(ret);
}
[Fact]
public async void Login_Login_Ok()
{
var resq = await _client.PostAsJsonAsync("Login", new { userName = "Admin", password = "123789" });
var _token = await resq.Content.ReadAsStringAsync();
Assert.NotNull(_token);
}
[Fact]
public async void Login_Option_Ok()
{
var req = new HttpRequestMessage(HttpMethod.Options, "Login");
var resp = await _client.SendAsync(req);
}
[Fact]
public async void Logs_Get_Ok()
{
var log = new Log() { CRUD = "UnitTest", ClientAgent = "UnitTest", ClientIp = "::1", RequestUrl = "~/UnitTest", UserName = "UnitTest" };
log.Save(log);
// 菜单 系统菜单 系统使用条件
var query = "Logs?sort=LogTime&order=desc&offset=0&limit=20&operateType=&OperateTimeStart=&OperateTimeEnd=&_=1547617573596";
var qd = await _client.GetAsJsonAsync<QueryData<Log>>(query);
Assert.NotEmpty(qd.rows);
// clean
DbManager.Create().Execute("Delete from Logs where CRUD = @0", log.CRUD);
}
[Fact]
public async void Logs_Post_Ok()
{
_client.DefaultRequestHeaders.Add("user-agent", "UnitTest");
var resp = await _client.PostAsJsonAsync<Log, bool>("Logs", new Log() { CRUD = "UnitTest", RequestUrl = "~/UnitTest" });
Assert.True(resp);
// clean
DbManager.Create().Execute("delete from Logs where CRUD = @0", "UnitTest");
}
[Fact]
public async void Menus_Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "Menus?sort=Order&order=asc&offset=0&limit=20&parentName=&name=%E5%90%8E%E5%8F%B0%E7%AE%A1%E7%90%86&category=0&isresource=0&_=1547619684999";
var qd = await _client.GetAsJsonAsync<QueryData<object>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void Menus_PostAndDelete_Ok()
{
var ret = await _client.PostAsJsonAsync<BootstrapMenu, bool>("Menus", new BootstrapMenu() { Name = "UnitTest-Menu", Application = "0", Category = "0", ParentId = "0", Url = "#", Target = "_self", IsResource = 0 });
Assert.True(ret);
var menu = new Menu();
var ids = menu.RetrieveAllMenus("Admin").Where(d => d.Name == "UnitTest-Menu").Select(d => d.Id);
Assert.True(await _client.DeleteAsJsonAsync<IEnumerable<string>, bool>("Menus", ids));
}
[Fact]
public async void Menus_PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Menus/{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Menus/{rid}?type=role", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void Menus_PutById_Ok()
{
var ids = new Menu().RetrieveAllMenus("Admin").Select(g => g.Id);
var rid = new Role().Retrieves().Where(r => r.RoleName == "Administrators").First().Id;
var ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Menus/{rid}", ids);
Assert.True(ret);
}
[Theory]
[InlineData("inbox")]
[InlineData("sendmail")]
[InlineData("mark")]
[InlineData("trash")]
public async void Messages_Get_Ok(string action)
{
var resp = await _client.GetAsJsonAsync<IEnumerable<Message>>($"Messages/{action}");
Assert.NotNull(resp);
}
[Fact]
public async void Messages_GetCount_Ok()
{
var resp = await _client.GetAsJsonAsync<MessageCountModel>("Messages");
Assert.NotNull(resp);
}
[Fact]
public async void New_Get_Ok()
{
var nusr = InsertNewUser();
var resp = await _client.GetAsJsonAsync<IEnumerable<object>>("New");
Assert.NotEmpty(resp);
// 删除新用户
DeleteUnitTestUser();
}
[Fact]
public async void New_Put_Ok()
{
DeleteUnitTestUser();
var nusr = InsertNewUser();
// Approve
nusr.UserStatus = UserStates.ApproveUser;
var resp = await _client.PutAsJsonAsync<User, bool>("New", nusr);
Assert.True(resp);
// 删除新用户
nusr.Delete(new string[] { nusr.Id });
// Reject
nusr = InsertNewUser();
nusr.UserStatus = UserStates.RejectUser;
resp = await _client.PutAsJsonAsync<User, bool>("New", nusr);
Assert.True(resp);
// 删除新用户
DeleteUnitTestUser();
}
private User InsertNewUser()
{
// 插入新用户
var nusr = new User() { UserName = "UnitTest-Register", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
Assert.True(new User().Save(nusr));
return nusr;
}
private void DeleteUnitTestUser()
{
var ids = new User().RetrieveNewUsers().Where(u => u.UserName == "UnitTest-Register").Select(u => u.Id);
new User().Delete(ids);
}
[Fact]
public async void Notifications_Get_Ok()
{
var resp = await _client.GetAsJsonAsync<object>("Notifications");
Assert.NotNull(resp);
}
[Fact]
public async void Register_Get_Ok()
{
var resp = await _client.GetAsJsonAsync<bool>("Register?userName=Admin");
Assert.False(resp);
}
[Fact]
public async void Register_Post_Ok()
{
// register new user
var nusr = new User() { UserName = "UnitTest-RegisterController", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
var resp = await _client.PostAsJsonAsync<User, bool>("Register", nusr);
Assert.True(resp);
nusr.Delete(nusr.RetrieveNewUsers().Where(u => u.UserName == nusr.UserName).Select(u => u.Id));
}
[Fact]
public async void Roles_Get_Ok()
{
// 菜单 系统菜单 系统使用条件
var query = "Roles?sort=RoleName&order=asc&offset=0&limit=20&roleName=Administrators&description=%E7%B3%BB%E7%BB%9F%E7%AE%A1%E7%90%86%E5%91%98&_=1547625202230";
var qd = await _client.GetAsJsonAsync<QueryData<Group>>(query);
Assert.Single(qd.rows);
}
[Fact]
public async void Roles_PostAndDelete_Ok()
{
var ret = await _client.PostAsJsonAsync<Role, bool>("Roles", new Role() { RoleName = "UnitTest-Role", Description = "UnitTest-Desc" });
Assert.True(ret);
var ids = new Role().Retrieves().Where(d => d.RoleName == "UnitTest-Role").Select(d => d.Id);
Assert.True(await _client.DeleteAsJsonAsync<IEnumerable<string>, bool>("Roles", ids));
}
[Fact]
public async void Roles_PostById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var gid = new Group().Retrieves().Where(g => g.GroupName == "Admin").First().Id;
var mid = new Menu().RetrieveAllMenus("Admin").Where(m => m.Url == "~/Admin/Index").First().Id;
var ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Roles/{uid}?type=user", string.Empty);
Assert.NotEmpty(ret);
ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Roles/{gid}?type=group", string.Empty);
Assert.NotEmpty(ret);
ret = await _client.PostAsJsonAsync<string, IEnumerable<object>>($"Roles/{mid}?type=menu", string.Empty);
Assert.NotEmpty(ret);
}
[Fact]
public async void Roles_PutById_Ok()
{
var uid = new User().Retrieves().Where(u => u.UserName == "Admin").First().Id;
var gid = new Group().Retrieves().Where(g => g.GroupName == "Admin").First().Id;
var mid = new Menu().RetrieveAllMenus("Admin").Where(m => m.Url == "~/Admin/Index").First().Id;
var ids = new Role().Retrieves().Select(r => r.Id);
var ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Roles/{uid}?type=user", ids);
Assert.True(ret);
ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Roles/{gid}?type=group", ids);
Assert.True(ret);
ret = await _client.PutAsJsonAsync<IEnumerable<string>, bool>($"Roles/{mid}?type=menu", ids);
Assert.True(ret);
}
[Fact]
public async void Settings_Get_Ok()
{
var resp = await _client.GetAsJsonAsync<IEnumerable<ICacheCorsItem>>("Settings");
Assert.NotNull(resp);
}
[Fact]
public async void Settings_Post_Ok()
{
var dict = new Dict();
var dicts = dict.RetrieveDicts();
var ids = dicts.Where(d => d.Category == "UnitTest-Settings").Select(d => d.Id);
dict.Delete(ids);
Assert.True(dict.Save(new Dict() { Category = "UnitTest-Settings", Name = "UnitTest", Code = "0", Define = 0 }));
// 获得原来值
var resp = await _client.PostAsJsonAsync<BootstrapDict, bool>("Settings", new Dict() { Category = "UnitTest-Settings", Name = "UnitTest", Code = "UnitTest" });
Assert.True(resp);
var code = dict.RetrieveDicts().FirstOrDefault(d => d.Category == "UnitTest-Settings").Code;
Assert.Equal("UnitTest", code);
// Delete
ids = dict.RetrieveDicts().Where(d => d.Category == "UnitTest-Settings").Select(d => d.Id);
dict.Delete(ids);
}
[Fact]
public async void Tasks_Get_Ok()
{
var resp = await _client.GetAsJsonAsync<IEnumerable<Task>>("Tasks");
Assert.NotNull(resp);
}
}
}

View File

@ -1,85 +0,0 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Mvc.Testing.Handlers;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using UnitTest;
namespace Bootstrap.Admin
{
/// <summary>
///
/// </summary>
public class BAWebHost : WebApplicationFactory<Startup>
{
/// <summary>
///
/// </summary>
static BAWebHost()
{
// Copy license
TestHelper.CopyLicense();
}
public BAWebHost()
{
Login();
}
public new HttpClient CreateClient() => CreateClient("http://localhost/api/");
public HttpClient CreateClient(string baseAddress)
{
var client = CreateDefaultClient(new RedirectHandler(7), new CookieContainerHandler(cookie));
client.BaseAddress = new Uri(baseAddress);
return client;
}
private CookieContainer cookie = new CookieContainer();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
TestHelper.ConfigureWebHost(builder);
}
public string Login(string userName = "Admin", string password = "123789")
{
if (cookie.Count == 2) return "";
var client = CreateClient("http://localhost/Account/Login");
var r = client.GetAsync("");
r.Wait();
var tv = r.Result.Content.ReadAsStringAsync();
tv.Wait();
var tokenTag = "<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"";
var view = tv.Result;
var index = view.IndexOf(tokenTag);
view = view.Substring(index + tokenTag.Length);
index = view.IndexOf("\" /></form>");
var antiToken = view.Substring(0, index);
var content = new MultipartFormDataContent();
content.Add(new StringContent(userName), "userName");
content.Add(new StringContent(password), "password");
content.Add(new StringContent("true"), "remember");
content.Add(new StringContent(antiToken), "__RequestVerificationToken");
var resp = client.PostAsync("", content);
resp.Wait();
tv = resp.Result.Content.ReadAsStringAsync();
tv.Wait();
return tv.Result;
}
public void Logout()
{
cookie = new CookieContainer();
}
}
}

View File

@ -0,0 +1,24 @@
using System.Net.Http;
using Xunit;
namespace Bootstrap.Admin
{
[Collection("BootstrapAdminTestContext")]
public class ControllerTest
{
protected HttpClient Client { get; set; }
protected BAWebHost Host { get; set; }
/// <summary>
///
/// </summary>
/// <param name="factory"></param>
/// <param name="baseAddress"></param>
public ControllerTest(BAWebHost factory, string baseAddress = "api")
{
Host = factory;
Client = factory.CreateClient(baseAddress);
}
}
}

View File

@ -0,0 +1,47 @@
using Xunit;
namespace Bootstrap.Admin.Controllers
{
public class AccountTest : ControllerTest
{
public AccountTest(BAWebHost factory) : base(factory, "Account") { }
[Fact]
public async void Login_Fail()
{
var client = Host.CreateClient();
var r = await client.GetAsync("/Account/Login");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("登 陆", content);
}
[Fact]
public async void Login_Admin()
{
var resp = await Client.GetAsync("Login");
var context = await resp.Content.ReadAsStringAsync();
Assert.Contains("注销", context);
}
[Fact]
public async void Logout_Ok()
{
var client = Host.CreateClient();
var r = await client.GetAsync("/Account/Logout");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("登 陆", content);
}
[Fact]
public async void AccessDenied_Ok()
{
// logout
var r = await Client.GetAsync("AccessDenied");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("您无权访问本页面请联系网站管理员授权后再查看", content);
}
}
}

View File

@ -0,0 +1,43 @@
using System.Net;
using Xunit;
namespace Bootstrap.Admin.Controllers
{
public class AdminTest : ControllerTest
{
public AdminTest(BAWebHost factory) : base(factory, "Admin") { }
[Theory]
[InlineData("Index", "欢迎使用后台管理")]
[InlineData("Users", "用户管理")]
[InlineData("Groups", "部门管理")]
[InlineData("Dicts", "字典表维护")]
[InlineData("Roles", "角色管理")]
[InlineData("Menus", "菜单管理")]
[InlineData("Logs", "系统日志")]
[InlineData("FAIcon", "图标集")]
[InlineData("IconView", "图标分类")]
[InlineData("Settings", "网站设置")]
[InlineData("Notifications", "通知管理")]
[InlineData("Profiles", "个人中心")]
[InlineData("Exceptions", "程序异常")]
[InlineData("Messages", "站内消息")]
[InlineData("Tasks", "任务管理")]
[InlineData("Mobile", "客户端测试")]
public async void View_Ok(string view, string text)
{
var r = await Client.GetAsync(view);
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains(text, content);
}
[Fact]
public async void Admin_Error_Ok()
{
var r = await Client.GetAsync("Error");
Assert.False(r.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.InternalServerError, r.StatusCode);
}
}
}

View File

@ -0,0 +1,32 @@
using Xunit;
namespace Bootstrap.Admin.Controllers
{
public class HomeTest : ControllerTest
{
public HomeTest(BAWebHost factory) : base(factory, "Home/Error") { }
[Theory]
[InlineData(0)]
[InlineData(404)]
[InlineData(500)]
public async void Error_Ok(int errorCode)
{
var r = await Client.GetAsync($"{errorCode}");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
if (errorCode == 0)
{
Assert.Contains("未处理服务器内部错误", content);
}
else if (errorCode == 404)
{
Assert.Contains("请求资源未找到", content);
}
else
{
Assert.Contains("服务器内部错误", content);
}
}
}
}

View File

@ -1,116 +0,0 @@
using System.Net;
using System.Net.Http;
using Xunit;
namespace Bootstrap.Admin.Controllers
{
public class ControllersTest : IClassFixture<BAWebHost>
{
private HttpClient _client;
private BAWebHost _host;
public ControllersTest(BAWebHost factory)
{
_host = factory;
_client = factory.CreateClient();
}
[Fact]
public async void Login_Fail()
{
// login
_host.Logout();
_client = _host.CreateClient();
var r = await _client.GetAsync("/Account/Login");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("登 陆", content);
}
[Fact]
public void Login_Admin()
{
// login
_host.Logout();
var resp = _host.Login();
Assert.Contains("注销", resp);
}
[Fact]
public async void Logout_Ok()
{
// logout
var r = await _client.GetAsync("/Account/Logout");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("登 陆", content);
}
[Fact]
public async void AccessDenied_Ok()
{
// logout
var r = await _client.GetAsync("/Account/AccessDenied");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains("您无权访问本页面请联系网站管理员授权后再查看", content);
}
[Theory]
[InlineData(0)]
[InlineData(404)]
[InlineData(500)]
public async void Home_Error_Ok(int errorCode)
{
var r = await _client.GetAsync($"/Home/Error/{errorCode}");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
if (errorCode == 0)
{
Assert.Contains("未处理服务器内部错误", content);
}
else if (errorCode == 404)
{
Assert.Contains("请求资源未找到", content);
}
else
{
Assert.Contains("服务器内部错误", content);
}
}
[Theory]
[InlineData("Index", "欢迎使用后台管理")]
[InlineData("Users", "用户管理")]
[InlineData("Groups", "部门管理")]
[InlineData("Dicts", "字典表维护")]
[InlineData("Roles", "角色管理")]
[InlineData("Menus", "菜单管理")]
[InlineData("Logs", "系统日志")]
[InlineData("FAIcon", "图标集")]
[InlineData("IconView", "图标分类")]
[InlineData("Settings", "网站设置")]
[InlineData("Notifications", "通知管理")]
[InlineData("Profiles", "个人中心")]
[InlineData("Exceptions", "程序异常")]
[InlineData("Messages", "站内消息")]
[InlineData("Tasks", "任务管理")]
[InlineData("Mobile", "客户端测试")]
public async void View_Ok(string view, string text)
{
var r = await _client.GetAsync($"/Admin/{view}");
Assert.True(r.IsSuccessStatusCode);
var content = await r.Content.ReadAsStringAsync();
Assert.Contains(text, content);
}
[Fact]
public async void Admin_Error_Ok()
{
var r = await _client.GetAsync("/Admin/Error");
Assert.False(r.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.InternalServerError, r.StatusCode);
}
}
}

View File

@ -7,6 +7,13 @@ namespace Bootstrap.Admin
{
public static class HttpClientExtensions
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="client"></param>
/// <param name="requestUri"></param>
/// <returns></returns>
public static async Task<T> GetAsJsonAsync<T>(this HttpClient client, string requestUri = null)
{
var resp = await client.GetAsync(requestUri);
@ -14,6 +21,15 @@ namespace Bootstrap.Admin
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="requestUri"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> PostAsJsonAsync<TValue, TRet>(this HttpClient client, string requestUri, TValue t)
{
var resp = await client.PostAsJsonAsync(requestUri, t);
@ -21,6 +37,25 @@ namespace Bootstrap.Admin
return JsonConvert.DeserializeObject<TRet>(json);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> PostAsJsonAsync<TValue, TRet>(this HttpClient client, TValue t) => await PostAsJsonAsync<TValue, TRet>(client, string.Empty, t);
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="requestUri"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> DeleteAsJsonAsync<TValue, TRet>(this HttpClient client, string requestUri, TValue t)
{
var req = new HttpRequestMessage(HttpMethod.Delete, requestUri);
@ -32,11 +67,60 @@ namespace Bootstrap.Admin
return JsonConvert.DeserializeObject<TRet>(json);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> DeleteAsJsonAsync<TValue, TRet>(this HttpClient client, TValue t) => await DeleteAsJsonAsync<TValue, TRet>(client, string.Empty, t);
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="requestUri"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> PutAsJsonAsync<TValue, TRet>(this HttpClient client, string requestUri, TValue t)
{
var resp = await client.PutAsJsonAsync(requestUri, t);
var json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TRet>(json);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TRet"></typeparam>
/// <param name="client"></param>
/// <param name="t"></param>
/// <returns></returns>
public static async Task<TRet> PutAsJsonAsync<TValue, TRet>(this HttpClient client, TValue t) => await PutAsJsonAsync<TValue, TRet>(client, string.Empty, t);
public static async Task LoginAsync(this HttpClient client, string userName = "Admin", string password = "123789")
{
var r = await client.GetAsync("/Account/Login");
var view = await r.Content.ReadAsStringAsync();
var tokenTag = "<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"";
var index = view.IndexOf(tokenTag);
view = view.Substring(index + tokenTag.Length);
index = view.IndexOf("\" /></form>");
var antiToken = view.Substring(0, index);
var content = new MultipartFormDataContent
{
{ new StringContent(userName), "userName" },
{ new StringContent(password), "password" },
{ new StringContent("true"), "remember" },
{ new StringContent(antiToken), "__RequestVerificationToken" }
};
await client.PostAsync("/Account/Login", content);
}
}
}

View File

@ -1,19 +0,0 @@
using Microsoft.Extensions.DependencyInjection;
using UnitTest;
namespace Bootstrap.DataAccess
{
public class BootstrapAdminStartup
{
static BootstrapAdminStartup()
{
var config = TestHelper.CreateConfiguraton();
var sc = new ServiceCollection();
sc.AddSingleton(config);
sc.AddConfigurationManager(config);
sc.AddCacheManager(config);
sc.AddDbAdapter();
}
}
}

View File

@ -3,7 +3,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class DictsTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class DictsTest
{
[Fact]
public void SaveAndDelete_Ok()

View File

@ -4,7 +4,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class ExceptionsTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class ExceptionsTest
{
[Fact]
public void Log_Ok()

View File

@ -3,7 +3,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class GroupsTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class GroupsTest
{
[Fact]
public void Retrieves_Ok()

View File

@ -2,7 +2,8 @@
namespace Bootstrap.DataAccess
{
public class LogsTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class LogsTest
{
[Fact]
public void Save_Ok()

View File

@ -3,7 +3,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class MenusTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class MenusTest
{
[Fact]
public void Save_Ok()

View File

@ -2,7 +2,8 @@
namespace Bootstrap.DataAccess
{
public class MessagesTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class MessagesTest
{
[Fact]
public void RetrieveHeaders_Ok()

View File

@ -3,7 +3,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class RolesTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class RolesTest
{
[Fact]
public void SaveRolesByUserId_Ok()

View File

@ -3,7 +3,8 @@ using Xunit;
namespace Bootstrap.DataAccess
{
public class TasksTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class TasksTest
{
[Fact]
public void Retrieves_Ok()

View File

@ -7,7 +7,8 @@ namespace Bootstrap.DataAccess
/// <summary>
///
/// </summary>
public class UsersTest : IClassFixture<BootstrapAdminStartup>
[Collection("BootstrapAdminTestContext")]
public class UsersTest
{
/// <summary>
///

View File

@ -44,18 +44,10 @@ namespace UnitTest
if (!File.Exists(targetFile)) File.Copy(licFile, targetFile, true);
#if SQLite
CopySQLiteDBFile();
#endif
}
/// <summary>
///
/// </summary>
public static void CopySQLiteDBFile()
{
var dbPath = RetrievePath($"UnitTest{Path.DirectorySeparatorChar}DB{Path.DirectorySeparatorChar}UnitTest.db");
var dbFile = Path.Combine(AppContext.BaseDirectory, "UnitTest.db");
if (!File.Exists(dbFile)) File.Copy(dbPath, dbFile);
#endif
}
private const string SqlConnectionString = "Data Source=.;Initial Catalog=UnitTest;User ID=sa;Password=sa";
@ -96,46 +88,5 @@ namespace UnitTest
}));
#endif
}
public static IConfiguration CreateConfiguraton()
{
var config = new ConfigurationBuilder().AddInMemoryCollection(new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("ConnectionStrings:ba", SqlConnectionString),
new KeyValuePair<string, string>("DB:0:Enabled", "false"),
new KeyValuePair<string, string>("DB:1:Enabled", "false"),
new KeyValuePair<string, string>("DB:1:ProviderName", "SQLite"),
new KeyValuePair<string, string>("DB:1:ConnectionStrings:ba", SQLiteConnectionString),
new KeyValuePair<string, string>("DB:2:Enabled", "false"),
new KeyValuePair<string, string>("DB:2:ProviderName", "MySql"),
new KeyValuePair<string, string>("DB:2:ConnectionStrings:ba", MySqlConnectionString),
new KeyValuePair<string, string>("DB:3:Enabled", "false"),
new KeyValuePair<string, string>("DB:3:ProviderName", "NPgsql"),
new KeyValuePair<string, string>("DB:3:ConnectionStrings:ba", NpgSqlConnectionString),
new KeyValuePair<string, string>("LongbowCache:Enabled", "false")
});
#if SQLite
config.AddInMemoryCollection(new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("DB:1:Enabled", "true")
});
CopySQLiteDBFile();
#endif
#if MySQL
config.AddInMemoryCollection(new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("DB:2:Enabled", "true")
});
#endif
#if Npgsql
config.AddInMemoryCollection(new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>("DB:3:Enabled", "true")
});
#endif
return config.Build();
}
}
}