diff options
author | 杨宇千 <crupest@outlook.com> | 2019-08-04 21:35:04 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-04 21:35:04 +0800 |
commit | ebda3fc381ee4ed9f729fa85c1cee837ce4c5c3b (patch) | |
tree | d1c9c7b51353b67b47bb4cd89aa82754ef0a1234 /Timeline.Tests | |
parent | 85d25348c9d6ad527b86c57fd5023829c8b9d6bf (diff) | |
parent | 2a32e03a384a30b14988b0b6e40db845f4a5444e (diff) | |
download | timeline-ebda3fc381ee4ed9f729fa85c1cee837ce4c5c3b.tar.gz timeline-ebda3fc381ee4ed9f729fa85c1cee837ce4c5c3b.tar.bz2 timeline-ebda3fc381ee4ed9f729fa85c1cee837ce4c5c3b.zip |
Merge pull request #34 from crupest/token-time
Set token expired time and write unit tests.
Diffstat (limited to 'Timeline.Tests')
-rw-r--r-- | Timeline.Tests/AuthorizationUnitTest.cs | 13 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs | 16 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/MyWebApplicationFactory.cs | 83 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/ResponseExtensions.cs | 14 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/TestClock.cs | 25 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/TestUsers.cs | 8 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/UserInfoComparers.cs | 2 | ||||
-rw-r--r-- | Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs | 53 | ||||
-rw-r--r-- | Timeline.Tests/JwtTokenUnitTest.cs | 75 | ||||
-rw-r--r-- | Timeline.Tests/Timeline.Tests.csproj | 45 | ||||
-rw-r--r-- | Timeline.Tests/TokenUnitTest.cs | 163 | ||||
-rw-r--r-- | Timeline.Tests/UserUnitTest.cs | 6 |
12 files changed, 324 insertions, 179 deletions
diff --git a/Timeline.Tests/AuthorizationUnitTest.cs b/Timeline.Tests/AuthorizationUnitTest.cs index ee3deac8..a25a8f9b 100644 --- a/Timeline.Tests/AuthorizationUnitTest.cs +++ b/Timeline.Tests/AuthorizationUnitTest.cs @@ -8,7 +8,7 @@ using Xunit.Abstractions; namespace Timeline.Tests { - public class AuthorizationUnitTest : IClassFixture<WebApplicationFactory<Startup>> + public class AuthorizationUnitTest : IClassFixture<MyWebApplicationFactory<Startup>> { private const string AuthorizeUrl = "Test/User/Authorize"; private const string UserUrl = "Test/User/User"; @@ -16,9 +16,9 @@ namespace Timeline.Tests private readonly WebApplicationFactory<Startup> _factory; - public AuthorizationUnitTest(WebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper) + public AuthorizationUnitTest(MyWebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper) { - _factory = factory.WithTestConfig(outputHelper); + _factory = factory.WithTestLogging(outputHelper); } [Fact] @@ -44,12 +44,11 @@ namespace Timeline.Tests [Fact] public async Task UserAuthorizationTest() { - using (var client = _factory.CreateDefaultClient()) + using (var client = await _factory.CreateClientWithUser("user", "user")) { - var token = (await client.CreateUserTokenAsync("user", "user")).Token; - var response1 = await client.SendWithAuthenticationAsync(token, UserUrl); + var response1 = await client.GetAsync(UserUrl); Assert.Equal(HttpStatusCode.OK, response1.StatusCode); - var response2 = await client.SendWithAuthenticationAsync(token, AdminUrl); + var response2 = await client.GetAsync(AdminUrl); Assert.Equal(HttpStatusCode.Forbidden, response2.StatusCode); } } diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs index f4e2e45a..27362ac3 100644 --- a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs +++ b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc.Testing; using Newtonsoft.Json; -using System; using System.Net.Http; using System.Threading.Tasks; using Timeline.Entities.Http; @@ -11,9 +10,9 @@ namespace Timeline.Tests.Helpers.Authentication { private const string CreateTokenUrl = "/token/create"; - public static async Task<CreateTokenResponse> CreateUserTokenAsync(this HttpClient client, string username, string password) + public static async Task<CreateTokenResponse> CreateUserTokenAsync(this HttpClient client, string username, string password, double? expireOffset = null) { - var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password }); + var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password, ExpireOffset = expireOffset }); var result = JsonConvert.DeserializeObject<CreateTokenResponse>(await response.Content.ReadAsStringAsync()); return result; } @@ -25,16 +24,5 @@ namespace Timeline.Tests.Helpers.Authentication client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); return client; } - - public static async Task<HttpResponseMessage> SendWithAuthenticationAsync(this HttpClient client, string token, string path, Action<HttpRequestMessage> requestBuilder = null) - { - var request = new HttpRequestMessage - { - RequestUri = new Uri(client.BaseAddress, path), - }; - request.Headers.Add("Authorization", "Bearer " + token); - requestBuilder?.Invoke(request); - return await client.SendAsync(request); - } } } diff --git a/Timeline.Tests/Helpers/MyWebApplicationFactory.cs b/Timeline.Tests/Helpers/MyWebApplicationFactory.cs new file mode 100644 index 00000000..903cd670 --- /dev/null +++ b/Timeline.Tests/Helpers/MyWebApplicationFactory.cs @@ -0,0 +1,83 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Timeline.Models; +using Timeline.Services;
+using Xunit.Abstractions; + +namespace Timeline.Tests.Helpers +{ + public class MyWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
+ {
+ // We should keep the connection, so the database is persisted but not recreate every time.
+ // See https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite#writing-tests .
+ private readonly SqliteConnection _databaseConnection;
+
+ public MyWebApplicationFactory() : base()
+ {
+ _databaseConnection = new SqliteConnection("Data Source=:memory:;");
+ _databaseConnection.Open();
+
+ InitDatabase();
+ }
+
+ private void InitDatabase()
+ {
+ var options = new DbContextOptionsBuilder<DatabaseContext>()
+ .UseSqlite(_databaseConnection)
+ .Options;
+
+ using (var context = new DatabaseContext(options))
+ {
+ context.Database.EnsureCreated();
+ context.Users.AddRange(TestMockUsers.MockUsers);
+ context.SaveChanges();
+ }
+ }
+
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ builder.ConfigureServices(services =>
+ {
+ services.AddEntityFrameworkSqlite();
+ services.AddDbContext<DatabaseContext>(options =>
+ {
+ options.UseSqlite(_databaseConnection);
+ });
+ })
+ .ConfigureTestServices(services =>
+ {
+ services.AddSingleton<IClock, TestClock>();
+ });
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _databaseConnection.Close();
+ _databaseConnection.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+ } + + public static class WebApplicationFactoryExtensions + { + public static WebApplicationFactory<TEntry> WithTestLogging<TEntry>(this WebApplicationFactory<TEntry> factory, ITestOutputHelper outputHelper) where TEntry : class + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureLogging(logging =>
+ {
+ logging.AddXunit(outputHelper);
+ }); + }); + } + } +} diff --git a/Timeline.Tests/Helpers/ResponseExtensions.cs b/Timeline.Tests/Helpers/ResponseExtensions.cs new file mode 100644 index 00000000..86ac1c88 --- /dev/null +++ b/Timeline.Tests/Helpers/ResponseExtensions.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; +using System.Net.Http; +using System.Threading.Tasks; + +namespace Timeline.Tests.Helpers +{ + public static class ResponseExtensions + { + public static async Task<T> ReadBodyAsJson<T>(this HttpResponseMessage response) + { + return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync()); + } + } +} diff --git a/Timeline.Tests/Helpers/TestClock.cs b/Timeline.Tests/Helpers/TestClock.cs new file mode 100644 index 00000000..91523f2b --- /dev/null +++ b/Timeline.Tests/Helpers/TestClock.cs @@ -0,0 +1,25 @@ +using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.DependencyInjection;
+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);
+ }
+ }
+
+ public static class TestClockWebApplicationFactoryExtensions
+ {
+ public static TestClock GetTestClock<T>(this WebApplicationFactory<T> factory) where T : class
+ {
+ return factory.Server.Host.Services.GetRequiredService<IClock>() as TestClock;
+ }
+ }
+}
diff --git a/Timeline.Tests/Helpers/TestUsers.cs b/Timeline.Tests/Helpers/TestUsers.cs index dd00e38d..41dd83a9 100644 --- a/Timeline.Tests/Helpers/TestUsers.cs +++ b/Timeline.Tests/Helpers/TestUsers.cs @@ -11,19 +11,21 @@ namespace Timeline.Tests.Helpers static TestMockUsers() { var mockUsers = new List<User>(); - var passwordService = new PasswordService(null); + var passwordService = new PasswordService(); mockUsers.Add(new User { Name = "user", EncryptedPassword = passwordService.HashPassword("user"), - RoleString = "user" + RoleString = UserUtility.IsAdminToRoleString(false), + Version = 0, }); mockUsers.Add(new User { Name = "admin", EncryptedPassword = passwordService.HashPassword("admin"), - RoleString = "user,admin" + RoleString = UserUtility.IsAdminToRoleString(true), + Version = 0, }); MockUsers = mockUsers; diff --git a/Timeline.Tests/Helpers/UserInfoComparers.cs b/Timeline.Tests/Helpers/UserInfoComparers.cs index 0d91efe3..fcf37e5c 100644 --- a/Timeline.Tests/Helpers/UserInfoComparers.cs +++ b/Timeline.Tests/Helpers/UserInfoComparers.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; using Timeline.Entities; namespace Timeline.Tests.Helpers diff --git a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs b/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs deleted file mode 100644 index a7616b41..00000000 --- a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Timeline.Models; -using Xunit.Abstractions; - -namespace Timeline.Tests.Helpers -{ - public static class WebApplicationFactoryExtensions - { - public static WebApplicationFactory<TEntry> WithTestConfig<TEntry>(this WebApplicationFactory<TEntry> factory, ITestOutputHelper outputHelper) where TEntry : class - { - return factory.WithWebHostBuilder(builder => - { - builder - .ConfigureLogging(logging => - { - logging.AddXunit(outputHelper); - }) - .ConfigureServices(services => - { - var serviceProvider = new ServiceCollection() - .AddEntityFrameworkInMemoryDatabase() - .BuildServiceProvider(); - - services.AddDbContext<DatabaseContext>(options => - { - options.UseInMemoryDatabase("timeline"); - options.UseInternalServiceProvider(serviceProvider); - }); - - var sp = services.BuildServiceProvider(); - - // Create a scope to obtain a reference to the database - // context (ApplicationDbContext). - using (var scope = sp.CreateScope()) - { - var scopedServices = scope.ServiceProvider; - var db = scopedServices.GetRequiredService<DatabaseContext>(); - - // Ensure the database is created. - db.Database.EnsureCreated(); - - db.Users.AddRange(TestMockUsers.MockUsers); - db.SaveChanges(); - } - }); - }); - } - } -} diff --git a/Timeline.Tests/JwtTokenUnitTest.cs b/Timeline.Tests/JwtTokenUnitTest.cs deleted file mode 100644 index 6c0d4213..00000000 --- a/Timeline.Tests/JwtTokenUnitTest.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Testing; -using Newtonsoft.Json; -using System.Net; -using System.Net.Http; -using Timeline.Entities.Http; -using Timeline.Tests.Helpers; -using Timeline.Tests.Helpers.Authentication; -using Xunit; -using Xunit.Abstractions; - -namespace Timeline.Tests -{ - public class JwtTokenUnitTest : IClassFixture<WebApplicationFactory<Startup>> - { - private const string CreateTokenUrl = "token/create"; - private const string VerifyTokenUrl = "token/verify"; - - private readonly WebApplicationFactory<Startup> _factory; - - public JwtTokenUnitTest(WebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper) - { - _factory = factory.WithTestConfig(outputHelper); - } - - [Fact] - public async void CreateTokenTest_BadCredential() - { - using (var client = _factory.CreateDefaultClient()) - { - var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "???", Password = "???" }); - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } - } - - [Fact] - public async void CreateTokenTest_GoodCredential() - { - using (var client = _factory.CreateDefaultClient()) - { - var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "user", Password = "user" }); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var result = JsonConvert.DeserializeObject<CreateTokenResponse>(await response.Content.ReadAsStringAsync()); - Assert.NotNull(result.Token); - Assert.NotNull(result.User); - } - } - - [Fact] - public async void VerifyTokenTest_BadToken() - { - using (var client = _factory.CreateDefaultClient()) - { - var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = "bad token hahaha" }); - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } - } - - [Fact] - public async void VerifyTokenTest_GoodToken() - { - using (var client = _factory.CreateDefaultClient()) - { - var createTokenResult = await client.CreateUserTokenAsync("admin", "admin"); - - var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = createTokenResult.Token }); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - var result = JsonConvert.DeserializeObject<VerifyTokenResponse>(await response.Content.ReadAsStringAsync()); - Assert.NotNull(result.User); - Assert.Equal(createTokenResult.User.Username, result.User.Username); - Assert.Equal(createTokenResult.User.Administrator, result.User.Administrator); - } - } - } -} diff --git a/Timeline.Tests/Timeline.Tests.csproj b/Timeline.Tests/Timeline.Tests.csproj index 820737cc..1a5f2850 100644 --- a/Timeline.Tests/Timeline.Tests.csproj +++ b/Timeline.Tests/Timeline.Tests.csproj @@ -1,22 +1,23 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>netcoreapp2.2</TargetFramework> - </PropertyGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.AspNetCore.App" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.2.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Testing" Version="2.2.0-rtm-35646" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" /> - <PackageReference Include="xunit" Version="2.4.1" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1"> - <PrivateAssets>all</PrivateAssets> - <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> - </PackageReference> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\Timeline\Timeline.csproj" /> - </ItemGroup> -</Project> +<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <TargetFramework>netcoreapp2.2</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.AspNetCore.App" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.2.0" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.6" />
+ <PackageReference Include="Microsoft.Extensions.Logging.Testing" Version="2.2.0-rtm-35646" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Timeline\Timeline.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Timeline.Tests/TokenUnitTest.cs b/Timeline.Tests/TokenUnitTest.cs new file mode 100644 index 00000000..7b83cd13 --- /dev/null +++ b/Timeline.Tests/TokenUnitTest.cs @@ -0,0 +1,163 @@ +using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.DependencyInjection;
+using Newtonsoft.Json;
+using System;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using Timeline.Controllers;
+using Timeline.Entities.Http;
+using Timeline.Services;
+using Timeline.Tests.Helpers;
+using Timeline.Tests.Helpers.Authentication;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Timeline.Tests
+{
+ public class TokenUnitTest : IClassFixture<MyWebApplicationFactory<Startup>>
+ {
+ private const string CreateTokenUrl = "token/create";
+ private const string VerifyTokenUrl = "token/verify";
+
+ private readonly WebApplicationFactory<Startup> _factory;
+
+ public TokenUnitTest(MyWebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper)
+ {
+ _factory = factory.WithTestLogging(outputHelper);
+ }
+
+ [Fact]
+ public async void CreateTokenTest_UserNotExist()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "usernotexist", Password = "???" });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Create_UserNotExist, body.Code);
+ }
+ }
+
+ [Fact]
+ public async void CreateTokenTest_BadPassword()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "user", Password = "???" });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Create_BadPassword, body.Code);
+ }
+ }
+
+ [Fact]
+ public async void CreateTokenTest_BadExpireOffset()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "???", Password = "???", ExpireOffset = -1000 });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Create_BadExpireOffset, body.Code);
+ }
+ }
+
+ [Fact]
+ public async void CreateTokenTest_Success()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = "user", Password = "user" });
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CreateTokenResponse>();
+ Assert.NotEmpty(body.Token);
+ Assert.Equal(TestMockUsers.MockUserInfos.Where(u => u.Username == "user").Single(), body.User, UserInfoComparers.EqualityComparer);
+ }
+ }
+
+ [Fact]
+ public async void VerifyTokenTest_BadToken()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = "bad token hahaha" });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Verify_BadToken, body.Code);
+ }
+ }
+
+ [Fact]
+ public async void VerifyTokenTest_BadVersion_AND_UserNotExist()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ using (var scope = _factory.Server.Host.Services.CreateScope()) // UserService is scoped.
+ {
+ // create a user for test
+ var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
+
+ const string username = "verifytokentest0";
+ const string password = "12345678";
+
+ await userService.PutUser(username, password, false);
+
+ // create a token
+ var token = (await client.CreateUserTokenAsync(username, password)).Token;
+
+ // increase version
+ await userService.PatchUser(username, null, null);
+
+ // test against bad version
+ var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = token });
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Verify_BadVersion, body.Code);
+
+ // create another token
+ var token2 = (await client.CreateUserTokenAsync(username, password)).Token;
+
+ // delete user
+ await userService.DeleteUser(username);
+
+ // test against user not exist
+ var response2 = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = token });
+ Assert.Equal(HttpStatusCode.BadRequest, response2.StatusCode);
+ var body2 = await response2.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Verify_UserNotExist, body2.Code);
+ }
+ }
+ }
+
+ [Fact]
+ public async void VerifyTokenTest_Expired()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ // I can only control the token expired time but not current time
+ // because verify logic is encapsuled in other library.
+ var mockClock = _factory.GetTestClock();
+ mockClock.MockCurrentTime = DateTime.Now - TimeSpan.FromDays(2);
+ var token = (await client.CreateUserTokenAsync("user", "user", 1)).Token;
+ var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = token });
+ var body = await response.ReadBodyAsJson<CommonResponse>();
+ Assert.Equal(TokenController.ErrorCodes.Verify_Expired, body.Code);
+ mockClock.MockCurrentTime = null;
+ }
+ }
+
+ [Fact]
+ public async void VerifyTokenTest_Success()
+ {
+ using (var client = _factory.CreateDefaultClient())
+ {
+ var createTokenResult = await client.CreateUserTokenAsync("user", "user");
+ var response = await client.PostAsJsonAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = createTokenResult.Token });
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var body = JsonConvert.DeserializeObject<VerifyTokenResponse>(await response.Content.ReadAsStringAsync());
+ Assert.Equal(TestMockUsers.MockUserInfos.Where(u => u.Username == "user").Single(), body.User, UserInfoComparers.EqualityComparer);
+ }
+ }
+ }
+}
diff --git a/Timeline.Tests/UserUnitTest.cs b/Timeline.Tests/UserUnitTest.cs index a4b4dace..b3377f7b 100644 --- a/Timeline.Tests/UserUnitTest.cs +++ b/Timeline.Tests/UserUnitTest.cs @@ -11,13 +11,13 @@ using Xunit.Abstractions; namespace Timeline.Tests { - public class UserUnitTest : IClassFixture<WebApplicationFactory<Startup>> + public class UserUnitTest : IClassFixture<MyWebApplicationFactory<Startup>> { private readonly WebApplicationFactory<Startup> _factory; - public UserUnitTest(WebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper) + public UserUnitTest(MyWebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper) { - _factory = factory.WithTestConfig(outputHelper); + _factory = factory.WithTestLogging(outputHelper); } [Fact] |