aboutsummaryrefslogtreecommitdiff
path: root/Timeline.Tests/Helpers
diff options
context:
space:
mode:
author杨宇千 <crupest@outlook.com>2020-02-01 00:26:35 +0800
committerGitHub <noreply@github.com>2020-02-01 00:26:35 +0800
commitd703269e06d4c9e254fe2d5589ff04cdd6a9b366 (patch)
treef02f8d57440c777d4732bc4439f82e8b25c6732c /Timeline.Tests/Helpers
parent631731e5c2253116a53fdc435afca184251a34fc (diff)
parentbddf1d6eaac782672071df6527c40c81c3123f3a (diff)
downloadtimeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.tar.gz
timeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.tar.bz2
timeline-d703269e06d4c9e254fe2d5589ff04cdd6a9b366.zip
Merge pull request #56 from crupest/dev
Refactor API to be RESTful.
Diffstat (limited to 'Timeline.Tests/Helpers')
-rw-r--r--Timeline.Tests/Helpers/MockUser.cs24
-rw-r--r--Timeline.Tests/Helpers/ParameterInfoAssertions.cs3
-rw-r--r--Timeline.Tests/Helpers/PrincipalHelper.cs23
-rw-r--r--Timeline.Tests/Helpers/ResponseAssertions.cs12
-rw-r--r--Timeline.Tests/Helpers/TestApplication.cs23
-rw-r--r--Timeline.Tests/Helpers/TestClock.cs15
-rw-r--r--Timeline.Tests/Helpers/TestDatabase.cs89
-rw-r--r--Timeline.Tests/Helpers/UseCultureAttribute.cs94
8 files changed, 29 insertions, 254 deletions
diff --git a/Timeline.Tests/Helpers/MockUser.cs b/Timeline.Tests/Helpers/MockUser.cs
deleted file mode 100644
index 8d738525..00000000
--- a/Timeline.Tests/Helpers/MockUser.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.Collections.Generic;
-using Timeline.Models;
-
-namespace Timeline.Tests.Helpers
-{
- public class MockUser
- {
- public MockUser(string username, string password, bool administrator)
- {
- Info = new UserInfo(username, administrator);
- Password = password;
- }
-
- public UserInfo 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<UserInfo> UserInfoList { get; } = new List<UserInfo> { User.Info, Admin.Info };
- }
-}
diff --git a/Timeline.Tests/Helpers/ParameterInfoAssertions.cs b/Timeline.Tests/Helpers/ParameterInfoAssertions.cs
index e3becee1..d3e5a41e 100644
--- a/Timeline.Tests/Helpers/ParameterInfoAssertions.cs
+++ b/Timeline.Tests/Helpers/ParameterInfoAssertions.cs
@@ -3,10 +3,7 @@ using FluentAssertions.Execution;
using FluentAssertions.Formatting;
using FluentAssertions.Primitives;
using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Reflection;
-using System.Threading.Tasks;
namespace Timeline.Tests.Helpers
{
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 301ceef6..f01a0677 100644
--- a/Timeline.Tests/Helpers/ResponseAssertions.cs
+++ b/Timeline.Tests/Helpers/ResponseAssertions.cs
@@ -3,6 +3,7 @@ using FluentAssertions.Execution;
using FluentAssertions.Formatting;
using FluentAssertions.Primitives;
using System;
+using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Text;
@@ -124,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);
@@ -152,9 +160,9 @@ namespace Timeline.Tests.Helpers
message = string.IsNullOrEmpty(message) ? "" : ", " + message;
assertions.HaveStatusCode(400, "Invalid Model Error must have 400 status code{0}", message)
.And.HaveCommonBody("Invalid Model Error must have CommonResponse body{0}", message)
- .Which.Code.Should().Be(ErrorCodes.Http.Common.InvalidModel,
+ .Which.Code.Should().Be(ErrorCodes.Common.InvalidModel,
"Invalid Model Error must have code {0} in body{1}",
- ErrorCodes.Http.Common.InvalidModel, message);
+ ErrorCodes.Common.InvalidModel, message);
}
}
}
diff --git a/Timeline.Tests/Helpers/TestApplication.cs b/Timeline.Tests/Helpers/TestApplication.cs
index d18f2848..bc5deeec 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,31 @@ 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:;");
+ DatabaseConnection.Open();
+
+ var options = new DbContextOptionsBuilder<DevelopmentDatabaseContext>()
+ .UseSqlite(DatabaseConnection)
+ .Options;
+
+ using (var context = new DevelopmentDatabaseContext(options))
+ {
+ context.Database.EnsureCreated();
+ }
+
Factory = factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
- services.AddEntityFrameworkSqlite();
services.AddDbContext<DatabaseContext, DevelopmentDatabaseContext>(options =>
{
- options.UseSqlite(Database.Connection);
+ options.UseSqlite(DatabaseConnection);
});
});
});
@@ -28,7 +42,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 9560f353..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 User CreateEntityFromMock(MockUser user)
- {
- return new User
- {
- Name = user.Username,
- EncryptedPassword = PasswordService.HashPassword(user.Password),
- RoleString = UserRoleConvert.ToString(user.Administrator),
- Avatar = null
- };
- }
-
- private static IEnumerable<User> 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();
- }
- }
-}