From c9cc1e18fb36df25ad28778c26e4b2bd88b6a96d Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Sun, 20 Oct 2019 16:24:11 +0800 Subject: ... --- Timeline.Tests/GlobalSuppressions.cs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Timeline.Tests/GlobalSuppressions.cs (limited to 'Timeline.Tests/GlobalSuppressions.cs') diff --git a/Timeline.Tests/GlobalSuppressions.cs b/Timeline.Tests/GlobalSuppressions.cs new file mode 100644 index 00000000..6562efbb --- /dev/null +++ b/Timeline.Tests/GlobalSuppressions.cs @@ -0,0 +1,9 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "This is not a UI application.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Tests name have underscores.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1063:Implement IDisposable Correctly", Justification = "Test classes do not need to implement it that way.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA1816:Dispose methods should call SuppressFinalize", Justification = "Test classes do not need to implement it that way.")] -- cgit v1.2.3 From 5e64e3385ae8eb9b877c032418da9e5086d50a06 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Mon, 21 Oct 2019 13:41:46 +0800 Subject: ... --- Timeline.Tests/Controllers/TokenControllerTest.cs | 13 +-- Timeline.Tests/Controllers/UserControllerTest.cs | 109 +++++++++++++++++++++ Timeline.Tests/GlobalSuppressions.cs | 5 + .../Helpers/AssertionResponseExtensions.cs | 46 +++------ Timeline.Tests/Helpers/HttpClientExtensions.cs | 13 +++ Timeline.Tests/Helpers/ImageHelper.cs | 24 ++--- Timeline.Tests/IntegratedTests/UserUnitTest.cs | 22 ++--- .../Mock/Services/MockStringLocalizer.cs | 31 ------ .../Mock/Services/TestStringLocalizerFactory.cs | 25 +++++ Timeline/Controllers/TokenController.cs | 4 +- Timeline/Controllers/UserController.cs | 39 ++++---- Timeline/Models/Http/Common.cs | 42 ++++++-- .../Resources/Controllers/UserController.en.resx | 9 ++ Timeline/Resources/Controllers/UserController.resx | 15 +++ .../Resources/Controllers/UserController.zh.resx | 9 ++ 15 files changed, 281 insertions(+), 125 deletions(-) create mode 100644 Timeline.Tests/Controllers/UserControllerTest.cs delete mode 100644 Timeline.Tests/Mock/Services/MockStringLocalizer.cs create mode 100644 Timeline.Tests/Mock/Services/TestStringLocalizerFactory.cs (limited to 'Timeline.Tests/GlobalSuppressions.cs') diff --git a/Timeline.Tests/Controllers/TokenControllerTest.cs b/Timeline.Tests/Controllers/TokenControllerTest.cs index 86a241e5..71520e77 100644 --- a/Timeline.Tests/Controllers/TokenControllerTest.cs +++ b/Timeline.Tests/Controllers/TokenControllerTest.cs @@ -20,13 +20,14 @@ namespace Timeline.Tests.Controllers private readonly Mock _mockUserService = new Mock(); private readonly TestClock _mockClock = new TestClock(); + private readonly TokenController _controller; public TokenControllerTest() { _controller = new TokenController(_mockUserService.Object, NullLogger.Instance, _mockClock, - new MockStringLocalizer()); + TestStringLocalizerFactory.Create().Create()); } public void Dispose() @@ -53,7 +54,7 @@ namespace Timeline.Tests.Controllers Password = "p", Expire = expire }); - action.Should().BeAssignableTo() + action.Result.Should().BeAssignableTo() .Which.Value.Should().BeEquivalentTo(createResult); } @@ -67,7 +68,7 @@ namespace Timeline.Tests.Controllers Password = "p", Expire = null }); - action.Should().BeAssignableTo() + action.Result.Should().BeAssignableTo() .Which.Value.Should().BeAssignableTo() .Which.Code.Should().Be(Create.BadCredential); } @@ -82,7 +83,7 @@ namespace Timeline.Tests.Controllers Password = "p", Expire = null }); - action.Should().BeAssignableTo() + action.Result.Should().BeAssignableTo() .Which.Value.Should().BeAssignableTo() .Which.Code.Should().Be(Create.BadCredential); } @@ -93,7 +94,7 @@ namespace Timeline.Tests.Controllers const string token = "aaaaaaaaaaaaaa"; _mockUserService.Setup(s => s.VerifyToken(token)).ReturnsAsync(MockUser.User.Info); var action = await _controller.Verify(new VerifyTokenRequest { Token = token }); - action.Should().BeAssignableTo() + action.Result.Should().BeAssignableTo() .Which.Value.Should().BeAssignableTo() .Which.User.Should().BeEquivalentTo(MockUser.User.Info); } @@ -113,7 +114,7 @@ namespace Timeline.Tests.Controllers const string token = "aaaaaaaaaaaaaa"; _mockUserService.Setup(s => s.VerifyToken(token)).ThrowsAsync(e); var action = await _controller.Verify(new VerifyTokenRequest { Token = token }); - action.Should().BeAssignableTo() + action.Result.Should().BeAssignableTo() .Which.Value.Should().BeAssignableTo() .Which.Code.Should().Be(code); } diff --git a/Timeline.Tests/Controllers/UserControllerTest.cs b/Timeline.Tests/Controllers/UserControllerTest.cs new file mode 100644 index 00000000..9fec477f --- /dev/null +++ b/Timeline.Tests/Controllers/UserControllerTest.cs @@ -0,0 +1,109 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using System; +using System.Linq; +using System.Threading.Tasks; +using Timeline.Controllers; +using Timeline.Models; +using Timeline.Models.Http; +using Timeline.Services; +using Timeline.Tests.Helpers; +using Timeline.Tests.Mock.Data; +using Timeline.Tests.Mock.Services; +using Xunit; +using static Timeline.ErrorCodes.Http.User; + +namespace Timeline.Tests.Controllers +{ + public class UserControllerTest : IDisposable + { + private readonly Mock _mockUserService = new Mock(); + + private readonly UserController _controller; + + public UserControllerTest() + { + _controller = new UserController(NullLogger.Instance, + _mockUserService.Object, + TestStringLocalizerFactory.Create()); + } + + public void Dispose() + { + _controller.Dispose(); + } + + [Fact] + public async Task GetList_Success() + { + var array = MockUser.UserInfoList.ToArray(); + _mockUserService.Setup(s => s.ListUsers()).ReturnsAsync(array); + var action = await _controller.List(); + action.Result.Should().BeAssignableTo() + .Which.Value.Should().BeEquivalentTo(array); + } + + [Fact] + public async Task Get_Success() + { + const string username = "aaa"; + _mockUserService.Setup(s => s.GetUser(username)).ReturnsAsync(MockUser.User.Info); + var action = await _controller.Get(username); + action.Result.Should().BeAssignableTo() + .Which.Value.Should().BeEquivalentTo(MockUser.User.Info); + } + + [Fact] + public async Task Get_NotFound() + { + const string username = "aaa"; + _mockUserService.Setup(s => s.GetUser(username)).Returns(Task.FromResult(null)); + var action = await _controller.Get(username); + action.Result.Should().BeAssignableTo() + .Which.Value.Should().BeAssignableTo() + .Which.Code.Should().Be(Get.NotExist); + } + + [Theory] + [InlineData(PutResult.Created, true)] + [InlineData(PutResult.Modified, false)] + public async Task Put_Success(PutResult result, bool create) + { + const string username = "aaa"; + const string password = "ppp"; + const bool administrator = true; + _mockUserService.Setup(s => s.PutUser(username, password, administrator)).ReturnsAsync(result); + var action = await _controller.Put(new UserPutRequest + { + Password = password, + Administrator = administrator + }, username); + var response = action.Result.Should().BeAssignableTo() + .Which.Value.Should().BeAssignableTo() + .Which; + response.Code.Should().Be(0); + response.Data.Create.Should().Be(create); + } + + [Fact] + public async Task Put_BadUsername() + { + const string username = "aaa"; + const string password = "ppp"; + const bool administrator = true; + _mockUserService.Setup(s => s.PutUser(username, password, administrator)).ThrowsAsync(new UsernameBadFormatException()); + var action = await _controller.Put(new UserPutRequest + { + Password = password, + Administrator = administrator + }, username); + action.Result.Should().BeAssignableTo() + .Which.Value.Should().BeAssignableTo() + .Which.Code.Should().Be(Put.BadUsername); + } + + //TODO! Complete this. + } +} diff --git a/Timeline.Tests/GlobalSuppressions.cs b/Timeline.Tests/GlobalSuppressions.cs index 6562efbb..2191a5c4 100644 --- a/Timeline.Tests/GlobalSuppressions.cs +++ b/Timeline.Tests/GlobalSuppressions.cs @@ -5,5 +5,10 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "This is not a UI application.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Tests name have underscores.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Test classes can be nested.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "This is redundant.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1063:Implement IDisposable Correctly", Justification = "Test classes do not need to implement it that way.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA1816:Dispose methods should call SuppressFinalize", Justification = "Test classes do not need to implement it that way.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2234:Pass system uri objects instead of strings", Justification = "I really don't understand this rule.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Tests do not need make strings resources.")] + diff --git a/Timeline.Tests/Helpers/AssertionResponseExtensions.cs b/Timeline.Tests/Helpers/AssertionResponseExtensions.cs index 5ce025ee..08f10b2b 100644 --- a/Timeline.Tests/Helpers/AssertionResponseExtensions.cs +++ b/Timeline.Tests/Helpers/AssertionResponseExtensions.cs @@ -82,22 +82,14 @@ namespace Timeline.Tests.Helpers { body = Subject.Content.ReadAsStringAsync().Result; } - catch (Exception e) + catch (AggregateException e) { - a.FailWith("Expected response body of {context:HttpResponseMessage} to be json string{reason}, but failed to read it or it was not a string. Exception is {0}.", e); + a.FailWith("Expected response body of {context:HttpResponseMessage} to be json string{reason}, but failed to read it or it was not a string. Exception is {0}.", e.InnerExceptions); return new AndWhichConstraint(Subject, null); } - try - { - var result = JsonConvert.DeserializeObject(body); - return new AndWhichConstraint(Subject, result); - } - catch (Exception e) - { - a.FailWith("Expected response body of {context:HttpResponseMessage} to be able to convert to {0} instance{reason}, but failed. Exception is {1}.", typeof(T).FullName, e); - return new AndWhichConstraint(Subject, null); - } + var result = JsonConvert.DeserializeObject(body); + return new AndWhichConstraint(Subject, result); } } @@ -118,28 +110,22 @@ namespace Timeline.Tests.Helpers return assertions.HaveJsonBody>(because, becauseArgs); } - public static void BePutCreate(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs) - { - assertions.HaveStatusCode(201, because, becauseArgs) - .And.Should().HaveCommonDataBody(because, becauseArgs).Which.Should().BeEquivalentTo(CommonPutResponse.Create(), because, becauseArgs); - } - - public static void BePutModify(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs) - { - assertions.HaveStatusCode(200, because, becauseArgs) - .And.Should().HaveCommonDataBody(because, becauseArgs).Which.Should().BeEquivalentTo(CommonPutResponse.Modify(), because, becauseArgs); - } - - public static void BeDeleteDelete(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs) + public static void BePut(this HttpResponseMessageAssertions assertions, bool create, string because = "", params object[] becauseArgs) { - assertions.HaveStatusCode(200, because, becauseArgs) - .And.Should().HaveCommonDataBody(because, becauseArgs).Which.Should().BeEquivalentTo(CommonDeleteResponse.Delete(), because, becauseArgs); + var body = assertions.HaveStatusCode(create ? 201 : 200, because, becauseArgs) + .And.Should().HaveJsonBody(because, becauseArgs) + .Which; + body.Code.Should().Be(0); + body.Data.Create.Should().Be(create); } - public static void BeDeleteNotExist(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs) + public static void BeDelete(this HttpResponseMessageAssertions assertions, bool delete, string because = "", params object[] becauseArgs) { - assertions.HaveStatusCode(200, because, becauseArgs) - .And.Should().HaveCommonDataBody(because, becauseArgs).Which.Should().BeEquivalentTo(CommonDeleteResponse.NotExist(), because, becauseArgs); + var body = assertions.HaveStatusCode(200, because, becauseArgs) + .And.Should().HaveJsonBody(because, becauseArgs) + .Which; + body.Code.Should().Be(0); + body.Data.Delete.Should().Be(delete); } public static void BeInvalidModel(this HttpResponseMessageAssertions assertions, string message = null) diff --git a/Timeline.Tests/Helpers/HttpClientExtensions.cs b/Timeline.Tests/Helpers/HttpClientExtensions.cs index e3beea1d..38641f90 100644 --- a/Timeline.Tests/Helpers/HttpClientExtensions.cs +++ b/Timeline.Tests/Helpers/HttpClientExtensions.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; @@ -10,12 +11,24 @@ namespace Timeline.Tests.Helpers public static class HttpClientExtensions { public static Task PatchAsJsonAsync(this HttpClient client, string url, T body) + { + return client.PatchAsJsonAsync(new Uri(url, UriKind.RelativeOrAbsolute), body); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public static Task PatchAsJsonAsync(this HttpClient client, Uri url, T body) { return client.PatchAsync(url, new StringContent( JsonConvert.SerializeObject(body), Encoding.UTF8, MediaTypeNames.Application.Json)); } public static Task PutByteArrayAsync(this HttpClient client, string url, byte[] body, string mimeType) + { + return client.PutByteArrayAsync(new Uri(url, UriKind.RelativeOrAbsolute), body, mimeType); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public static Task PutByteArrayAsync(this HttpClient client, Uri url, byte[] body, string mimeType) { var content = new ByteArrayContent(body); content.Headers.ContentLength = body.Length; diff --git a/Timeline.Tests/Helpers/ImageHelper.cs b/Timeline.Tests/Helpers/ImageHelper.cs index 2a2f3870..9bed0917 100644 --- a/Timeline.Tests/Helpers/ImageHelper.cs +++ b/Timeline.Tests/Helpers/ImageHelper.cs @@ -9,26 +9,18 @@ namespace Timeline.Tests.Helpers { public static byte[] CreatePngWithSize(int width, int height) { - using (var image = new Image(width, height)) - { - using (var stream = new MemoryStream()) - { - image.SaveAsPng(stream); - return stream.ToArray(); - } - } + using var image = new Image(width, height); + using var stream = new MemoryStream(); + image.SaveAsPng(stream); + return stream.ToArray(); } public static byte[] CreateImageWithSize(int width, int height, IImageFormat format) { - using (var image = new Image(width, height)) - { - using (var stream = new MemoryStream()) - { - image.Save(stream, format); - return stream.ToArray(); - } - } + using var image = new Image(width, height); + using var stream = new MemoryStream(); + image.Save(stream, format); + return stream.ToArray(); } } } diff --git a/Timeline.Tests/IntegratedTests/UserUnitTest.cs b/Timeline.Tests/IntegratedTests/UserUnitTest.cs index b2aab24c..47a8699c 100644 --- a/Timeline.Tests/IntegratedTests/UserUnitTest.cs +++ b/Timeline.Tests/IntegratedTests/UserUnitTest.cs @@ -4,13 +4,13 @@ using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using Timeline.Controllers; using Timeline.Models; using Timeline.Models.Http; using Timeline.Tests.Helpers; using Timeline.Tests.Helpers.Authentication; using Timeline.Tests.Mock.Data; using Xunit; +using static Timeline.ErrorCodes.Http.User; namespace Timeline.Tests.IntegratedTests { @@ -57,7 +57,7 @@ namespace Timeline.Tests.IntegratedTests var res = await client.GetAsync("users/usernotexist"); res.Should().HaveStatusCode(404) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.Get_NotExist); + .Which.Code.Should().Be(Get.NotExist); } public static IEnumerable Put_InvalidModel_Data() @@ -88,7 +88,7 @@ namespace Timeline.Tests.IntegratedTests }); res.Should().HaveStatusCode(400) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.Put_BadUsername); + .Which.Code.Should().Be(Put.BadUsername); } private async Task CheckAdministrator(HttpClient client, string username, bool administrator) @@ -108,7 +108,7 @@ namespace Timeline.Tests.IntegratedTests Password = "password", Administrator = false }); - res.Should().BePutModify(); + res.Should().BePut(false); await CheckAdministrator(client, MockUser.User.Username, false); } @@ -124,7 +124,7 @@ namespace Timeline.Tests.IntegratedTests Password = "password", Administrator = false }); - res.Should().BePutCreate(); + res.Should().BePut(true); await CheckAdministrator(client, username, false); } @@ -135,7 +135,7 @@ namespace Timeline.Tests.IntegratedTests var res = await client.PatchAsJsonAsync("users/usernotexist", new UserPatchRequest { }); res.Should().HaveStatusCode(404) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.Patch_NotExist); + .Which.Code.Should().Be(Patch.NotExist); } [Fact] @@ -156,7 +156,7 @@ namespace Timeline.Tests.IntegratedTests using var client = await _factory.CreateClientAsAdmin(); var url = "users/" + MockUser.User.Username; var res = await client.DeleteAsync(url); - res.Should().BeDeleteDelete(); + res.Should().BeDelete(true); var res2 = await client.GetAsync(url); res2.Should().HaveStatusCode(404); @@ -167,7 +167,7 @@ namespace Timeline.Tests.IntegratedTests { using var client = await _factory.CreateClientAsAdmin(); var res = await client.DeleteAsync("users/usernotexist"); - res.Should().BeDeleteNotExist(); + res.Should().BeDelete(false); } @@ -214,7 +214,7 @@ namespace Timeline.Tests.IntegratedTests new ChangeUsernameRequest { OldUsername = "usernotexist", NewUsername = "newUsername" }); res.Should().HaveStatusCode(400) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.ChangeUsername_NotExist); + .Which.Code.Should().Be(Op.ChangeUsername.NotExist); } [Fact] @@ -225,7 +225,7 @@ namespace Timeline.Tests.IntegratedTests new ChangeUsernameRequest { OldUsername = MockUser.User.Username, NewUsername = MockUser.Admin.Username }); res.Should().HaveStatusCode(400) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.ChangeUsername_AlreadyExist); + .Which.Code.Should().Be(Op.ChangeUsername.AlreadyExist); } [Fact] @@ -282,7 +282,7 @@ namespace Timeline.Tests.IntegratedTests var res = await client.PostAsJsonAsync(url, new ChangePasswordRequest { OldPassword = "???", NewPassword = "???" }); res.Should().HaveStatusCode(400) .And.Should().HaveCommonBody() - .Which.Code.Should().Be(UserController.ErrorCodes.ChangePassword_BadOldPassword); + .Which.Code.Should().Be(Op.ChangePassword.BadOldPassword); } [Fact] diff --git a/Timeline.Tests/Mock/Services/MockStringLocalizer.cs b/Timeline.Tests/Mock/Services/MockStringLocalizer.cs deleted file mode 100644 index 7729d56c..00000000 --- a/Timeline.Tests/Mock/Services/MockStringLocalizer.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Microsoft.Extensions.Localization; -using System.Collections.Generic; -using System.Globalization; - -namespace Timeline.Tests.Mock.Services -{ - public class MockStringLocalizer : IStringLocalizer - { - private const string mockKey = "MOCK_KEY"; - private const string mockString = "THIS IS A MOCK LOCALIZED STRING."; - - public LocalizedString this[string name] => new LocalizedString(name, mockString); - - public LocalizedString this[string name, params object[] arguments] => new LocalizedString(name, mockString); - - public IEnumerable GetAllStrings(bool includeParentCultures) - { - yield return new LocalizedString(mockKey, mockString); - } - - public IStringLocalizer WithCulture(CultureInfo culture) - { - return this; - } - } - - public class MockStringLocalizer : MockStringLocalizer, IStringLocalizer - { - - } -} diff --git a/Timeline.Tests/Mock/Services/TestStringLocalizerFactory.cs b/Timeline.Tests/Mock/Services/TestStringLocalizerFactory.cs new file mode 100644 index 00000000..4084dd8f --- /dev/null +++ b/Timeline.Tests/Mock/Services/TestStringLocalizerFactory.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; + +namespace Timeline.Tests.Mock.Services +{ + internal static class TestStringLocalizerFactory + { + internal static IStringLocalizerFactory Create() + { + return new ResourceManagerStringLocalizerFactory( + Options.Create(new LocalizationOptions() + { + ResourcesPath = "Resource" + }), + NullLoggerFactory.Instance + ); + } + + internal static IStringLocalizer Create(this IStringLocalizerFactory factory) + { + return new StringLocalizer(factory); + } + } +} diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs index d708127a..cf32a562 100644 --- a/Timeline/Controllers/TokenController.cs +++ b/Timeline/Controllers/TokenController.cs @@ -56,7 +56,7 @@ namespace Timeline.Controllers [HttpPost("create")] [AllowAnonymous] - public async Task Create([FromBody] CreateTokenRequest request) + public async Task> Create([FromBody] CreateTokenRequest request) { void LogFailure(string reason, Exception? e = null) { @@ -102,7 +102,7 @@ namespace Timeline.Controllers [HttpPost("verify")] [AllowAnonymous] - public async Task Verify([FromBody] VerifyTokenRequest request) + public async Task> Verify([FromBody] VerifyTokenRequest request) { void LogFailure(string reason, Exception? e = null, params (string, object?)[] otherProperties) { diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index b01d06fb..6afc890c 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -77,7 +77,7 @@ namespace Timeline.Controllers } [HttpGet("users/{username}"), AdminAuthorize] - public async Task Get([FromRoute] string username) + public async Task> Get([FromRoute] string username) { var user = await _userService.GetUser(username); if (user == null) @@ -89,7 +89,7 @@ namespace Timeline.Controllers } [HttpPut("users/{username}"), AdminAuthorize] - public async Task Put([FromBody] UserPutRequest request, [FromRoute] string username) + public async Task> Put([FromBody] UserPutRequest request, [FromRoute] string username) { try { @@ -114,7 +114,7 @@ namespace Timeline.Controllers } [HttpPatch("users/{username}"), AdminAuthorize] - public async Task Patch([FromBody] UserPatchRequest request, [FromRoute] string username) + public async Task Patch([FromBody] UserPatchRequest request, [FromRoute] string username) { try { @@ -129,7 +129,7 @@ namespace Timeline.Controllers } [HttpDelete("users/{username}"), AdminAuthorize] - public async Task Delete([FromRoute] string username) + public async Task> Delete([FromRoute] string username) { try { @@ -145,44 +145,45 @@ namespace Timeline.Controllers } [HttpPost("userop/changeusername"), AdminAuthorize] - public async Task ChangeUsername([FromBody] ChangeUsernameRequest request) + public async Task ChangeUsername([FromBody] ChangeUsernameRequest request) { try { await _userService.ChangeUsername(request.OldUsername, request.NewUsername); - _logger.LogInformation(FormatLogMessage("A user changed username.", - Pair("Old Username", request.OldUsername), Pair("New Username", request.NewUsername))); + _logger.LogInformation(Log.Format(_localizer["LogChangeUsernameSuccess"], + ("Old Username", request.OldUsername), ("New Username", request.NewUsername))); return Ok(); } catch (UserNotExistException e) { - _logger.LogInformation(e, FormatLogMessage("Attempt to change a non-existent user's username failed.", - Pair("Old Username", request.OldUsername), Pair("New Username", request.NewUsername))); - return BadRequest(new CommonResponse(ErrorCodes.ChangeUsername_NotExist, $"The user {request.OldUsername} does not exist.")); + _logger.LogInformation(e, Log.Format(_localizer["LogChangeUsernameNotExist"], + ("Old Username", request.OldUsername), ("New Username", request.NewUsername))); + return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.NotExist, _localizer["ErrorChangeUsernameNotExist", request.OldUsername])); } catch (UserAlreadyExistException e) { - _logger.LogInformation(e, FormatLogMessage("Attempt to change a user's username to a existent one failed.", - Pair("Old Username", request.OldUsername), Pair("New Username", request.NewUsername))); - return BadRequest(new CommonResponse(ErrorCodes.ChangeUsername_AlreadyExist, $"The user {request.NewUsername} already exists.")); + _logger.LogInformation(e, Log.Format(_localizer["LogChangeUsernameAlreadyExist"], + ("Old Username", request.OldUsername), ("New Username", request.NewUsername))); + return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.AlreadyExist, _localizer["ErrorChangeUsernameAlreadyExist"])); } // there is no need to catch bad format exception because it is already checked in model validation. } [HttpPost("userop/changepassword"), Authorize] - public async Task ChangePassword([FromBody] ChangePasswordRequest request) + public async Task ChangePassword([FromBody] ChangePasswordRequest request) { try { - await _userService.ChangePassword(User.Identity.Name, request.OldPassword, request.NewPassword); - _logger.LogInformation(FormatLogMessage("A user changed password.", Pair("Username", User.Identity.Name))); + await _userService.ChangePassword(User.Identity.Name!, request.OldPassword, request.NewPassword); + _logger.LogInformation(Log.Format(_localizer["LogChangePasswordSuccess"], ("Username", User.Identity.Name))); return Ok(); } catch (BadPasswordException e) { - _logger.LogInformation(e, FormatLogMessage("A user attempt to change password but old password is wrong.", - Pair("Username", User.Identity.Name), Pair("Old Password", request.OldPassword))); - return BadRequest(new CommonResponse(ErrorCodes.ChangePassword_BadOldPassword, "Old password is wrong.")); + _logger.LogInformation(e, Log.Format(_localizer["LogChangePasswordBadPassword"], + ("Username", User.Identity.Name), ("Old Password", request.OldPassword))); + return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangePassword.BadOldPassword, + _localizer["ErrorChangePasswordBadPassword"])); } // User can't be non-existent or the token is bad. } diff --git a/Timeline/Models/Http/Common.cs b/Timeline/Models/Http/Common.cs index 2735e43c..130439d3 100644 --- a/Timeline/Models/Http/Common.cs +++ b/Timeline/Models/Http/Common.cs @@ -61,7 +61,7 @@ namespace Timeline.Models.Http public T Data { get; set; } = default!; } - public static class CommonPutResponse + public class CommonPutResponse : CommonDataResponse { public class ResponseData { @@ -73,21 +73,32 @@ namespace Timeline.Models.Http public bool Create { get; set; } } - internal static CommonDataResponse Create(IStringLocalizerFactory localizerFactory) + public CommonPutResponse() + { + + } + + public CommonPutResponse(int code, string message, bool create) + : base(code, message, new ResponseData(create)) + { + + } + + internal static CommonPutResponse Create(IStringLocalizerFactory localizerFactory) { var localizer = localizerFactory.Create("Http.Common"); - return new CommonDataResponse(0, localizer["ResponsePutCreate"], new ResponseData(true)); + return new CommonPutResponse(0, localizer["ResponsePutCreate"], true); } - internal static CommonDataResponse Modify(IStringLocalizerFactory localizerFactory) + internal static CommonPutResponse Modify(IStringLocalizerFactory localizerFactory) { var localizer = localizerFactory.Create("Http.Common"); - return new CommonDataResponse(0, localizer["ResponsePutModify"], new ResponseData(false)); + return new CommonPutResponse(0, localizer["ResponsePutModify"], false); } } - public static class CommonDeleteResponse + public class CommonDeleteResponse : CommonDataResponse { public class ResponseData { @@ -99,16 +110,27 @@ namespace Timeline.Models.Http public bool Delete { get; set; } } - internal static CommonDataResponse Delete(IStringLocalizerFactory localizerFactory) + public CommonDeleteResponse() + { + + } + + public CommonDeleteResponse(int code, string message, bool delete) + : base(code, message, new ResponseData(delete)) + { + + } + + internal static CommonDeleteResponse Delete(IStringLocalizerFactory localizerFactory) { var localizer = localizerFactory.Create("Http.Common"); - return new CommonDataResponse(0, localizer["ResponseDeleteDelete"], new ResponseData(true)); + return new CommonDeleteResponse(0, localizer["ResponseDeleteDelete"], true); } - internal static CommonDataResponse NotExist(IStringLocalizerFactory localizerFactory) + internal static CommonDeleteResponse NotExist(IStringLocalizerFactory localizerFactory) { var localizer = localizerFactory.Create("Http.Common"); - return new CommonDataResponse(0, localizer["ResponseDeleteNotExist"], new ResponseData(false)); + return new CommonDeleteResponse(0, localizer["ResponseDeleteNotExist"], false); } } } diff --git a/Timeline/Resources/Controllers/UserController.en.resx b/Timeline/Resources/Controllers/UserController.en.resx index f0fb372a..0bd1dfe3 100644 --- a/Timeline/Resources/Controllers/UserController.en.resx +++ b/Timeline/Resources/Controllers/UserController.en.resx @@ -117,6 +117,15 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Old password is wrong. + + + The new username {0} already exists. + + + The old username {0} does not exist. + The user does not exist. diff --git a/Timeline/Resources/Controllers/UserController.resx b/Timeline/Resources/Controllers/UserController.resx index 901f8aab..d720d1c1 100644 --- a/Timeline/Resources/Controllers/UserController.resx +++ b/Timeline/Resources/Controllers/UserController.resx @@ -117,6 +117,21 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Attempt to change password with wrong old password failed. + + + A user has changed password. + + + Attempt to change a user's username to a existent one failed. + + + Attempt to change a username of a user that does not exist failed. + + + A user has changed username. + A user has been deleted. diff --git a/Timeline/Resources/Controllers/UserController.zh.resx b/Timeline/Resources/Controllers/UserController.zh.resx index 519f08f6..3556083e 100644 --- a/Timeline/Resources/Controllers/UserController.zh.resx +++ b/Timeline/Resources/Controllers/UserController.zh.resx @@ -117,6 +117,15 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 旧密码错误。 + + + 新用户名{0}已经存在。 + + + 旧用户名{0}不存在。 + 用户不存在。 -- cgit v1.2.3 From 912455ac19161533205c2fe56b91ff4595ea4fdb Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Thu, 24 Oct 2019 19:57:59 +0800 Subject: ... --- Timeline.Tests/DatabaseTest.cs | 14 +- Timeline.Tests/GlobalSuppressions.cs | 2 +- .../Helpers/AsyncFunctionAssertionsExtensions.cs | 16 ++ Timeline.Tests/IntegratedTests/UserAvatarTest.cs | 20 ++ Timeline.Tests/Mock/Data/TestUsers.cs | 2 +- Timeline.Tests/UserAvatarServiceTest.cs | 206 +++++++++------------ Timeline/Entities/UserAvatar.cs | 12 -- .../Services/UserAvatarService.Designer.cs | 6 +- Timeline/Resources/Services/UserAvatarService.resx | 4 +- Timeline/Services/ETagGenerator.cs | 7 +- Timeline/Services/UserAvatarService.cs | 19 +- 11 files changed, 162 insertions(+), 146 deletions(-) create mode 100644 Timeline.Tests/Helpers/AsyncFunctionAssertionsExtensions.cs (limited to 'Timeline.Tests/GlobalSuppressions.cs') diff --git a/Timeline.Tests/DatabaseTest.cs b/Timeline.Tests/DatabaseTest.cs index c45c0f66..b5681491 100644 --- a/Timeline.Tests/DatabaseTest.cs +++ b/Timeline.Tests/DatabaseTest.cs @@ -26,11 +26,21 @@ namespace Timeline.Tests [Fact] public void DeleteUserShouldAlsoDeleteAvatar() { - _context.UserAvatars.Count().Should().Be(2); var user = _context.Users.First(); - _context.Users.Remove(user); + _context.UserAvatars.Count().Should().Be(0); + _context.UserAvatars.Add(new UserAvatar + { + Data = null, + Type = null, + ETag = null, + LastModified = DateTime.Now, + UserId = user.Id + }); _context.SaveChanges(); _context.UserAvatars.Count().Should().Be(1); + _context.Users.Remove(user); + _context.SaveChanges(); + _context.UserAvatars.Count().Should().Be(0); } } } diff --git a/Timeline.Tests/GlobalSuppressions.cs b/Timeline.Tests/GlobalSuppressions.cs index 2191a5c4..1d1d294b 100644 --- a/Timeline.Tests/GlobalSuppressions.cs +++ b/Timeline.Tests/GlobalSuppressions.cs @@ -5,10 +5,10 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "This is not a UI application.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Tests name have underscores.")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Test may catch all exceptions.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Test classes can be nested.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "This is redundant.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1063:Implement IDisposable Correctly", Justification = "Test classes do not need to implement it that way.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA1816:Dispose methods should call SuppressFinalize", Justification = "Test classes do not need to implement it that way.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2234:Pass system uri objects instead of strings", Justification = "I really don't understand this rule.")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Tests do not need make strings resources.")] - diff --git a/Timeline.Tests/Helpers/AsyncFunctionAssertionsExtensions.cs b/Timeline.Tests/Helpers/AsyncFunctionAssertionsExtensions.cs new file mode 100644 index 00000000..b78309c0 --- /dev/null +++ b/Timeline.Tests/Helpers/AsyncFunctionAssertionsExtensions.cs @@ -0,0 +1,16 @@ +using FluentAssertions; +using FluentAssertions.Primitives; +using FluentAssertions.Specialized; +using System; +using System.Threading.Tasks; + +namespace Timeline.Tests.Helpers +{ + public static class AsyncFunctionAssertionsExtensions + { + public static async Task> ThrowAsync(this AsyncFunctionAssertions assertions, Type exceptionType, string because = "", params object[] becauseArgs) + { + return (await assertions.ThrowAsync(because, becauseArgs)).Which.Should().BeAssignableTo(exceptionType); + } + } +} diff --git a/Timeline.Tests/IntegratedTests/UserAvatarTest.cs b/Timeline.Tests/IntegratedTests/UserAvatarTest.cs index ba6d98e1..ce389046 100644 --- a/Timeline.Tests/IntegratedTests/UserAvatarTest.cs +++ b/Timeline.Tests/IntegratedTests/UserAvatarTest.cs @@ -40,6 +40,7 @@ namespace Timeline.Tests.IntegratedTests } [Fact] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "HttpMessageRequest should be disposed ???")] public async Task Test() { Avatar mockAvatar = new Avatar @@ -264,6 +265,25 @@ namespace Timeline.Tests.IntegratedTests .And.Should().HaveCommonBody().Which.Code.Should().Be(Delete.UserNotExist); } } + + // bad username check + using (var client = await _factory.CreateClientAsAdmin()) + { + { + var res = await client.GetAsync("users/u!ser/avatar"); + res.Should().BeInvalidModel(); + } + + { + var res = await client.PutByteArrayAsync("users/u!ser/avatar", ImageHelper.CreatePngWithSize(100, 100), "image/png"); + res.Should().BeInvalidModel(); + } + + { + var res = await client.DeleteAsync("users/u!ser/avatar"); + res.Should().BeInvalidModel(); + } + } } } } \ No newline at end of file diff --git a/Timeline.Tests/Mock/Data/TestUsers.cs b/Timeline.Tests/Mock/Data/TestUsers.cs index 6b0a9997..fa75236a 100644 --- a/Timeline.Tests/Mock/Data/TestUsers.cs +++ b/Timeline.Tests/Mock/Data/TestUsers.cs @@ -36,7 +36,7 @@ namespace Timeline.Tests.Mock.Data Name = user.Username, EncryptedPassword = passwordService.HashPassword(user.Password), RoleString = UserRoleConvert.ToString(user.Administrator), - Avatar = UserAvatar.Create(DateTime.Now) + Avatar = null }; } diff --git a/Timeline.Tests/UserAvatarServiceTest.cs b/Timeline.Tests/UserAvatarServiceTest.cs index 7489517b..79fa6f5c 100644 --- a/Timeline.Tests/UserAvatarServiceTest.cs +++ b/Timeline.Tests/UserAvatarServiceTest.cs @@ -2,8 +2,10 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using Moq; using SixLabors.ImageSharp.Formats.Png; using System; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,40 +13,12 @@ using Timeline.Entities; using Timeline.Services; using Timeline.Tests.Helpers; using Timeline.Tests.Mock.Data; +using Timeline.Tests.Mock.Services; using Xunit; using Xunit.Abstractions; namespace Timeline.Tests { - public class MockDefaultUserAvatarProvider : IDefaultUserAvatarProvider - { - public static string ETag { get; } = "Hahaha"; - - public static AvatarInfo AvatarInfo { get; } = new AvatarInfo - { - Avatar = new Avatar { Type = "image/test", Data = Encoding.ASCII.GetBytes("test") }, - LastModified = DateTime.Now - }; - - public Task GetDefaultAvatarETag() - { - return Task.FromResult(ETag); - } - - public Task GetDefaultAvatar() - { - return Task.FromResult(AvatarInfo); - } - } - - public class MockUserAvatarValidator : IUserAvatarValidator - { - public Task Validate(Avatar avatar) - { - return Task.CompletedTask; - } - } - public class UserAvatarValidatorTest : IClassFixture { private readonly UserAvatarValidator _validator; @@ -106,22 +80,30 @@ namespace Timeline.Tests } } - public class UserAvatarServiceTest : IDisposable, IClassFixture, IClassFixture + public class UserAvatarServiceTest : IDisposable { - private UserAvatar MockAvatarEntity1 { get; } = new UserAvatar + private UserAvatar CreateMockAvatarEntity(string key) => new UserAvatar { - Type = "image/testaaa", - Data = Encoding.ASCII.GetBytes("amock"), - ETag = "aaaa", + Type = $"image/test{key}", + Data = Encoding.ASCII.GetBytes($"mock{key}"), + ETag = $"etag{key}", LastModified = DateTime.Now }; - private UserAvatar MockAvatarEntity2 { get; } = new UserAvatar + private AvatarInfo CreateMockAvatarInfo(string key) => new AvatarInfo { - Type = "image/testbbb", - Data = Encoding.ASCII.GetBytes("bmock"), - ETag = "bbbb", - LastModified = DateTime.Now + TimeSpan.FromMinutes(1) + Avatar = new Avatar + { + Type = $"image/test{key}", + Data = Encoding.ASCII.GetBytes($"mock{key}") + }, + LastModified = DateTime.Now + }; + + private Avatar CreateMockAvatar(string key) => new Avatar + { + Type = $"image/test{key}", + Data = Encoding.ASCII.GetBytes($"mock{key}") }; private Avatar ToAvatar(UserAvatar entity) @@ -150,137 +132,115 @@ namespace Timeline.Tests to.LastModified = from.LastModified; } - private readonly MockDefaultUserAvatarProvider _mockDefaultUserAvatarProvider; + private readonly Mock _mockDefaultAvatarProvider; + private readonly Mock _mockValidator; + private readonly Mock _mockETagGenerator; + private readonly Mock _mockClock; private readonly TestDatabase _database; - private readonly IETagGenerator _eTagGenerator; - private readonly UserAvatarService _service; - public UserAvatarServiceTest(MockDefaultUserAvatarProvider mockDefaultUserAvatarProvider, MockUserAvatarValidator mockUserAvatarValidator) + public UserAvatarServiceTest() { - _mockDefaultUserAvatarProvider = mockDefaultUserAvatarProvider; + _mockDefaultAvatarProvider = new Mock(); + _mockValidator = new Mock(); + _mockETagGenerator = new Mock(); + _mockClock = new Mock(); _database = new TestDatabase(); - _eTagGenerator = new ETagGenerator(); - - _service = new UserAvatarService(NullLogger.Instance, _database.DatabaseContext, _mockDefaultUserAvatarProvider, mockUserAvatarValidator, _eTagGenerator); + _service = new UserAvatarService(NullLogger.Instance, _database.DatabaseContext, _mockDefaultAvatarProvider.Object, _mockValidator.Object, _mockETagGenerator.Object, _mockClock.Object); } - public void Dispose() { _database.Dispose(); } - [Fact] - public void GetAvatarETag_ShouldThrow_ArgumentException() + [Theory] + [InlineData(null, typeof(ArgumentNullException))] + [InlineData("", typeof(UsernameBadFormatException))] + [InlineData("a!a", typeof(UsernameBadFormatException))] + [InlineData("usernotexist", typeof(UserNotExistException))] + public async Task GetAvatarETag_ShouldThrow(string username, Type exceptionType) { - // no need to await because arguments are checked syncronizedly. - _service.Invoking(s => s.GetAvatarETag(null)).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("null", StringComparison.OrdinalIgnoreCase)); - _service.Invoking(s => s.GetAvatarETag("")).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("empty", StringComparison.OrdinalIgnoreCase)); - } - - [Fact] - public void GetAvatarETag_ShouldThrow_UserNotExistException() - { - const string username = "usernotexist"; - _service.Awaiting(s => s.GetAvatarETag(username)).Should().Throw() - .Where(e => e.Username == username); + await _service.Awaiting(s => s.GetAvatarETag(username)).Should().ThrowAsync(exceptionType); } [Fact] public async Task GetAvatarETag_ShouldReturn_Default() { - string username = MockUser.User.Username; - (await _service.GetAvatarETag(username)).Should().BeEquivalentTo((await _mockDefaultUserAvatarProvider.GetDefaultAvatarETag())); + const string etag = "aaaaaa"; + _mockDefaultAvatarProvider.Setup(p => p.GetDefaultAvatarETag()).ReturnsAsync(etag); + (await _service.GetAvatarETag(MockUser.User.Username)).Should().Be(etag); } [Fact] public async Task GetAvatarETag_ShouldReturn_Data() { string username = MockUser.User.Username; + var mockAvatarEntity = CreateMockAvatarEntity("aaa"); { - // create mock data var context = _database.DatabaseContext; var user = await context.Users.Where(u => u.Name == username).Include(u => u.Avatar).SingleAsync(); - Set(user.Avatar, MockAvatarEntity1); + user.Avatar = mockAvatarEntity; await context.SaveChangesAsync(); } - - (await _service.GetAvatarETag(username)).Should().BeEquivalentTo(MockAvatarEntity1.ETag); + (await _service.GetAvatarETag(username)).Should().BeEquivalentTo(mockAvatarEntity.ETag); } - [Fact] - public void GetAvatar_ShouldThrow_ArgumentException() + [Theory] + [InlineData(null, typeof(ArgumentNullException))] + [InlineData("", typeof(UsernameBadFormatException))] + [InlineData("a!a", typeof(UsernameBadFormatException))] + [InlineData("usernotexist", typeof(UserNotExistException))] + public async Task GetAvatar_ShouldThrow(string username, Type exceptionType) { - // no need to await because arguments are checked syncronizedly. - _service.Invoking(s => s.GetAvatar(null)).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("null", StringComparison.OrdinalIgnoreCase)); - _service.Invoking(s => s.GetAvatar("")).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("empty", StringComparison.OrdinalIgnoreCase)); - } + await _service.Awaiting(s => s.GetAvatar(username)).Should().ThrowAsync(exceptionType); - [Fact] - public void GetAvatar_ShouldThrow_UserNotExistException() - { - const string username = "usernotexist"; - _service.Awaiting(s => s.GetAvatar(username)).Should().Throw() - .Where(e => e.Username == username); } [Fact] public async Task GetAvatar_ShouldReturn_Default() { + var mockAvatar = CreateMockAvatarInfo("aaa"); + _mockDefaultAvatarProvider.Setup(p => p.GetDefaultAvatar()).ReturnsAsync(mockAvatar); string username = MockUser.User.Username; - (await _service.GetAvatar(username)).Avatar.Should().BeEquivalentTo((await _mockDefaultUserAvatarProvider.GetDefaultAvatar()).Avatar); + (await _service.GetAvatar(username)).Should().BeEquivalentTo(mockAvatar); } [Fact] public async Task GetAvatar_ShouldReturn_Data() { string username = MockUser.User.Username; - + var mockAvatarEntity = CreateMockAvatarEntity("aaa"); { - // create mock data var context = _database.DatabaseContext; var user = await context.Users.Where(u => u.Name == username).Include(u => u.Avatar).SingleAsync(); - Set(user.Avatar, MockAvatarEntity1); + user.Avatar = mockAvatarEntity; await context.SaveChangesAsync(); } - (await _service.GetAvatar(username)).Should().BeEquivalentTo(ToAvatarInfo(MockAvatarEntity1)); + (await _service.GetAvatar(username)).Should().BeEquivalentTo(ToAvatarInfo(mockAvatarEntity)); } - [Fact] - public void SetAvatar_ShouldThrow_ArgumentException() + public static IEnumerable SetAvatar_ShouldThrow_Data() { - var avatar = ToAvatar(MockAvatarEntity1); - // no need to await because arguments are checked syncronizedly. - _service.Invoking(s => s.SetAvatar(null, avatar)).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("null", StringComparison.OrdinalIgnoreCase)); - _service.Invoking(s => s.SetAvatar("", avatar)).Should().Throw() - .Where(e => e.ParamName == "username" && e.Message.Contains("empty", StringComparison.OrdinalIgnoreCase)); - - _service.Invoking(s => s.SetAvatar("aaa", new Avatar { Type = null, Data = new[] { (byte)0x00 } })).Should().Throw() - .Where(e => e.ParamName == "avatar" && e.Message.Contains("null", StringComparison.OrdinalIgnoreCase)); - _service.Invoking(s => s.SetAvatar("aaa", new Avatar { Type = "", Data = new[] { (byte)0x00 } })).Should().Throw() - .Where(e => e.ParamName == "avatar" && e.Message.Contains("empty", StringComparison.OrdinalIgnoreCase)); - - _service.Invoking(s => s.SetAvatar("aaa", new Avatar { Type = "aaa", Data = null })).Should().Throw() - .Where(e => e.ParamName == "avatar" && e.Message.Contains("null", StringComparison.OrdinalIgnoreCase)); + yield return new object[] { null, null, typeof(ArgumentNullException) }; + yield return new object[] { "", null, typeof(UsernameBadFormatException) }; + yield return new object[] { "u!u", null, typeof(UsernameBadFormatException) }; + yield return new object[] { null, new Avatar { Type = null, Data = new[] { (byte)0x00 } }, typeof(ArgumentException) }; + yield return new object[] { null, new Avatar { Type = "", Data = new[] { (byte)0x00 } }, typeof(ArgumentException) }; + yield return new object[] { null, new Avatar { Type = "aaa", Data = null }, typeof(ArgumentException) }; + yield return new object[] { "usernotexist", null, typeof(UserNotExistException) }; } - [Fact] - public void SetAvatar_ShouldThrow_UserNotExistException() + [Theory] + [MemberData(nameof(SetAvatar_ShouldThrow_Data))] + public async Task SetAvatar_ShouldThrow(string username, Avatar avatar, Type exceptionType) { - const string username = "usernotexist"; - _service.Awaiting(s => s.SetAvatar(username, ToAvatar(MockAvatarEntity1))).Should().Throw() - .Where(e => e.Username == username); + await _service.Awaiting(s => s.SetAvatar(username, avatar)).Should().ThrowAsync(exceptionType); } [Fact] @@ -290,27 +250,43 @@ namespace Timeline.Tests var user = await _database.DatabaseContext.Users.Where(u => u.Name == username).Include(u => u.Avatar).SingleAsync(); + var avatar1 = CreateMockAvatar("aaa"); + var avatar2 = CreateMockAvatar("bbb"); + + string etag1 = "etagaaa"; + string etag2 = "etagbbb"; + + DateTime dateTime1 = DateTime.Now.AddSeconds(2); + DateTime dateTime2 = DateTime.Now.AddSeconds(10); + DateTime dateTime3 = DateTime.Now.AddSeconds(20); + // create - var avatar1 = ToAvatar(MockAvatarEntity1); + _mockETagGenerator.Setup(g => g.Generate(avatar1.Data)).ReturnsAsync(etag1); + _mockClock.Setup(c => c.GetCurrentTime()).Returns(dateTime1); await _service.SetAvatar(username, avatar1); user.Avatar.Should().NotBeNull(); user.Avatar.Type.Should().Be(avatar1.Type); user.Avatar.Data.Should().Equal(avatar1.Data); - user.Avatar.ETag.Should().NotBeNull(); + user.Avatar.ETag.Should().Be(etag1); + user.Avatar.LastModified.Should().Be(dateTime1); // modify - var avatar2 = ToAvatar(MockAvatarEntity2); + _mockETagGenerator.Setup(g => g.Generate(avatar2.Data)).ReturnsAsync(etag2); + _mockClock.Setup(c => c.GetCurrentTime()).Returns(dateTime2); await _service.SetAvatar(username, avatar2); user.Avatar.Should().NotBeNull(); - user.Avatar.Type.Should().Be(MockAvatarEntity2.Type); - user.Avatar.Data.Should().Equal(MockAvatarEntity2.Data); - user.Avatar.ETag.Should().NotBeNull(); + user.Avatar.Type.Should().Be(avatar2.Type); + user.Avatar.Data.Should().Equal(avatar2.Data); + user.Avatar.ETag.Should().Be(etag2); + user.Avatar.LastModified.Should().Be(dateTime2); // delete + _mockClock.Setup(c => c.GetCurrentTime()).Returns(dateTime3); await _service.SetAvatar(username, null); user.Avatar.Type.Should().BeNull(); user.Avatar.Data.Should().BeNull(); user.Avatar.ETag.Should().BeNull(); + user.Avatar.LastModified.Should().Be(dateTime3); } } } diff --git a/Timeline/Entities/UserAvatar.cs b/Timeline/Entities/UserAvatar.cs index 3b5388aa..a5b18b94 100644 --- a/Timeline/Entities/UserAvatar.cs +++ b/Timeline/Entities/UserAvatar.cs @@ -24,17 +24,5 @@ namespace Timeline.Entities public DateTime LastModified { get; set; } public long UserId { get; set; } - - public static UserAvatar Create(DateTime lastModified) - { - return new UserAvatar - { - Id = 0, - Data = null, - Type = null, - ETag = null, - LastModified = lastModified - }; - } } } diff --git a/Timeline/Resources/Services/UserAvatarService.Designer.cs b/Timeline/Resources/Services/UserAvatarService.Designer.cs index cabc9ede..6ee6fef9 100644 --- a/Timeline/Resources/Services/UserAvatarService.Designer.cs +++ b/Timeline/Resources/Services/UserAvatarService.Designer.cs @@ -70,11 +70,11 @@ namespace Timeline.Resources.Services { } /// - /// Looks up a localized string similar to Type of avatar is null.. + /// Looks up a localized string similar to Type of avatar is null or empty.. /// - internal static string ArgumentAvatarTypeNull { + internal static string ArgumentAvatarTypeNullOrEmpty { get { - return ResourceManager.GetString("ArgumentAvatarTypeNull", resourceCulture); + return ResourceManager.GetString("ArgumentAvatarTypeNullOrEmpty", resourceCulture); } } diff --git a/Timeline/Resources/Services/UserAvatarService.resx b/Timeline/Resources/Services/UserAvatarService.resx index ab6389ff..3269bf13 100644 --- a/Timeline/Resources/Services/UserAvatarService.resx +++ b/Timeline/Resources/Services/UserAvatarService.resx @@ -120,8 +120,8 @@ Data of avatar is null. - - Type of avatar is null. + + Type of avatar is null or empty. Database corupted! One of type and data of a avatar is null but the other is not. diff --git a/Timeline/Services/ETagGenerator.cs b/Timeline/Services/ETagGenerator.cs index e518f01f..d328ea20 100644 --- a/Timeline/Services/ETagGenerator.cs +++ b/Timeline/Services/ETagGenerator.cs @@ -1,5 +1,6 @@ using System; using System.Security.Cryptography; +using System.Threading.Tasks; namespace Timeline.Services { @@ -11,7 +12,7 @@ namespace Timeline.Services /// The source data. /// The generated etag. /// Thrown if is null. - string Generate(byte[] source); + Task Generate(byte[] source); } public sealed class ETagGenerator : IETagGenerator, IDisposable @@ -24,12 +25,12 @@ namespace Timeline.Services _sha1 = SHA1.Create(); } - public string Generate(byte[] source) + public Task Generate(byte[] source) { if (source == null) throw new ArgumentNullException(nameof(source)); - return Convert.ToBase64String(_sha1.ComputeHash(source)); + return Task.Run(() => Convert.ToBase64String(_sha1.ComputeHash(source))); } private bool _disposed = false; // To detect redundant calls diff --git a/Timeline/Services/UserAvatarService.cs b/Timeline/Services/UserAvatarService.cs index 4c65a0fa..ff80003c 100644 --- a/Timeline/Services/UserAvatarService.cs +++ b/Timeline/Services/UserAvatarService.cs @@ -118,7 +118,7 @@ namespace Timeline.Services { _cacheData = await File.ReadAllBytesAsync(path); _cacheLastModified = File.GetLastWriteTime(path); - _cacheETag = _eTagGenerator.Generate(_cacheData); + _cacheETag = await _eTagGenerator.Generate(_cacheData); } } @@ -179,12 +179,15 @@ namespace Timeline.Services private readonly UsernameValidator _usernameValidator; + private readonly IClock _clock; + public UserAvatarService( ILogger logger, DatabaseContext database, IDefaultUserAvatarProvider defaultUserAvatarProvider, IUserAvatarValidator avatarValidator, - IETagGenerator eTagGenerator) + IETagGenerator eTagGenerator, + IClock clock) { _logger = logger; _database = database; @@ -192,6 +195,7 @@ namespace Timeline.Services _avatarValidator = avatarValidator; _eTagGenerator = eTagGenerator; _usernameValidator = new UsernameValidator(); + _clock = clock; } public async Task GetAvatarETag(string username) @@ -245,8 +249,8 @@ namespace Timeline.Services { if (avatar.Data == null) throw new ArgumentException(Resources.Services.UserAvatarService.ArgumentAvatarDataNull, nameof(avatar)); - if (avatar.Type == null) - throw new ArgumentException(Resources.Services.UserAvatarService.ArgumentAvatarTypeNull, nameof(avatar)); + if (string.IsNullOrEmpty(avatar.Type)) + throw new ArgumentException(Resources.Services.UserAvatarService.ArgumentAvatarTypeNullOrEmpty, nameof(avatar)); } var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, _usernameValidator, username); @@ -263,7 +267,7 @@ namespace Timeline.Services avatarEntity.Data = null; avatarEntity.Type = null; avatarEntity.ETag = null; - avatarEntity.LastModified = DateTime.Now; + avatarEntity.LastModified = _clock.GetCurrentTime(); await _database.SaveChangesAsync(); _logger.LogInformation(Resources.Services.UserAvatarService.LogUpdateEntity); } @@ -278,8 +282,9 @@ namespace Timeline.Services } avatarEntity!.Type = avatar.Type; avatarEntity.Data = avatar.Data; - avatarEntity.ETag = _eTagGenerator.Generate(avatar.Data); - avatarEntity.LastModified = DateTime.Now; + avatarEntity.ETag = await _eTagGenerator.Generate(avatar.Data); + avatarEntity.LastModified = _clock.GetCurrentTime(); + avatarEntity.UserId = userId; if (create) { _database.UserAvatars.Add(avatarEntity); -- cgit v1.2.3