diff --git a/Bootstrap.DataAccess.MongoDB/App.cs b/Bootstrap.DataAccess.MongoDB/App.cs index 7c67b585..b95e95fe 100644 --- a/Bootstrap.DataAccess.MongoDB/App.cs +++ b/Bootstrap.DataAccess.MongoDB/App.cs @@ -32,6 +32,9 @@ namespace Bootstrap.DataAccess.MongoDB /// public override bool SaveByRoleId(string roleId, IEnumerable 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.Update.Set(md => md.Apps, appIds)); return true; } diff --git a/Bootstrap.DataAccess.MongoDB/DbManager.cs b/Bootstrap.DataAccess.MongoDB/DbManager.cs index 43780fca..d12714b1 100644 --- a/Bootstrap.DataAccess.MongoDB/DbManager.cs +++ b/Bootstrap.DataAccess.MongoDB/DbManager.cs @@ -195,13 +195,6 @@ namespace Bootstrap.DataAccess.MongoDB { BsonSerializer.RegisterSerializer(DateTimeSerializer.LocalInstance); - if (!BsonClassMap.IsClassMapRegistered(typeof(Dict))) - { - BsonClassMap.RegisterClassMap(md => - { - md.AutoMap(); - }); - } if (!BsonClassMap.IsClassMapRegistered(typeof(BootstrapDict))) { BsonClassMap.RegisterClassMap(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))) diff --git a/Bootstrap.DataAccess.MongoDB/Trace.cs b/Bootstrap.DataAccess.MongoDB/Trace.cs index 7bcaafd0..f95cc5c7 100644 --- a/Bootstrap.DataAccess.MongoDB/Trace.cs +++ b/Bootstrap.DataAccess.MongoDB/Trace.cs @@ -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 /// public override bool Save(DataAccess.Trace p) { - p.Id = null; DbManager.Traces.InsertOne(p); ClearTraces(); return true; diff --git a/Bootstrap.DataAccess.MongoDB/User.cs b/Bootstrap.DataAccess.MongoDB/User.cs index d3f34a92..f0f27419 100644 --- a/Bootstrap.DataAccess.MongoDB/User.cs +++ b/Bootstrap.DataAccess.MongoDB/User.cs @@ -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; } diff --git a/Bootstrap.DataAccess/App.cs b/Bootstrap.DataAccess/App.cs index 9dd4f90b..960def19 100644 --- a/Bootstrap.DataAccess/App.cs +++ b/Bootstrap.DataAccess/App.cs @@ -56,7 +56,10 @@ namespace Bootstrap.DataAccess /// public virtual bool SaveByRoleId(string roleId, IEnumerable 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 { diff --git a/Bootstrap.DataAccess/Dict.cs b/Bootstrap.DataAccess/Dict.cs index 523105e4..2d11aa8b 100644 --- a/Bootstrap.DataAccess/Dict.cs +++ b/Bootstrap.DataAccess/Dict.cs @@ -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; diff --git a/Bootstrap.DataAccess/Group.cs b/Bootstrap.DataAccess/Group.cs index 37489531..1d4aac42 100644 --- a/Bootstrap.DataAccess/Group.cs +++ b/Bootstrap.DataAccess/Group.cs @@ -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($"where ID in ({ids})"); db.CompleteTransaction(); ret = true; } diff --git a/Bootstrap.DataAccess/Helper/DictHelper.cs b/Bootstrap.DataAccess/Helper/DictHelper.cs index 03fdd1ae..04e34354 100644 --- a/Bootstrap.DataAccess/Helper/DictHelper.cs +++ b/Bootstrap.DataAccess/Helper/DictHelper.cs @@ -41,14 +41,10 @@ namespace Bootstrap.DataAccess /// public static bool Delete(IEnumerable 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().Delete(value); CacheCleanUtility.ClearCache(dictIds: value); return ret; @@ -61,7 +57,7 @@ namespace Bootstrap.DataAccess /// 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().Save(p); diff --git a/Bootstrap.DataAccess/Helper/MenuHelper.cs b/Bootstrap.DataAccess/Helper/MenuHelper.cs index 2a93d07f..58af4640 100644 --- a/Bootstrap.DataAccess/Helper/MenuHelper.cs +++ b/Bootstrap.DataAccess/Helper/MenuHelper.cs @@ -31,20 +31,8 @@ namespace Bootstrap.DataAccess /// 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().Save(p); if (ret) CacheCleanUtility.ClearCache(menuIds: string.IsNullOrEmpty(p.Id) ? new List() : new List() { 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; } diff --git a/Bootstrap.DataAccess/Helper/MessageHelper.cs b/Bootstrap.DataAccess/Helper/MessageHelper.cs index e9131741..c8c91cc1 100644 --- a/Bootstrap.DataAccess/Helper/MessageHelper.cs +++ b/Bootstrap.DataAccess/Helper/MessageHelper.cs @@ -44,6 +44,10 @@ namespace Bootstrap.DataAccess /// public static IEnumerable Retrieves(string userName) => CacheManager.GetOrAdd(RetrieveMessageDataKey, key => DbContextManager.Create().RetrieveHeaders(userName).OrderByDescending(n => n.SendTime)); - public static bool Save(Message msg) => DbContextManager.Create().Save(msg); + public static bool Save(Message msg) + { + if (string.IsNullOrEmpty(msg.Id)) msg.Id = null; + return DbContextManager.Create().Save(msg); + } } } diff --git a/Bootstrap.DataAccess/Helper/TaskHelper.cs b/Bootstrap.DataAccess/Helper/TaskHelper.cs index c3ab69ba..b1f64d8d 100644 --- a/Bootstrap.DataAccess/Helper/TaskHelper.cs +++ b/Bootstrap.DataAccess/Helper/TaskHelper.cs @@ -25,6 +25,10 @@ namespace Bootstrap.DataAccess /// /// /// - public static bool Save(Task task) => DbContextManager.Create().Save(task); + public static bool Save(Task task) + { + if (string.IsNullOrEmpty(task.Id)) task.Id = null; + return DbContextManager.Create().Save(task); + } } } diff --git a/Bootstrap.DataAccess/Helper/TraceHelper.cs b/Bootstrap.DataAccess/Helper/TraceHelper.cs index 8e97da9d..0c5f3061 100644 --- a/Bootstrap.DataAccess/Helper/TraceHelper.cs +++ b/Bootstrap.DataAccess/Helper/TraceHelper.cs @@ -25,6 +25,7 @@ namespace Bootstrap.DataAccess v.DisplayName = user.DisplayName; DbContextManager.Create().Save(new Trace { + Id = null, Ip = v.Ip, RequestUrl = v.RequestUrl, LogTime = v.LastAccessTime, diff --git a/Bootstrap.DataAccess/Helper/UserHelper.cs b/Bootstrap.DataAccess/Helper/UserHelper.cs index 73c2d900..fd9bd294 100644 --- a/Bootstrap.DataAccess/Helper/UserHelper.cs +++ b/Bootstrap.DataAccess/Helper/UserHelper.cs @@ -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().Save(user); if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(user.Id) ? new List() : new List() { 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().Update(id, password, displayName); if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(id) ? new List() : new List() { id }); return ret; diff --git a/Bootstrap.DataAccess/Menu.cs b/Bootstrap.DataAccess/Menu.cs index b5aeb329..e9f2d92d 100644 --- a/Bootstrap.DataAccess/Menu.cs +++ b/Bootstrap.DataAccess/Menu.cs @@ -10,6 +10,7 @@ namespace Bootstrap.DataAccess /// /// /// + [TableName("Navigations")] public class Menu : BootstrapMenu { /// @@ -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($"where ID in ({ids})"); db.CompleteTransaction(); ret = true; } diff --git a/Bootstrap.DataAccess/Message.cs b/Bootstrap.DataAccess/Message.cs index 3438e48a..02f1c5af 100644 --- a/Bootstrap.DataAccess/Message.cs +++ b/Bootstrap.DataAccess/Message.cs @@ -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($"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($"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); } /// @@ -168,6 +168,8 @@ namespace Bootstrap.DataAccess /// public virtual bool Save(Message msg) { + var db = DbManager.Create(); + db.Save(msg); return true; } } diff --git a/Bootstrap.DataAccess/Role.cs b/Bootstrap.DataAccess/Role.cs index 3d2c7172..de22ab53 100644 --- a/Bootstrap.DataAccess/Role.cs +++ b/Bootstrap.DataAccess/Role.cs @@ -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($"where ID in ({ids})"); db.CompleteTransaction(); ret = true; } diff --git a/Bootstrap.DataAccess/User.cs b/Bootstrap.DataAccess/User.cs index 45fb525b..8cad6c9e 100644 --- a/Bootstrap.DataAccess/User.cs +++ b/Bootstrap.DataAccess/User.cs @@ -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($"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("where Id = @0", id); db.CompleteTransaction(); ret = true; } diff --git a/UnitTest/Bootstrap.Admin/Api/AnalyseTest.cs b/UnitTest/Bootstrap.Admin/Api/AnalyseTest.cs index 990edbc4..9738b16a 100644 --- a/UnitTest/Bootstrap.Admin/Api/AnalyseTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/AnalyseTest.cs @@ -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 { diff --git a/UnitTest/Bootstrap.Admin/Api/ExceptionsTest.cs b/UnitTest/Bootstrap.Admin/Api/ExceptionsTest.cs index 6d468d18..cd996148 100644 --- a/UnitTest/Bootstrap.Admin/Api/ExceptionsTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/ExceptionsTest.cs @@ -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); } } } diff --git a/UnitTest/Bootstrap.Admin/Api/GiteeTest.cs b/UnitTest/Bootstrap.Admin/Api/GiteeTest.cs index 084029f4..013721e7 100644 --- a/UnitTest/Bootstrap.Admin/Api/GiteeTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/GiteeTest.cs @@ -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("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>(() => + { + throw new TaskCanceledException(); + }) + }); + + t.Invoke(null, new object[] { + new Func>(()=> { + throw new Exception(); + }) + }); + } } } diff --git a/UnitTest/Bootstrap.Admin/Api/MySql/GiteeTest.cs b/UnitTest/Bootstrap.Admin/Api/MySql/GiteeTest.cs deleted file mode 100644 index 9ce503d3..00000000 --- a/UnitTest/Bootstrap.Admin/Api/MySql/GiteeTest.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Xunit; - -namespace Bootstrap.Admin.Api.MySql -{ - [Collection("MySqlContext")] - public class GiteeTest : SqlServer.GiteeTest - { - public GiteeTest(MySqlBAWebHost factory) : base(factory) { } - } -} diff --git a/UnitTest/Bootstrap.Admin/Api/OnlineUserTest.cs b/UnitTest/Bootstrap.Admin/Api/OnlineUserTest.cs index 6c1fd5f1..681c30da 100644 --- a/UnitTest/Bootstrap.Admin/Api/OnlineUserTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/OnlineUserTest.cs @@ -2,7 +2,7 @@ using System.Reflection; using Xunit; -namespace UnitTest.Bootstrap.Admin.Api +namespace Bootstrap.Admin.Api { public class OnlineUserTest { diff --git a/UnitTest/Bootstrap.Admin/Api/RegisterTest.cs b/UnitTest/Bootstrap.Admin/Api/RegisterTest.cs index 851c5b4f..d246b4bd 100644 --- a/UnitTest/Bootstrap.Admin/Api/RegisterTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/RegisterTest.cs @@ -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(nusr); Assert.True(resp); UserHelper.Delete(nusr.RetrieveNewUsers().Where(u => u.UserName == nusr.UserName).Select(u => u.Id)); diff --git a/UnitTest/Bootstrap.Admin/Api/SQLite/GiteeTest.cs b/UnitTest/Bootstrap.Admin/Api/SQLite/GiteeTest.cs deleted file mode 100644 index 45328617..00000000 --- a/UnitTest/Bootstrap.Admin/Api/SQLite/GiteeTest.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Xunit; - -namespace Bootstrap.Admin.Api.SQLite -{ - [Collection("SQLiteContext")] - public class GiteeTest : SqlServer.GiteeTest - { - public GiteeTest(SQLiteBAWebHost factory) : base(factory) { } - } -} diff --git a/UnitTest/Bootstrap.Admin/Api/ToolsTest.cs b/UnitTest/Bootstrap.Admin/Api/ToolsTest.cs index 2133074c..b033c863 100644 --- a/UnitTest/Bootstrap.Admin/Api/ToolsTest.cs +++ b/UnitTest/Bootstrap.Admin/Api/ToolsTest.cs @@ -2,7 +2,7 @@ using System.Net.Http; using Xunit; -namespace Bootstrap.Admin.Api.SqlServer +namespace Bootstrap.Admin.Api { public class ToolsTest : ControllerTest { diff --git a/UnitTest/Bootstrap.Admin/Controllers/AccountTest.cs b/UnitTest/Bootstrap.Admin/Controllers/AccountTest.cs index 613be418..c421ff16 100644 --- a/UnitTest/Bootstrap.Admin/Controllers/AccountTest.cs +++ b/UnitTest/Bootstrap.Admin/Controllers/AccountTest.cs @@ -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] diff --git a/UnitTest/Bootstrap.DataAccess/AppTest.cs b/UnitTest/Bootstrap.DataAccess/AppTest.cs index e7b71a7a..1556e2ef 100644 --- a/UnitTest/Bootstrap.DataAccess/AppTest.cs +++ b/UnitTest/Bootstrap.DataAccess/AppTest.cs @@ -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(() => AppHelper.SaveByRoleId(roleId, null)); + } } } diff --git a/UnitTest/Bootstrap.DataAccess/AuthButtonTest.cs b/UnitTest/Bootstrap.DataAccess/AuthButtonTest.cs new file mode 100644 index 00000000..7e98cffd --- /dev/null +++ b/UnitTest/Bootstrap.DataAccess/AuthButtonTest.cs @@ -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 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(); + } + } +} diff --git a/UnitTest/Bootstrap.DataAccess/AutoRollbackAttribute.cs b/UnitTest/Bootstrap.DataAccess/AutoRollbackAttribute.cs new file mode 100644 index 00000000..b412107d --- /dev/null +++ b/UnitTest/Bootstrap.DataAccess/AutoRollbackAttribute.cs @@ -0,0 +1,61 @@ +using System; +using System.Reflection; +using System.Transactions; +using Xunit.Sdk; + +namespace Bootstrap.DataAccess +{ + /// + /// Apply this attribute to your test method to automatically create a + /// that is rolled back when the test is finished. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public sealed class AutoRollbackAttribute : BeforeAfterTestAttribute + { + private TransactionScope scope; + + /// + /// Gets or sets whether transaction flow across thread continuations is enabled for TransactionScope. + /// By default transaction flow across thread continuations is enabled. + /// + public TransactionScopeAsyncFlowOption AsyncFlowOption { get; set; } = TransactionScopeAsyncFlowOption.Enabled; + + /// + /// Gets or sets the isolation level of the transaction. + /// Default value is .Unspecified. + /// + public IsolationLevel IsolationLevel { get; set; } = IsolationLevel.Unspecified; + + /// + /// Gets or sets the scope option for the transaction. + /// Default value is .Required. + /// + public TransactionScopeOption ScopeOption { get; set; } = TransactionScopeOption.Required; + + /// + /// Gets or sets the timeout of the transaction, in milliseconds. + /// By default, the transaction will not timeout. + /// + public long TimeoutInMS { get; set; } = -1; + + /// + /// Rolls back the transaction. + /// + public override void After(MethodInfo methodUnderTest) + { + scope.Dispose(); + } + + /// + /// Creates the transaction. + /// + 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); + } + } +} diff --git a/UnitTest/Bootstrap.DataAccess/DictsTest.cs b/UnitTest/Bootstrap.DataAccess/DictsTest.cs index eebfa36e..7a0b72d7 100644 --- a/UnitTest/Bootstrap.DataAccess/DictsTest.cs +++ b/UnitTest/Bootstrap.DataAccess/DictsTest.cs @@ -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 diff --git a/UnitTest/Bootstrap.DataAccess/ExceptionsTest.cs b/UnitTest/Bootstrap.DataAccess/ExceptionsTest.cs index de947e39..49da9c4e 100644 --- a/UnitTest/Bootstrap.DataAccess/ExceptionsTest.cs +++ b/UnitTest/Bootstrap.DataAccess/ExceptionsTest.cs @@ -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); } diff --git a/UnitTest/Bootstrap.DataAccess/GroupsTest.cs b/UnitTest/Bootstrap.DataAccess/GroupsTest.cs index c3f35c0e..2dcf4cb9 100644 --- a/UnitTest/Bootstrap.DataAccess/GroupsTest.cs +++ b/UnitTest/Bootstrap.DataAccess/GroupsTest.cs @@ -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)); diff --git a/UnitTest/Bootstrap.DataAccess/LogsTest.cs b/UnitTest/Bootstrap.DataAccess/LogsTest.cs index a8ae1232..158f8cb5 100644 --- a/UnitTest/Bootstrap.DataAccess/LogsTest.cs +++ b/UnitTest/Bootstrap.DataAccess/LogsTest.cs @@ -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)); diff --git a/UnitTest/Bootstrap.DataAccess/MenusTest.cs b/UnitTest/Bootstrap.DataAccess/MenusTest.cs index c07ee8f4..20c24172 100644 --- a/UnitTest/Bootstrap.DataAccess/MenusTest.cs +++ b/UnitTest/Bootstrap.DataAccess/MenusTest.cs @@ -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() { diff --git a/UnitTest/Bootstrap.DataAccess/MessagesTest.cs b/UnitTest/Bootstrap.DataAccess/MessagesTest.cs index afbe88c7..b6ad8360 100644 --- a/UnitTest/Bootstrap.DataAccess/MessagesTest.cs +++ b/UnitTest/Bootstrap.DataAccess/MessagesTest.cs @@ -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")); } } } diff --git a/UnitTest/Bootstrap.DataAccess/ResetUserTest.cs b/UnitTest/Bootstrap.DataAccess/ResetUserTest.cs index 2ba3e014..702a5460 100644 --- a/UnitTest/Bootstrap.DataAccess/ResetUserTest.cs +++ b/UnitTest/Bootstrap.DataAccess/ResetUserTest.cs @@ -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] diff --git a/UnitTest/Bootstrap.DataAccess/RollbackTest.cs b/UnitTest/Bootstrap.DataAccess/RollbackTest.cs new file mode 100644 index 00000000..693df18c --- /dev/null +++ b/UnitTest/Bootstrap.DataAccess/RollbackTest.cs @@ -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(() => TestHelper.RevokeMapper(() => new App().SaveByRoleId("1", new string[] { "2" }))); + } + + [Fact] + public void Group_Delete() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Group().Delete(new string[] { "0" }))); + } + + [Fact] + public void Group_SaveByUser() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Group().SaveByUserId("1", new string[] { "1" }))); + } + + [Fact] + public void Group_SaveByRole() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Group().SaveByRoleId("1", new string[] { "1" }))); + } + + [Fact] + public void Menu_Delete() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Menu().Delete(new string[] { "0" }))); + } + + [Fact] + public void Menu_Save() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Menu().SaveMenusByRoleId("1", new string[] { "1" }))); + } + + [Fact] + public void Role_Delete() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Role().Delete(new string[] { "0" }))); + } + + [Fact] + public void Role_SaveByMenu() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Role().SavaByMenuId("1", new string[] { "1" }))); + } + + [Fact] + public void Role_SaveByUser() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Role().SaveByUserId("1", new string[] { "1" }))); + } + + [Fact] + public void Role_SaveByGroup() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new Role().SaveByGroupId("1", new string[] { "1" }))); + } + + [Fact] + public void User_Delete() + { + Assert.ThrowsAny(() => 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(() => TestHelper.RevokeUserMapper(() => new User().ResetPassword(newUser.UserName, "123789"))); + Assert.True(UserHelper.Delete(new string[] { newUser.Id })); + } + + [Fact] + public void User_Rejet() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new User().Reject("0", "User"))); + } + + [Fact] + public void User_Save() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new User().Save(new User() { Password = "1", UserName = "U_Save", DisplayName = "UnitTest" }))); + } + + [Fact] + public void User_SaveByRole() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new User().SaveByRoleId("1", new string[] { "1" }))); + } + + [Fact] + public void User_SaveByMenu() + { + Assert.ThrowsAny(() => TestHelper.RevokeMapper(() => new User().SaveByGroupId("1", new string[] { "1" }))); + } + } +} diff --git a/UnitTest/Bootstrap.DataAccess/SystemModeTest.cs b/UnitTest/Bootstrap.DataAccess/SystemModeTest.cs new file mode 100644 index 00000000..4f705c6e --- /dev/null +++ b/UnitTest/Bootstrap.DataAccess/SystemModeTest.cs @@ -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); + } + } +} diff --git a/UnitTest/Bootstrap.DataAccess/TracesTest.cs b/UnitTest/Bootstrap.DataAccess/TracesTest.cs index 765173c0..92c7baa6 100644 --- a/UnitTest/Bootstrap.DataAccess/TracesTest.cs +++ b/UnitTest/Bootstrap.DataAccess/TracesTest.cs @@ -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().Save(log)); - } - [Fact] public void Retrieves_Ok() { @@ -37,14 +21,14 @@ namespace Bootstrap.DataAccess.SqlServer LogTime = DateTime.Now, RequestUrl = "~/Home/Index" }; - DbContextManager.Create().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().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)); } } diff --git a/UnitTest/Bootstrap.DataAccess/UsersTest.cs b/UnitTest/Bootstrap.DataAccess/UsersTest.cs index 69e2120c..981eb3ca 100644 --- a/UnitTest/Bootstrap.DataAccess/UsersTest.cs +++ b/UnitTest/Bootstrap.DataAccess/UsersTest.cs @@ -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] diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 701d4568..65675192 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -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 })); } } + + /// + /// + /// + /// + /// + 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(); + } } } diff --git a/UnitTest/appsettings.json b/UnitTest/appsettings.json index 6451c830..8eb89fa2 100644 --- a/UnitTest/appsettings.json +++ b/UnitTest/appsettings.json @@ -3,7 +3,9 @@ "LogLevel": { "Default": "Error", "System": "Error", - "Microsoft": "Error" + "Microsoft": "Error", + "Longbow.Logging.FileLogger": "None", + "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware": "None" } }, "ConnectionStrings": {