refactor(UnitTest): 重构单元测试

This commit is contained in:
Argo Zhang 2019-06-01 16:57:33 +08:00
parent 9959d7cfbc
commit 8e4ef25cde
42 changed files with 518 additions and 198 deletions

View File

@ -32,6 +32,9 @@ namespace Bootstrap.DataAccess.MongoDB
/// <returns></returns>
public override bool SaveByRoleId(string roleId, IEnumerable<string> appIds)
{
if (string.IsNullOrEmpty(roleId)) throw new ArgumentNullException(nameof(roleId));
if (appIds == null) appIds = new string[0];
var ret = DbManager.Roles.UpdateOne(md => md.Id == roleId, Builders<Role>.Update.Set(md => md.Apps, appIds));
return true;
}

View File

@ -195,13 +195,6 @@ namespace Bootstrap.DataAccess.MongoDB
{
BsonSerializer.RegisterSerializer(DateTimeSerializer.LocalInstance);
if (!BsonClassMap.IsClassMapRegistered(typeof(Dict)))
{
BsonClassMap.RegisterClassMap<Dict>(md =>
{
md.AutoMap();
});
}
if (!BsonClassMap.IsClassMapRegistered(typeof(BootstrapDict)))
{
BsonClassMap.RegisterClassMap<BootstrapDict>(md =>
@ -209,7 +202,6 @@ namespace Bootstrap.DataAccess.MongoDB
md.AutoMap();
md.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
md.IdMemberMap.SetIgnoreIfDefault(true);
md.AddKnownType(typeof(Dict));
});
}
if (!BsonClassMap.IsClassMapRegistered(typeof(DataAccess.User)))

View File

@ -1,4 +1,4 @@
using Longbow.Web.Mvc;
using Longbow.Web.Mvc;
using MongoDB.Driver;
using PetaPoco;
using System;
@ -93,7 +93,6 @@ namespace Bootstrap.DataAccess.MongoDB
/// <returns></returns>
public override bool Save(DataAccess.Trace p)
{
p.Id = null;
DbManager.Traces.InsertOne(p);
ClearTraces();
return true;

View File

@ -115,6 +115,7 @@ namespace Bootstrap.DataAccess.MongoDB
Description = user.Description,
IsReset = 0
});
user.Id = DbManager.Users.Find(r => r.UserName == user.UserName).FirstOrDefault().Id;
return true;
}

View File

@ -56,7 +56,10 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public virtual bool SaveByRoleId(string roleId, IEnumerable<string> appIds)
{
if (string.IsNullOrEmpty(roleId)) throw new ArgumentNullException(nameof(roleId));
bool ret = false;
if (appIds == null) appIds = new string[0];
var db = DbManager.Create();
try
{

View File

@ -1,4 +1,4 @@
using Bootstrap.Security;
using Bootstrap.Security;
using Bootstrap.Security.DataAccess;
using Longbow;
using PetaPoco;
@ -107,11 +107,7 @@ namespace Bootstrap.DataAccess
if (appCode != "0")
{
var appUrl = dicts.FirstOrDefault(d => d.Name.Equals(appCode, StringComparison.OrdinalIgnoreCase) && d.Category == "应用首页" && d.Define == 0)?.Code;
if (!string.IsNullOrEmpty(appUrl))
{
url = appUrl;
return url;
}
if (!string.IsNullOrEmpty(appUrl)) return appUrl;
}
var defaultUrl = dicts.FirstOrDefault(d => d.Name == "前台首页" && d.Category == "网站设置" && d.Define == 0)?.Code;
if (!string.IsNullOrEmpty(defaultUrl)) url = defaultUrl;

View File

@ -55,7 +55,7 @@ namespace Bootstrap.DataAccess
db.BeginTransaction();
db.Execute($"delete from UserGroup where GroupID in ({ids})");
db.Execute($"delete from RoleGroup where GroupID in ({ids})");
db.Execute($"delete from {db.Provider.EscapeSqlIdentifier("Groups")} where ID in ({ids})");
db.Delete<Group>($"where ID in ({ids})");
db.CompleteTransaction();
ret = true;
}

View File

@ -41,14 +41,10 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Delete(IEnumerable<string> value)
{
if (RetrieveSystemModel())
{
// 禁止删除系统数据与测试平台数据
var systemDicts = RetrieveProtectedDicts();
value = value.Where(v => !systemDicts.Any(d => d.Id == v));
if (!value.Any()) return true;
}
if (!value.Any()) return true;
// 禁止删除系统数据与测试平台数据
if (RetrieveSystemModel() && RetrieveProtectedDicts().Any(d => value.Any(v => v == d.Id))) return true;
var ret = DbContextManager.Create<Dict>().Delete(value);
CacheCleanUtility.ClearCache(dictIds: value);
return ret;
@ -61,7 +57,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Save(BootstrapDict p)
{
if (RetrieveSystemModel() && RetrieveProtectedDicts().Any(m => m.Id == p.Id)) return true;
if (RetrieveSystemModel() && !string.IsNullOrEmpty(p.Id) && RetrieveProtectedDicts().Any(m => m.Id == p.Id)) return true;
if (p.Id == string.Empty) p.Id = null;
var ret = DbContextManager.Create<Dict>().Save(p);

View File

@ -31,20 +31,8 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Save(BootstrapMenu p)
{
if (DictHelper.RetrieveSystemModel())
{
if (p.Id.IsNullOrEmpty())
{
if (p.Category == "0") p.Category = "1";
}
else
{
if (RetrieveAllMenus("Admin").Where(m => m.Category == "0").Any(m => m.Id == p.Id))
{
return true;
}
}
}
if (DictHelper.RetrieveSystemModel() && !string.IsNullOrEmpty(p.Id) && RetrieveAllMenus("Admin").Where(m => m.Category == "0" || m.Application == "2").Any(m => m.Id == p.Id)) return true;
if (p.Id == string.Empty) p.Id = null;
var ret = DbContextManager.Create<Menu>().Save(p);
if (ret) CacheCleanUtility.ClearCache(menuIds: string.IsNullOrEmpty(p.Id) ? new List<string>() : new List<string>() { p.Id });
@ -61,8 +49,7 @@ namespace Bootstrap.DataAccess
if (DictHelper.RetrieveSystemModel())
{
// 不允许删除系统菜单与前台演示系统的默认菜单
var menuNames = new string[] { "首页", "测试页面", "关于", "返回码云" };
var systemMenus = RetrieveAllMenus("Admin").Where(m => m.Category == "0" || menuNames.Any(n => n.Equals(m.Name, StringComparison.OrdinalIgnoreCase)));
var systemMenus = RetrieveAllMenus("Admin").Where(m => m.Category == "0" || m.Application == "2");
value = value.Where(v => !systemMenus.Any(m => m.Id == v));
if (!value.Any()) return true;
}

View File

@ -44,6 +44,10 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static IEnumerable<Message> Retrieves(string userName) => CacheManager.GetOrAdd(RetrieveMessageDataKey, key => DbContextManager.Create<Message>().RetrieveHeaders(userName).OrderByDescending(n => n.SendTime));
public static bool Save(Message msg) => DbContextManager.Create<Message>().Save(msg);
public static bool Save(Message msg)
{
if (string.IsNullOrEmpty(msg.Id)) msg.Id = null;
return DbContextManager.Create<Message>().Save(msg);
}
}
}

View File

@ -25,6 +25,10 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public static bool Save(Task task) => DbContextManager.Create<Task>().Save(task);
public static bool Save(Task task)
{
if (string.IsNullOrEmpty(task.Id)) task.Id = null;
return DbContextManager.Create<Task>().Save(task);
}
}
}

View File

@ -25,6 +25,7 @@ namespace Bootstrap.DataAccess
v.DisplayName = user.DisplayName;
DbContextManager.Create<Trace>().Save(new Trace
{
Id = null,
Ip = v.Ip,
RequestUrl = v.RequestUrl,
LogTime = v.LastAccessTime,

View File

@ -1,4 +1,4 @@
using Bootstrap.Security;
using Bootstrap.Security;
using Longbow.Cache;
using Longbow.Data;
using System;
@ -105,12 +105,8 @@ namespace Bootstrap.DataAccess
public static bool Save(User user)
{
if (!UserChecker(user)) return false;
if (DictHelper.RetrieveSystemModel() && !string.IsNullOrEmpty(user.Id) && RetrieveConstUsers().Any(u => u.Id == user.Id)) return true;
if (DictHelper.RetrieveSystemModel() && !user.Id.IsNullOrEmpty())
{
var admins = RetrieveConstUsers();
if (admins.Any(v => v.Id == user.Id)) return true;
}
var ret = DbContextManager.Create<User>().Save(user);
if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(user.Id) ? new List<string>() : new List<string>() { user.Id });
return ret;
@ -126,11 +122,8 @@ namespace Bootstrap.DataAccess
public static bool Update(string id, string password, string displayName)
{
if (!UserChecker(new User { Password = password, DisplayName = displayName })) return false;
if (DictHelper.RetrieveSystemModel())
{
var admins = RetrieveConstUsers();
if (admins.Any(v => v.Id == id)) return true;
}
if (DictHelper.RetrieveSystemModel() && RetrieveConstUsers().Any(v => v.Id == id)) return true;
var ret = DbContextManager.Create<User>().Update(id, password, displayName);
if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(id) ? new List<string>() : new List<string>() { id });
return ret;

View File

@ -10,6 +10,7 @@ namespace Bootstrap.DataAccess
/// <summary>
///
/// </summary>
[TableName("Navigations")]
public class Menu : BootstrapMenu
{
/// <summary>
@ -26,7 +27,7 @@ namespace Bootstrap.DataAccess
var ids = string.Join(",", value);
db.BeginTransaction();
db.Execute($"delete from NavigationRole where NavigationID in ({ids})");
db.Execute($"delete from Navigations where ID in ({ids})");
db.Delete<Menu>($"where ID in ({ids})");
db.CompleteTransaction();
ret = true;
}

View File

@ -96,7 +96,7 @@ namespace Bootstrap.DataAccess
var db = DbManager.Create();
var t = db.Provider.EscapeSqlIdentifier("To");
var f = db.Provider.EscapeSqlIdentifier("From");
return db.Fetch<Message>($"select m.*, d.Name, u.DisplayName from Messages m left join Dicts d on m.Label = d.Code and d.Category = @Category and d.Define = 0 inner join Users u on m.{f} = u.UserName where {t} = @UserName or {f} = @UserName order by SendTime desc", new { UserName = userName, Category = "消息标签" });
return db.Fetch<Message>($"select m.*, d.Name, u.DisplayName from Messages m left join Dicts d on m.Label = d.Code and d.Category = @0 and d.Define = 0 inner join Users u on m.{f} = u.UserName where {t} = @1 or {f} = @1 order by SendTime desc", "消息标签", userName);
}
/// <summary>
@ -168,6 +168,8 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public virtual bool Save(Message msg)
{
var db = DbManager.Create();
db.Save(msg);
return true;
}
}

View File

@ -89,7 +89,7 @@ namespace Bootstrap.DataAccess
db.Execute($"delete from UserRole where RoleID in ({ids})");
db.Execute($"delete from RoleGroup where RoleID in ({ids})");
db.Execute($"delete from NavigationRole where RoleID in ({ids})");
db.Execute($"delete from Roles where ID in ({ids})");
db.Delete<Role>($"where ID in ({ids})");
db.CompleteTransaction();
ret = true;
}

View File

@ -147,7 +147,7 @@ namespace Bootstrap.DataAccess
db.BeginTransaction();
db.Execute($"Delete from UserRole where UserID in ({ids})");
db.Execute($"delete from UserGroup where UserID in ({ids})");
db.Execute($"delete from Users where ID in ({ids})");
db.Delete<User>($"where ID in ({ids})");
db.CompleteTransaction();
ret = true;
}
@ -267,7 +267,7 @@ namespace Bootstrap.DataAccess
db.Execute("insert into RejectUsers (UserName, DisplayName, RegisterTime, RejectedBy, RejectedTime, RejectedReason) select UserName, DisplayName, Registertime, @1, @2, @3 from Users where ID = @0", id, rejectBy, DateTime.Now, "未填写");
db.Execute("delete from UserRole where UserId = @0", id);
db.Execute("delete from UserGroup where UserId = @0", id);
db.Execute("delete from users where ID = @0", id);
db.Delete<User>("where Id = @0", id);
db.CompleteTransaction();
ret = true;
}

View File

@ -1,7 +1,7 @@
using Xunit;
using static Bootstrap.Admin.Controllers.Api.AnalyseController;
namespace Bootstrap.Admin.Api.SqlServer
namespace Bootstrap.Admin.Api
{
public class AnalyseTest : ControllerTest
{

View File

@ -26,7 +26,7 @@ namespace Bootstrap.Admin.Api.SqlServer
Assert.NotEmpty(qd.rows);
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
DbManager.Create().Execute("delete from Exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
[Fact]
@ -43,7 +43,7 @@ namespace Bootstrap.Admin.Api.SqlServer
}
// clean
DbManager.Create().Execute("delete from exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
DbManager.Create().Execute("delete from Exceptions where AppDomainName = @0", AppDomain.CurrentDomain.FriendlyName);
}
}
}

View File

@ -1,6 +1,10 @@
using Xunit;
using Bootstrap.Admin.Controllers.Api;
using System;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace Bootstrap.Admin.Api.SqlServer
namespace Bootstrap.Admin.Api
{
public class GiteeTest : ControllerTest
{
@ -33,5 +37,25 @@ namespace Bootstrap.Admin.Api.SqlServer
var cates = await Client.GetAsJsonAsync<object>("Builds");
Assert.NotNull(cates);
}
[Fact]
public void GetJsonAsync_Exception()
{
var t = typeof(GiteeController).GetMethod("GetJsonAsync", BindingFlags.NonPublic | BindingFlags.Static);
t = t.MakeGenericMethod(new Type[] { typeof(string) });
t.Invoke(null, new object[] {
new Func<Task<string>>(() =>
{
throw new TaskCanceledException();
})
});
t.Invoke(null, new object[] {
new Func<Task<string>>(()=> {
throw new Exception();
})
});
}
}
}

View File

@ -1,10 +0,0 @@
using Xunit;
namespace Bootstrap.Admin.Api.MySql
{
[Collection("MySqlContext")]
public class GiteeTest : SqlServer.GiteeTest
{
public GiteeTest(MySqlBAWebHost factory) : base(factory) { }
}
}

View File

@ -2,7 +2,7 @@
using System.Reflection;
using Xunit;
namespace UnitTest.Bootstrap.Admin.Api
namespace Bootstrap.Admin.Api
{
public class OnlineUserTest
{

View File

@ -19,7 +19,7 @@ namespace Bootstrap.Admin.Api.SqlServer
public async void Post_Ok()
{
// register new user
var nusr = new User() { UserName = "UnitTest_RegisterController", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
var nusr = new User() { UserName = "U_Register", DisplayName = "UnitTest", Password = "1", Description = "UnitTest" };
var resp = await Client.PostAsJsonAsync<User, bool>(nusr);
Assert.True(resp);
UserHelper.Delete(nusr.RetrieveNewUsers().Where(u => u.UserName == nusr.UserName).Select(u => u.Id));

View File

@ -1,10 +0,0 @@
using Xunit;
namespace Bootstrap.Admin.Api.SQLite
{
[Collection("SQLiteContext")]
public class GiteeTest : SqlServer.GiteeTest
{
public GiteeTest(SQLiteBAWebHost factory) : base(factory) { }
}
}

View File

@ -2,7 +2,7 @@
using System.Net.Http;
using Xunit;
namespace Bootstrap.Admin.Api.SqlServer
namespace Bootstrap.Admin.Api
{
public class ToolsTest : ControllerTest
{

View File

@ -18,9 +18,13 @@ namespace Bootstrap.Admin.Controllers.SqlServer
DictHelper.Save(dict);
var r = await Client.GetAsync("Login");
// 恢复保护模式
var db = DbManager.Create();
db.Execute("Update Dicts Set Code = @0 Where Id = @1", "0", dict.Id);
Assert.Equal(HttpStatusCode.OK, r.StatusCode);
dict.Code = "0";
DictHelper.Save(dict);
var source = await r.Content.ReadAsStringAsync();
Assert.Contains("演示系统", source);
}
[Fact]

View File

@ -1,4 +1,6 @@
using System.Linq;
using System;
using System.Linq;
using UnitTest;
using Xunit;
namespace Bootstrap.DataAccess.SqlServer
@ -32,8 +34,17 @@ namespace Bootstrap.DataAccess.SqlServer
public void SaveByRoleId_Ok()
{
var rid = RoleHelper.Retrieves().FirstOrDefault(r => r.RoleName == "Administrators").Id;
Assert.True(AppHelper.SaveByRoleId(rid, null));
Assert.True(AppHelper.SaveByRoleId(rid, new string[] { "2" }));
Assert.NotEmpty(AppHelper.RetrievesByRoleId(rid).Where(r => r.Checked == "checked"));
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void SaveByRoleId_ArgumentNullException(string roleId)
{
Assert.ThrowsAny<ArgumentNullException>(() => AppHelper.SaveByRoleId(roleId, null));
}
}
}

View File

@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading;
using Xunit;
namespace Bootstrap.DataAccess
{
[Collection("SQLServerContext")]
public class AuthButtonTest
{
[Fact]
public void User_Ok()
{
Assert.False(MenuHelper.AuthorizateButtons(new FooHttpContext(), "~/Admin/Profiles1", "saveDisplayName"));
Assert.False(MenuHelper.AuthorizateButtons(new FooHttpContext(), "~/Admin/Index", "saveDisplayName"));
}
private class FooHttpContext : HttpContext
{
public override IFeatureCollection Features => throw new NotImplementedException();
public override HttpRequest Request => throw new NotImplementedException();
public override HttpResponse Response => throw new NotImplementedException();
public override ConnectionInfo Connection => throw new NotImplementedException();
public override WebSocketManager WebSockets => throw new NotImplementedException();
public override AuthenticationManager Authentication => throw new NotImplementedException();
public override ClaimsPrincipal User { get; set; } = new ClaimsPrincipal(new System.Security.Principal.GenericIdentity("User"));
public override IDictionary<object, object> Items { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override IServiceProvider RequestServices { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override CancellationToken RequestAborted { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override string TraceIdentifier { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override ISession Session { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override void Abort() => throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Reflection;
using System.Transactions;
using Xunit.Sdk;
namespace Bootstrap.DataAccess
{
/// <summary>
/// Apply this attribute to your test method to automatically create a <see cref="TransactionScope"/>
/// that is rolled back when the test is finished.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AutoRollbackAttribute : BeforeAfterTestAttribute
{
private TransactionScope scope;
/// <summary>
/// Gets or sets whether transaction flow across thread continuations is enabled for TransactionScope.
/// By default transaction flow across thread continuations is enabled.
/// </summary>
public TransactionScopeAsyncFlowOption AsyncFlowOption { get; set; } = TransactionScopeAsyncFlowOption.Enabled;
/// <summary>
/// Gets or sets the isolation level of the transaction.
/// Default value is <see cref="IsolationLevel"/>.Unspecified.
/// </summary>
public IsolationLevel IsolationLevel { get; set; } = IsolationLevel.Unspecified;
/// <summary>
/// Gets or sets the scope option for the transaction.
/// Default value is <see cref="TransactionScopeOption"/>.Required.
/// </summary>
public TransactionScopeOption ScopeOption { get; set; } = TransactionScopeOption.Required;
/// <summary>
/// Gets or sets the timeout of the transaction, in milliseconds.
/// By default, the transaction will not timeout.
/// </summary>
public long TimeoutInMS { get; set; } = -1;
/// <summary>
/// Rolls back the transaction.
/// </summary>
public override void After(MethodInfo methodUnderTest)
{
scope.Dispose();
}
/// <summary>
/// Creates the transaction.
/// </summary>
public override void Before(MethodInfo methodUnderTest)
{
var options = new TransactionOptions { IsolationLevel = IsolationLevel };
if (TimeoutInMS > 0)
options.Timeout = TimeSpan.FromMilliseconds(TimeoutInMS);
scope = new TransactionScope(ScopeOption, options, AsyncFlowOption);
}
}
}

View File

@ -17,18 +17,13 @@ namespace Bootstrap.DataAccess.SqlServer
var dict = new BootstrapDict()
{
Category = "UnitTest",
Name = "Test1",
Name = "SaveDict",
Code = "1",
Define = 1
};
// insert
Assert.True(DictHelper.Save(dict));
// update
dict.Code = "2";
Assert.True(DictHelper.Save(dict));
// delete
Assert.True(DictHelper.Delete(new string[] { dict.Id }));
}
@ -38,16 +33,17 @@ namespace Bootstrap.DataAccess.SqlServer
var dict = new Dict()
{
Category = "UnitTest",
Name = "Test1",
Name = "SaveSettings",
Code = "1",
Define = 1
};
// insert
Assert.True(DictHelper.Save(dict));
// update
Assert.True(DictHelper.SaveSettings(dict));
// delete
dict.Delete(DictHelper.RetrieveDicts().Where(d => d.Category == dict.Category).Select(d => d.Id));
Assert.True(DictHelper.Delete(new string[] { dict.Id }));
}
[Fact]
@ -92,6 +88,16 @@ namespace Bootstrap.DataAccess.SqlServer
Assert.Equal("~/Home/Index", DictHelper.RetrieveHomeUrl("0"));
var url = DictHelper.RetrieveHomeUrl("2");
Assert.NotEqual("~/Home/Index", url);
// INSERT INTO [Dicts] ([Category], [Name], [Code], [Define]) VALUES ('应用首页', 2, 'http://localhost:49185/', 0);
var dict = DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "应用首页" && d.Name == "2");
url = dict.Code;
dict.Code = "";
Assert.True(DictHelper.Save(dict));
Assert.Equal("~/Home/Index", DictHelper.RetrieveHomeUrl("2"));
dict.Code = url;
Assert.True(DictHelper.Save(dict));
}
[Fact]
@ -189,7 +195,7 @@ namespace Bootstrap.DataAccess.SqlServer
var dict = new BootstrapDict() { Category = "系统检查", Name = "系统设置", Code = DatabaseName, Define = 0 };
Assert.True(DictHelper.Save(dict));
Assert.Equal(DatabaseName, DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == dict.Category && d.Name == dict.Name)?.Code ?? "unknown");
DictHelper.Delete(new string[] { dict.Id });
Assert.True(DictHelper.Delete(new string[] { dict.Id }));
}
#region Private Class For Test

View File

@ -1,4 +1,4 @@
using Longbow.Web.Mvc;
using Longbow.Web.Mvc;
using Microsoft.Data.Sqlite;
using System;
using Xunit;
@ -14,7 +14,7 @@ namespace Bootstrap.DataAccess.SqlServer
ExceptionsHelper.Log(new Exception("UnitTest", new SqliteException("UnitTest", 1001)), null);
Assert.NotEmpty(ExceptionsHelper.Retrieves());
Exceptions ex = new Exceptions() { Period = "1" };
var ex = new Exceptions() { Period = "1" };
Assert.Equal("1", ex.Period);
}

View File

@ -1,4 +1,6 @@
using System.Linq;
using System;
using System.Linq;
using UnitTest;
using Xunit;
namespace Bootstrap.DataAccess.SqlServer
@ -15,7 +17,7 @@ namespace Bootstrap.DataAccess.SqlServer
[Fact]
public void SaveAndDelete_Ok()
{
Group g = new Group() { GroupName = "UnitTest", Description = "UnitTestSave" };
var g = new Group() { GroupName = "UnitTest", Description = "UnitTestSave" };
// insert
Assert.True(GroupHelper.Save(g));

View File

@ -6,22 +6,6 @@ namespace Bootstrap.DataAccess.SqlServer
[Collection("SQLServerContext")]
public class LogsTest
{
[Fact]
public void Save_Ok()
{
var log = new Log()
{
UserName = "UnitTest",
Browser = "UnitTest",
City = "本地连接",
OS = "UnitTest",
Ip = "::1",
CRUD = "UnitTest",
RequestUrl = "~/Home/Index"
};
Assert.True(LogHelper.Save(log));
}
[Fact]
public void Retrieves_Ok()
{
@ -35,7 +19,7 @@ namespace Bootstrap.DataAccess.SqlServer
CRUD = "UnitTest",
RequestUrl = "~/Home/Index"
};
LogHelper.Save(log);
Assert.True(LogHelper.Save(log));
Assert.NotNull(LogHelper.RetrievePages(new PaginationOption() { Limit = 20, Sort = "LogTime", Order = "desc" }, null, null, null));
Assert.NotNull(LogHelper.RetrievePages(new PaginationOption() { Limit = 20, Sort = "CRUD", Order = "desc" }, null, null, null));
Assert.NotNull(LogHelper.RetrievePages(new PaginationOption() { Limit = 20, Sort = "UserName", Order = "desc" }, null, null, null));

View File

@ -42,25 +42,6 @@ namespace Bootstrap.DataAccess.SqlServer
Assert.NotEmpty(MenuHelper.RetrieveMenusByRoleId(roleId));
}
[Fact]
public void Delete_Ok()
{
var poco = new BootstrapMenu()
{
Name = "UnitTest",
Application = "0",
Category = "0",
Icon = "fa fa-fa",
IsResource = 0,
Target = "_blank",
Order = 10,
Url = "#",
ParentId = "0"
};
MenuHelper.Save(poco);
MenuHelper.Delete(MenuHelper.RetrieveAllMenus("Admin").Where(n => n.Name == poco.Name).Select(n => n.Id));
}
[Fact]
public void RetrieveAllMenus_Ok()
{

View File

@ -7,13 +7,7 @@ namespace Bootstrap.DataAccess.SqlServer
public class MessagesTest
{
[Fact]
public void RetrieveHeaders_Ok()
{
Assert.NotNull(MessageHelper.Retrieves("Admin"));
}
[Fact]
public virtual void Save_Ok()
public void Retrieves_Ok()
{
var msg = new Message()
{
@ -32,8 +26,7 @@ namespace Bootstrap.DataAccess.SqlServer
FromIcon = "Default.jpg"
};
Assert.True(MessageHelper.Save(msg));
Assert.NotEmpty(MessageHelper.Retrieves("User"));
}
}
}

View File

@ -11,7 +11,6 @@ namespace Bootstrap.DataAccess.SqlServer
public void ResetReasonsByUserName_Ok()
{
var user = new User { UserName = "UnitTestReset", Password = "1", DisplayName = "DisplayName", ApprovedBy = "System", ApprovedTime = DateTime.Now, Description = "Desc", Icon = "default.jpg" };
UserHelper.Delete(UserHelper.Retrieves().Union(UserHelper.RetrieveNewUsers()).Where(u => u.UserName == user.UserName).Select(u => u.Id));
Assert.True(UserHelper.Save(user));
UserHelper.ForgotPassword(new ResetUser() { UserName = user.UserName, DisplayName = user.DisplayName, Reason = "UnitTest", ResetTime = DateTime.Now });
@ -19,6 +18,8 @@ namespace Bootstrap.DataAccess.SqlServer
var reasons = UserHelper.RetrieveResetReasonsByUserName(user.UserName);
Assert.NotEmpty(reasons);
UserHelper.Delete(new string[] { user.Id });
}
[Fact]

View File

@ -0,0 +1,110 @@
using System;
using UnitTest;
using Xunit;
namespace Bootstrap.DataAccess
{
[Collection("SQLServerContext")]
public class RollbackTest
{
[Fact]
public void App_Save()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new App().SaveByRoleId("1", new string[] { "2" })));
}
[Fact]
public void Group_Delete()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Group().Delete(new string[] { "0" })));
}
[Fact]
public void Group_SaveByUser()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Group().SaveByUserId("1", new string[] { "1" })));
}
[Fact]
public void Group_SaveByRole()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Group().SaveByRoleId("1", new string[] { "1" })));
}
[Fact]
public void Menu_Delete()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Menu().Delete(new string[] { "0" })));
}
[Fact]
public void Menu_Save()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Menu().SaveMenusByRoleId("1", new string[] { "1" })));
}
[Fact]
public void Role_Delete()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Role().Delete(new string[] { "0" })));
}
[Fact]
public void Role_SaveByMenu()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Role().SavaByMenuId("1", new string[] { "1" })));
}
[Fact]
public void Role_SaveByUser()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Role().SaveByUserId("1", new string[] { "1" })));
}
[Fact]
public void Role_SaveByGroup()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new Role().SaveByGroupId("1", new string[] { "1" })));
}
[Fact]
public void User_Delete()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new User().Delete(new string[] { "0" })));
}
[Fact]
public void User_Reset()
{
var newUser = new User() { UserName = "U_Reset", DisplayName = "UnitTest", ApprovedTime = DateTime.Now, ApprovedBy = "System", Password = "1", Description = "UnitTest", RegisterTime = DateTime.Now };
Assert.True(UserHelper.Save(newUser));
Assert.True(UserHelper.ForgotPassword(new ResetUser() { DisplayName = "UnitTest", Reason = "UnitTest", ResetTime = DateTime.Now, UserName = newUser.UserName }));
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeUserMapper(() => new User().ResetPassword(newUser.UserName, "123789")));
Assert.True(UserHelper.Delete(new string[] { newUser.Id }));
}
[Fact]
public void User_Rejet()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new User().Reject("0", "User")));
}
[Fact]
public void User_Save()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new User().Save(new User() { Password = "1", UserName = "U_Save", DisplayName = "UnitTest" })));
}
[Fact]
public void User_SaveByRole()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new User().SaveByRoleId("1", new string[] { "1" })));
}
[Fact]
public void User_SaveByMenu()
{
Assert.ThrowsAny<Exception>(() => TestHelper.RevokeMapper(() => new User().SaveByGroupId("1", new string[] { "1" })));
}
}
}

View File

@ -0,0 +1,119 @@
using Bootstrap.Security;
using Longbow.Web;
using System.Linq;
using Xunit;
namespace Bootstrap.DataAccess
{
[Collection("SQLServerContext")]
[AutoRollback]
public class SystemModeTest
{
private void SetSystemMode()
{
var dict = DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "演示系统");
dict.Code = "1";
DictHelper.Save(dict);
}
[Fact]
public void DictDelete_Ok()
{
SetSystemMode();
var ids = DictHelper.RetrieveDicts().Where(d => d.Define == 0);
Assert.True(DictHelper.Delete(ids.Select(d => d.Id)));
Assert.Equal(ids.Count(), DictHelper.RetrieveDicts().Count(d => d.Define == 0));
}
[Fact]
public void MenuSave_Ok()
{
SetSystemMode();
var menu = MenuHelper.RetrieveMenus("Admin").FirstOrDefault(m => m.Category == "0");
var name = menu.Name;
menu.Name = "UnitTest";
Assert.True(MenuHelper.Save(menu));
var menu2 = MenuHelper.RetrieveMenus("Admin").FirstOrDefault(m => m.Id == menu.Id);
Assert.Equal(name, menu2.Name);
}
[Fact]
public void MenuDelete_Ok()
{
SetSystemMode();
var menu = MenuHelper.RetrieveMenus("Admin").FirstOrDefault(m => m.Category == "0");
Assert.True(MenuHelper.Delete(new string[] { menu.Id }));
var menu2 = MenuHelper.RetrieveMenus("Admin").FirstOrDefault(m => m.Id == menu.Id);
Assert.NotNull(menu2);
// 保护模式下,正常菜单可以删除
var poco = new BootstrapMenu()
{
Name = "UnitTest",
Application = "3",
Category = "1",
Icon = "fa fa-fa",
IsResource = 0,
Target = "_blank",
Order = 10,
Url = "#",
ParentId = "0",
ParentName = "Test",
};
// insert
Assert.True(MenuHelper.Save(poco));
// update
poco = MenuHelper.RetrieveAllMenus("Admin").Where(m => m.Id == poco.Id).FirstOrDefault();
Assert.True(MenuHelper.Save(poco));
// clean
MenuHelper.Delete(new string[] { poco.Id });
}
[Fact]
public void UserSave_Ok()
{
SetSystemMode();
var user = UserHelper.Retrieves().FirstOrDefault(m => m.UserName == "User");
user.DisplayName = "UnitTest";
Assert.True(UserHelper.Save(user));
var user2 = UserHelper.Retrieves().FirstOrDefault(m => m.Id == user.Id);
Assert.NotEqual("UnitTest", user2.DisplayName);
}
[Fact]
public void UserUpdate_Ok()
{
SetSystemMode();
var user = UserHelper.Retrieves().FirstOrDefault(m => m.UserName == "User");
user.DisplayName = "UnitTest";
Assert.True(UserHelper.Update(user.Id, "123789", "UnitTest"));
var user2 = UserHelper.Retrieves().FirstOrDefault(m => m.Id == user.Id);
Assert.NotEqual("UnitTest", user2.DisplayName);
}
[Fact]
public void UserChangePassword_Ok()
{
SetSystemMode();
Assert.True(UserHelper.ChangePassword("User", "123789", "123789"));
}
[Fact]
public void ConfigIPLocator_Ok()
{
var op = new IPLocatorOption()
{
IP = "182.148.123.196"
};
var dict = DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP地理位置接口" && d.Define == 0);
Assert.NotNull(dict);
dict.Code = "JuheIPSvr";
DictHelper.Save(dict);
DictHelper.ConfigIPLocator(op);
Assert.NotNull(op.Url);
}
}
}

View File

@ -8,22 +8,6 @@ namespace Bootstrap.DataAccess.SqlServer
[Collection("SQLServerContext")]
public class TracesTest
{
[Fact]
public void Save_Ok()
{
var log = new Trace()
{
UserName = "UnitTest",
Browser = "UnitTest",
City = "本地连接",
OS = "UnitTest",
Ip = "::1",
LogTime = DateTime.Now,
RequestUrl = "~/Home/Index"
};
Assert.True(DbContextManager.Create<Trace>().Save(log));
}
[Fact]
public void Retrieves_Ok()
{
@ -37,14 +21,14 @@ namespace Bootstrap.DataAccess.SqlServer
LogTime = DateTime.Now,
RequestUrl = "~/Home/Index"
};
DbContextManager.Create<Trace>().Save(log);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "LogTime" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "IP" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "UserName" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "City" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "Browser" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "OS" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "RequestUrl" }, null, null, null).Items);
Assert.True(DbContextManager.Create<Trace>().Save(log));
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "LogTime" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "IP" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "UserName" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "City" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "Browser" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "OS" }, null, null, null).Items);
Assert.NotNull(TraceHelper.Retrieves(new PaginationOption() { Limit = 20, Offset = 0, Order = "desc", Sort = "RequestUrl" }, null, null, null).Items);
Assert.NotEmpty(TraceHelper.RetrieveAll(null, null, null));
}
}

View File

@ -67,26 +67,6 @@ namespace Bootstrap.DataAccess.SqlServer
UserHelper.Delete(UserHelper.Retrieves().Where(u => u.UserName == up.UserName).Select(u => u.Id));
}
[Fact]
public void RetrieveUsersByRoleId_Ok()
{
var rid = RoleHelper.Retrieves().FirstOrDefault(r => r.RoleName == "Administrators").Id;
var uid = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == "Admin").Id;
UserHelper.SaveByRoleId(rid, new string[] { uid });
var users = UserHelper.RetrievesByRoleId(rid);
Assert.NotEmpty(users.Where(u => u.Checked == "checked"));
}
[Fact]
public void RetrievesByGroupId_Ok()
{
var gid = GroupHelper.Retrieves().FirstOrDefault(r => r.GroupName == "Admin").Id;
var users = UserHelper.RetrievesByGroupId(gid);
Assert.NotEmpty(users.Where(u => u.Checked == "checked"));
}
[Fact]
public void SaveUser_Ok()
{
@ -133,6 +113,11 @@ namespace Bootstrap.DataAccess.SqlServer
var groupId = GroupHelper.Retrieves().FirstOrDefault(g => g.GroupName == "Admin").Id;
var id = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == "Admin").Id;
Assert.True(UserHelper.SaveByGroupId(groupId, new string[] { id }));
var users = UserHelper.RetrievesByGroupId(groupId);
Assert.NotEmpty(users.Where(u => u.Checked == "checked"));
Assert.True(UserHelper.SaveByGroupId(groupId, new string[0]));
}
[Fact]
@ -141,6 +126,9 @@ namespace Bootstrap.DataAccess.SqlServer
var roleId = RoleHelper.Retrieves().FirstOrDefault(g => g.RoleName == "Administrators").Id;
var id = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == "Admin").Id;
Assert.True(UserHelper.SaveByRoleId(roleId, new string[] { id }));
var users = UserHelper.RetrievesByRoleId(roleId);
Assert.NotEmpty(users.Where(u => u.Checked == "checked"));
}
[Fact]
@ -165,11 +153,10 @@ namespace Bootstrap.DataAccess.SqlServer
Assert.False(UserHelper.ResetPassword("User", "123789"));
var newUser = new User() { UserName = "U_Reset", DisplayName = "UnitTest", ApprovedTime = DateTime.Now, ApprovedBy = "System", Password = "1", Description = "UnitTest", RegisterTime = DateTime.Now };
var ids = UserHelper.Retrieves().Where(u => u.UserName == newUser.UserName).Select(u => u.Id);
UserHelper.Delete(ids);
Assert.True(UserHelper.Save(newUser));
Assert.True(UserHelper.ForgotPassword(new ResetUser() { DisplayName = "UnitTest", Reason = "UnitTest", ResetTime = DateTime.Now, UserName = newUser.UserName }));
Assert.True(UserHelper.ResetPassword(newUser.UserName, "123"));
Assert.True(UserHelper.Delete(new string[] { newUser.Id }));
}
[Fact]

View File

@ -1,6 +1,8 @@
using Bootstrap.DataAccess;
using Longbow.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.IO;
@ -78,5 +80,44 @@ namespace UnitTest
}));
}
}
/// <summary>
///
/// </summary>
/// <param name="t"></param>
/// <param name="callback"></param>
public static void RevokeMapper(Action callback)
{
var t = typeof(App);
var map = Mappers.GetMapper(t, null);
Mappers.Revoke(map);
var foo = new FooMapper();
Mappers.Register(t.Assembly, foo);
try { callback(); }
catch (Exception ex) { throw ex; }
finally
{
Mappers.Revoke(foo);
Mappers.Register(t.Assembly, map);
}
}
public static void RevokeUserMapper(Action callback)
{
var foo = new FooMapper();
Mappers.Register(typeof(User), foo);
try { callback(); }
catch (Exception ex) { throw ex; }
finally
{
Mappers.Revoke(foo);
}
}
private class FooMapper : ConventionMapper
{
public override TableInfo GetTableInfo(Type pocoType) => throw new Exception();
}
}
}

View File

@ -3,7 +3,9 @@
"LogLevel": {
"Default": "Error",
"System": "Error",
"Microsoft": "Error"
"Microsoft": "Error",
"Longbow.Logging.FileLogger": "None",
"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware": "None"
}
},
"ConnectionStrings": {