aboutsummaryrefslogtreecommitdiff
path: root/Timeline.Tests/Helpers
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-01-30 20:26:52 +0800
committercrupest <crupest@outlook.com>2020-01-30 20:26:52 +0800
commit52acf41e331ddbd66befed4692c804b754ba7d5c (patch)
tree538ceea06640f501d2a950cac813c10561036e4d /Timeline.Tests/Helpers
parentabde51b167f17301c25e32ae247e7909c0dc9367 (diff)
downloadtimeline-52acf41e331ddbd66befed4692c804b754ba7d5c.tar.gz
timeline-52acf41e331ddbd66befed4692c804b754ba7d5c.tar.bz2
timeline-52acf41e331ddbd66befed4692c804b754ba7d5c.zip
...
Diffstat (limited to 'Timeline.Tests/Helpers')
-rw-r--r--Timeline.Tests/Helpers/MockUser.cs24
-rw-r--r--Timeline.Tests/Helpers/PrincipalHelper.cs23
-rw-r--r--Timeline.Tests/Helpers/ResponseAssertions.cs14
-rw-r--r--Timeline.Tests/Helpers/TestApplication.cs15
-rw-r--r--Timeline.Tests/Helpers/TestClock.cs15
-rw-r--r--Timeline.Tests/Helpers/TestDatabase.cs89
-rw-r--r--Timeline.Tests/Helpers/UseCultureAttribute.cs94
7 files changed, 17 insertions, 257 deletions
diff --git a/Timeline.Tests/Helpers/MockUser.cs b/Timeline.Tests/Helpers/MockUser.cs
deleted file mode 100644
index 49576842..00000000
--- a/Timeline.Tests/Helpers/MockUser.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.Collections.Generic;
-using Timeline.Models.Http;
-
-namespace Timeline.Tests.Helpers
-{
- public class MockUser
- {
- public MockUser(string username, string password, bool administrator)
- {
- Info = new User { Username = username, Administrator = administrator };
- Password = password;
- }
-
- public User Info { get; set; }
- public string Username => Info.Username;
- public string Password { get; set; }
- public bool Administrator => Info.Administrator;
-
- public static MockUser User { get; } = new MockUser("user", "userpassword", false);
- public static MockUser Admin { get; } = new MockUser("admin", "adminpassword", true);
-
- public static IReadOnlyList<User> UserInfoList { get; } = new List<User> { User.Info, Admin.Info };
- }
-}
diff --git a/Timeline.Tests/Helpers/PrincipalHelper.cs b/Timeline.Tests/Helpers/PrincipalHelper.cs
deleted file mode 100644
index 89f3f7b1..00000000
--- a/Timeline.Tests/Helpers/PrincipalHelper.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Linq;
-using System.Security.Claims;
-using Timeline.Models;
-
-namespace Timeline.Tests.Helpers
-{
- public static class PrincipalHelper
- {
- internal const string AuthScheme = "TESTAUTH";
-
- internal static ClaimsPrincipal Create(string username, bool administrator)
- {
- var identity = new ClaimsIdentity(AuthScheme);
- identity.AddClaim(new Claim(identity.NameClaimType, username, ClaimValueTypes.String));
- identity.AddClaims(UserRoleConvert.ToArray(administrator).Select(role => new Claim(identity.RoleClaimType, role, ClaimValueTypes.String)));
-
- var principal = new ClaimsPrincipal();
- principal.AddIdentity(identity);
-
- return principal;
- }
- }
-}
diff --git a/Timeline.Tests/Helpers/ResponseAssertions.cs b/Timeline.Tests/Helpers/ResponseAssertions.cs
index be0043dc..f01a0677 100644
--- a/Timeline.Tests/Helpers/ResponseAssertions.cs
+++ b/Timeline.Tests/Helpers/ResponseAssertions.cs
@@ -125,6 +125,13 @@ namespace Timeline.Tests.Helpers
return assertions.HaveJsonBody<CommonResponse>(because, becauseArgs);
}
+ public static void HaveCommonBody(this HttpResponseMessageAssertions assertions, int code, string message = null, params object[] messageArgs)
+ {
+ message = string.IsNullOrEmpty(message) ? "" : ", " + string.Format(CultureInfo.CurrentCulture, message, messageArgs);
+ var body = assertions.HaveCommonBody("Response body should be CommonResponse{0}", message).Which;
+ body.Code.Should().Be(code, "Response body code is not the specified one{0}", message);
+ }
+
public static AndWhichConstraint<HttpResponseMessageAssertions, CommonDataResponse<TData>> HaveCommonDataBody<TData>(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
{
return assertions.HaveJsonBody<CommonDataResponse<TData>>(because, becauseArgs);
@@ -148,13 +155,6 @@ namespace Timeline.Tests.Helpers
body.Data.Delete.Should().Be(delete);
}
- public static void HaveCommonResponseBody(this HttpResponseMessageAssertions assertions, int code, string message = null, params object[] messageArgs)
- {
- message = string.IsNullOrEmpty(message) ? "" : ", " + string.Format(CultureInfo.CurrentCulture, message, messageArgs);
- var body = assertions.HaveJsonBody<CommonResponse>("Response body should be CommonResponse{0}", message).Which;
- body.Code.Should().Be(code, "Response body code is not the specified one{0}", message);
- }
-
public static void BeInvalidModel(this HttpResponseMessageAssertions assertions, string message = null)
{
message = string.IsNullOrEmpty(message) ? "" : ", " + message;
diff --git a/Timeline.Tests/Helpers/TestApplication.cs b/Timeline.Tests/Helpers/TestApplication.cs
index d18f2848..14cafea3 100644
--- a/Timeline.Tests/Helpers/TestApplication.cs
+++ b/Timeline.Tests/Helpers/TestApplication.cs
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -8,19 +10,21 @@ namespace Timeline.Tests.Helpers
{
public class TestApplication : IDisposable
{
- public TestDatabase Database { get; } = new TestDatabase();
+ public SqliteConnection DatabaseConnection { get; }
+
public WebApplicationFactory<Startup> Factory { get; }
public TestApplication(WebApplicationFactory<Startup> factory)
{
+ DatabaseConnection = new SqliteConnection("Data Source=:memory:;");
+
Factory = factory.WithWebHostBuilder(builder =>
{
- builder.ConfigureServices(services =>
+ builder.ConfigureTestServices(services =>
{
- services.AddEntityFrameworkSqlite();
services.AddDbContext<DatabaseContext, DevelopmentDatabaseContext>(options =>
{
- options.UseSqlite(Database.Connection);
+ options.UseSqlite(DatabaseConnection);
});
});
});
@@ -28,7 +32,8 @@ namespace Timeline.Tests.Helpers
public void Dispose()
{
- Database.Dispose();
+ DatabaseConnection.Close();
+ DatabaseConnection.Dispose();
}
}
}
diff --git a/Timeline.Tests/Helpers/TestClock.cs b/Timeline.Tests/Helpers/TestClock.cs
deleted file mode 100644
index 12b320d3..00000000
--- a/Timeline.Tests/Helpers/TestClock.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System;
-using Timeline.Services;
-
-namespace Timeline.Tests.Helpers
-{
- public class TestClock : IClock
- {
- public DateTime? MockCurrentTime { get; set; } = null;
-
- public DateTime GetCurrentTime()
- {
- return MockCurrentTime.GetValueOrDefault(DateTime.Now);
- }
- }
-}
diff --git a/Timeline.Tests/Helpers/TestDatabase.cs b/Timeline.Tests/Helpers/TestDatabase.cs
deleted file mode 100644
index e29a71fa..00000000
--- a/Timeline.Tests/Helpers/TestDatabase.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-using Microsoft.Data.Sqlite;
-using Microsoft.EntityFrameworkCore;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Timeline.Entities;
-using Timeline.Models;
-using Timeline.Services;
-
-namespace Timeline.Tests.Helpers
-{
- public class TestDatabase : IDisposable
- {
- // currently password service is thread safe, so we share a static one.
- private static PasswordService PasswordService { get; } = new PasswordService();
-
- private static UserEntity CreateEntityFromMock(MockUser user)
- {
- return new UserEntity
- {
- Username = user.Username,
- Password = PasswordService.HashPassword(user.Password),
- Roles = UserRoleConvert.ToString(user.Administrator),
- Avatar = null
- };
- }
-
- private static IEnumerable<UserEntity> CreateDefaultMockEntities()
- {
- // emmmmmmm. Never reuse the user instances because EF Core uses them, which will cause strange things.
- yield return CreateEntityFromMock(MockUser.User);
- yield return CreateEntityFromMock(MockUser.Admin);
- }
-
- private static void InitDatabase(DatabaseContext context)
- {
- context.Database.EnsureCreated();
- context.Users.AddRange(CreateDefaultMockEntities());
- context.SaveChanges();
- }
-
- public SqliteConnection Connection { get; }
- public DatabaseContext Context { get; }
-
- public TestDatabase()
- {
- Connection = new SqliteConnection("Data Source=:memory:;");
- Connection.Open();
-
- var options = new DbContextOptionsBuilder<DevelopmentDatabaseContext>()
- .UseSqlite(Connection)
- .Options;
-
- Context = new DevelopmentDatabaseContext(options);
-
- InitDatabase(Context);
- }
-
- private List<MockUser> _extraMockUsers;
-
- public IReadOnlyList<MockUser> ExtraMockUsers => _extraMockUsers;
-
- public void CreateExtraMockUsers(int count)
- {
- if (count <= 0)
- throw new ArgumentOutOfRangeException(nameof(count), count, "Additional user count must be bigger than 0.");
- if (_extraMockUsers != null)
- throw new InvalidOperationException("Already create mock users.");
-
- _extraMockUsers = new List<MockUser>();
- for (int i = 0; i < count; i++)
- {
- _extraMockUsers.Add(new MockUser($"user{i}", $"password", false));
- }
-
- Context.AddRange(_extraMockUsers.Select(u => CreateEntityFromMock(u)));
- Context.SaveChanges();
- }
-
- public void Dispose()
- {
- Context.Dispose();
-
- Connection.Close();
- Connection.Dispose();
- }
-
- }
-}
diff --git a/Timeline.Tests/Helpers/UseCultureAttribute.cs b/Timeline.Tests/Helpers/UseCultureAttribute.cs
deleted file mode 100644
index 017d77a8..00000000
--- a/Timeline.Tests/Helpers/UseCultureAttribute.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.Globalization;
-using System.Reflection;
-using System.Threading;
-using Xunit.Sdk;
-
-
-namespace Timeline.Tests.Helpers
-{
- // Copied from https://github.com/xunit/samples.xunit/blob/master/UseCulture/UseCultureAttribute.cs
-
- /// <summary>
- /// Apply this attribute to your test method to replace the
- /// <see cref="Thread.CurrentThread" /> <see cref="CultureInfo.CurrentCulture" /> and
- /// <see cref="CultureInfo.CurrentUICulture" /> with another culture.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
- public class UseCultureAttribute : BeforeAfterTestAttribute
- {
- readonly Lazy<CultureInfo> culture;
- readonly Lazy<CultureInfo> uiCulture;
-
- CultureInfo originalCulture;
- CultureInfo originalUICulture;
-
- /// <summary>
- /// Replaces the culture and UI culture of the current thread with
- /// <paramref name="culture" />
- /// </summary>
- /// <param name="culture">The name of the culture.</param>
- /// <remarks>
- /// <para>
- /// This constructor overload uses <paramref name="culture" /> for both
- /// <see cref="Culture" /> and <see cref="UICulture" />.
- /// </para>
- /// </remarks>
- public UseCultureAttribute(string culture)
- : this(culture, culture) { }
-
- /// <summary>
- /// Replaces the culture and UI culture of the current thread with
- /// <paramref name="culture" /> and <paramref name="uiCulture" />
- /// </summary>
- /// <param name="culture">The name of the culture.</param>
- /// <param name="uiCulture">The name of the UI culture.</param>
- public UseCultureAttribute(string culture, string uiCulture)
- {
- this.culture = new Lazy<CultureInfo>(() => new CultureInfo(culture, false));
- this.uiCulture = new Lazy<CultureInfo>(() => new CultureInfo(uiCulture, false));
- }
-
- /// <summary>
- /// Gets the culture.
- /// </summary>
- public CultureInfo Culture { get { return culture.Value; } }
-
- /// <summary>
- /// Gets the UI culture.
- /// </summary>
- public CultureInfo UICulture { get { return uiCulture.Value; } }
-
- /// <summary>
- /// Stores the current <see cref="Thread.CurrentPrincipal" />
- /// <see cref="CultureInfo.CurrentCulture" /> and <see cref="CultureInfo.CurrentUICulture" />
- /// and replaces them with the new cultures defined in the constructor.
- /// </summary>
- /// <param name="methodUnderTest">The method under test</param>
- public override void Before(MethodInfo methodUnderTest)
- {
- originalCulture = Thread.CurrentThread.CurrentCulture;
- originalUICulture = Thread.CurrentThread.CurrentUICulture;
-
- Thread.CurrentThread.CurrentCulture = Culture;
- Thread.CurrentThread.CurrentUICulture = UICulture;
-
- CultureInfo.CurrentCulture.ClearCachedData();
- CultureInfo.CurrentUICulture.ClearCachedData();
- }
-
- /// <summary>
- /// Restores the original <see cref="CultureInfo.CurrentCulture" /> and
- /// <see cref="CultureInfo.CurrentUICulture" /> to <see cref="Thread.CurrentPrincipal" />
- /// </summary>
- /// <param name="methodUnderTest">The method under test</param>
- public override void After(MethodInfo methodUnderTest)
- {
- Thread.CurrentThread.CurrentCulture = originalCulture;
- Thread.CurrentThread.CurrentUICulture = originalUICulture;
-
- CultureInfo.CurrentCulture.ClearCachedData();
- CultureInfo.CurrentUICulture.ClearCachedData();
- }
- }
-}