From ddfd4cedaf696e6ad19f40bec4db0f9d0e28dc65 Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 18 Jun 2020 16:21:39 +0800 Subject: Add last modified info to timeline. --- Timeline.Tests/Helpers/TestApplication.cs | 29 +++------ Timeline.Tests/Helpers/TestClock.cs | 23 +++++++ Timeline.Tests/Helpers/TestDatabase.cs | 76 ++++++++++++++++++++++ Timeline.Tests/Services/TimelineServiceTest.cs | 87 ++++++++++++++++++++++++++ 4 files changed, 193 insertions(+), 22 deletions(-) create mode 100644 Timeline.Tests/Helpers/TestClock.cs create mode 100644 Timeline.Tests/Helpers/TestDatabase.cs create mode 100644 Timeline.Tests/Services/TimelineServiceTest.cs (limited to 'Timeline.Tests') diff --git a/Timeline.Tests/Helpers/TestApplication.cs b/Timeline.Tests/Helpers/TestApplication.cs index 45807516..684ffe2c 100644 --- a/Timeline.Tests/Helpers/TestApplication.cs +++ b/Timeline.Tests/Helpers/TestApplication.cs @@ -10,14 +10,13 @@ using System.IO; using System.Threading.Tasks; using Timeline.Configs; using Timeline.Entities; -using Timeline.Migrations; using Xunit; namespace Timeline.Tests.Helpers { public class TestApplication : IAsyncLifetime { - public SqliteConnection DatabaseConnection { get; private set; } + public TestDatabase Database { get; } public IHost Host { get; private set; } @@ -25,30 +24,16 @@ namespace Timeline.Tests.Helpers public TestApplication() { - + Database = new TestDatabase(false); } public async Task InitializeAsync() { + await Database.InitializeAsync(); + WorkDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(WorkDir); - DatabaseConnection = new SqliteConnection("Data Source=:memory:;"); - await DatabaseConnection.OpenAsync(); - - var options = new DbContextOptionsBuilder() - .UseSqlite(DatabaseConnection).Options; - - using (var context = new DatabaseContext(options)) - { - await context.Database.EnsureCreatedAsync(); - context.JwtToken.Add(new JwtTokenEntity - { - Key = JwtTokenGenerateHelper.GenerateKey() - }); - await context.SaveChangesAsync(); - } - Host = await Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder() .ConfigureAppConfiguration((context, config) => { @@ -62,7 +47,7 @@ namespace Timeline.Tests.Helpers { services.AddDbContext(options => { - options.UseSqlite(DatabaseConnection); + options.UseSqlite(Database.Connection); }); }) .ConfigureWebHost(webBuilder => @@ -79,9 +64,9 @@ namespace Timeline.Tests.Helpers await Host.StopAsync(); Host.Dispose(); - await DatabaseConnection.CloseAsync(); - await DatabaseConnection.DisposeAsync(); Directory.Delete(WorkDir, true); + + await Database.DisposeAsync(); } } } diff --git a/Timeline.Tests/Helpers/TestClock.cs b/Timeline.Tests/Helpers/TestClock.cs new file mode 100644 index 00000000..7febc0fe --- /dev/null +++ b/Timeline.Tests/Helpers/TestClock.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Timeline.Services; + +namespace Timeline.Tests.Helpers +{ + public class TestClock : IClock + { + private DateTime? _currentTime = null; + + public DateTime GetCurrentTime() + { + return _currentTime ?? DateTime.Now; + } + + public void SetCurrentTime(DateTime? mockTime) + { + _currentTime = mockTime; + } + } +} diff --git a/Timeline.Tests/Helpers/TestDatabase.cs b/Timeline.Tests/Helpers/TestDatabase.cs new file mode 100644 index 00000000..40f8f2d4 --- /dev/null +++ b/Timeline.Tests/Helpers/TestDatabase.cs @@ -0,0 +1,76 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using System.Threading.Tasks; +using Timeline.Entities; +using Timeline.Migrations; +using Timeline.Models; +using Timeline.Services; +using Xunit; + +namespace Timeline.Tests.Helpers +{ + public class TestDatabase : IAsyncLifetime + { + private readonly bool _createUser; + + public TestDatabase(bool createUser = true) + { + _createUser = createUser; + Connection = new SqliteConnection("Data Source=:memory:;"); + } + + public async Task InitializeAsync() + { + await Connection.OpenAsync(); + + using (var context = CreateContext()) + { + await context.Database.EnsureCreatedAsync(); + context.JwtToken.Add(new JwtTokenEntity + { + Key = JwtTokenGenerateHelper.GenerateKey() + }); + await context.SaveChangesAsync(); + + if (_createUser) + { + var passwordService = new PasswordService(); + var userService = new UserService(NullLogger.Instance, context, passwordService); + + await userService.CreateUser(new User + { + Username = "admin", + Password = "adminpw", + Administrator = true, + Nickname = "administrator" + }); + + await userService.CreateUser(new User + { + Username = "user", + Password = "userpw", + Administrator = false, + Nickname = "imuser" + }); + } + } + } + + public async Task DisposeAsync() + { + await Connection.CloseAsync(); + await Connection.DisposeAsync(); + } + + public SqliteConnection Connection { get; } + + public DatabaseContext CreateContext() + { + var options = new DbContextOptionsBuilder() + .UseSqlite(Connection).Options; + + return new DatabaseContext(options); + } + } +} diff --git a/Timeline.Tests/Services/TimelineServiceTest.cs b/Timeline.Tests/Services/TimelineServiceTest.cs new file mode 100644 index 00000000..f7a94dfc --- /dev/null +++ b/Timeline.Tests/Services/TimelineServiceTest.cs @@ -0,0 +1,87 @@ +using Castle.Core.Logging; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Timeline.Entities; +using Timeline.Services; +using Timeline.Tests.Helpers; +using Xunit; + +namespace Timeline.Tests.Services +{ + public class TimelineServiceTest : IAsyncLifetime + { + private TestDatabase _testDatabase = new TestDatabase(); + + private DatabaseContext _databaseContext; + + private readonly PasswordService _passwordService = new PasswordService(); + + private readonly ETagGenerator _eTagGenerator = new ETagGenerator(); + + private readonly ImageValidator _imageValidator = new ImageValidator(); + + private readonly TestClock _clock = new TestClock(); + + private DataManager _dataManager; + + private UserService _userService; + + private TimelineService _timelineService; + + public TimelineServiceTest() + { + } + + public async Task InitializeAsync() + { + await _testDatabase.InitializeAsync(); + _databaseContext = _testDatabase.CreateContext(); + _dataManager = new DataManager(_databaseContext, _eTagGenerator); + _userService = new UserService(NullLogger.Instance, _databaseContext, _passwordService); + _timelineService = new TimelineService(NullLogger.Instance, _databaseContext, _dataManager, _userService, _imageValidator, _clock); + } + + public async Task DisposeAsync() + { + await _testDatabase.DisposeAsync(); + } + + [Fact] + public async Task PersonalTimeline_LastModified() + { + var mockTime = new DateTime(2000, 1, 1, 1, 1, 1); + + _clock.SetCurrentTime(mockTime); + + var timeline = await _timelineService.GetTimeline("@user"); + + timeline.NameLastModified.Should().Be(mockTime); + timeline.LastModified.Should().Be(mockTime); + } + + [Fact] + public async Task OrdinaryTimeline_LastModified() + { + var mockTime = new DateTime(2000, 1, 1, 1, 1, 1); + + _clock.SetCurrentTime(mockTime); + + { + var timeline = await _timelineService.CreateTimeline("tl", await _userService.GetUserIdByUsername("user")); + + timeline.NameLastModified.Should().Be(mockTime); + timeline.LastModified.Should().Be(mockTime); + } + + { + var timeline = await _timelineService.GetTimeline("tl"); + timeline.NameLastModified.Should().Be(mockTime); + timeline.LastModified.Should().Be(mockTime); + } + } + } +} -- cgit v1.2.3 From 5c1b88ce2df221d6a021b9246c952dbf5ee58550 Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 18 Jun 2020 17:13:08 +0800 Subject: feat(back): Timeline service add last modified. --- Timeline.Tests/Helpers/TestClock.cs | 20 ++++++++++ Timeline.Tests/Services/TimelineServiceTest.cs | 53 ++++++++++++++----------- Timeline/Services/TimelineService.cs | 55 +++++++++++++++++++------- 3 files changed, 91 insertions(+), 37 deletions(-) (limited to 'Timeline.Tests') diff --git a/Timeline.Tests/Helpers/TestClock.cs b/Timeline.Tests/Helpers/TestClock.cs index 7febc0fe..de7d0eb7 100644 --- a/Timeline.Tests/Helpers/TestClock.cs +++ b/Timeline.Tests/Helpers/TestClock.cs @@ -19,5 +19,25 @@ namespace Timeline.Tests.Helpers { _currentTime = mockTime; } + + public DateTime SetMockCurrentTime() + { + var time = new DateTime(2000, 1, 1, 1, 1, 1); + _currentTime = time; + return time; + } + + public DateTime ForwardCurrentTime() + { + return ForwardCurrentTime(TimeSpan.FromDays(1)); + } + + public DateTime ForwardCurrentTime(TimeSpan timeSpan) + { + if (_currentTime == null) + return SetMockCurrentTime(); + _currentTime.Value.Add(timeSpan); + return _currentTime.Value; + } } } diff --git a/Timeline.Tests/Services/TimelineServiceTest.cs b/Timeline.Tests/Services/TimelineServiceTest.cs index f7a94dfc..cb2ade61 100644 --- a/Timeline.Tests/Services/TimelineServiceTest.cs +++ b/Timeline.Tests/Services/TimelineServiceTest.cs @@ -1,18 +1,20 @@ using Castle.Core.Logging; using FluentAssertions; +using FluentAssertions.Xml; using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Timeline.Entities; +using Timeline.Models; using Timeline.Services; using Timeline.Tests.Helpers; using Xunit; namespace Timeline.Tests.Services { - public class TimelineServiceTest : IAsyncLifetime + public class TimelineServiceTest : IAsyncLifetime, IDisposable { private TestDatabase _testDatabase = new TestDatabase(); @@ -48,40 +50,45 @@ namespace Timeline.Tests.Services public async Task DisposeAsync() { await _testDatabase.DisposeAsync(); + await _databaseContext.DisposeAsync(); } - [Fact] - public async Task PersonalTimeline_LastModified() + public void Dispose() { - var mockTime = new DateTime(2000, 1, 1, 1, 1, 1); - - _clock.SetCurrentTime(mockTime); - - var timeline = await _timelineService.GetTimeline("@user"); - - timeline.NameLastModified.Should().Be(mockTime); - timeline.LastModified.Should().Be(mockTime); + _eTagGenerator.Dispose(); } - [Fact] - public async Task OrdinaryTimeline_LastModified() + [Theory] + [InlineData("@user")] + [InlineData("tl")] + public async Task Timeline_LastModified(string timelineName) { - var mockTime = new DateTime(2000, 1, 1, 1, 1, 1); - - _clock.SetCurrentTime(mockTime); + _clock.ForwardCurrentTime(); + void Check(Models.Timeline timeline) { - var timeline = await _timelineService.CreateTimeline("tl", await _userService.GetUserIdByUsername("user")); - - timeline.NameLastModified.Should().Be(mockTime); - timeline.LastModified.Should().Be(mockTime); + timeline.NameLastModified.Should().Be(_clock.GetCurrentTime()); + timeline.LastModified.Should().Be(_clock.GetCurrentTime()); } + async Task GetAndCheck() { - var timeline = await _timelineService.GetTimeline("tl"); - timeline.NameLastModified.Should().Be(mockTime); - timeline.LastModified.Should().Be(mockTime); + Check(await _timelineService.GetTimeline(timelineName)); } + + var _ = TimelineHelper.ExtractTimelineName(timelineName, out var isPersonal); + if (!isPersonal) + Check(await _timelineService.CreateTimeline(timelineName, await _userService.GetUserIdByUsername("user"))); + + await GetAndCheck(); + + _clock.ForwardCurrentTime(); + await _timelineService.ChangeProperty(timelineName, new TimelineChangePropertyRequest { Visibility = TimelineVisibility.Public }); + await GetAndCheck(); + + _clock.ForwardCurrentTime(); + await _timelineService.ChangeMember(timelineName, new List { "admin" }, null); + await GetAndCheck(); } } } diff --git a/Timeline/Services/TimelineService.cs b/Timeline/Services/TimelineService.cs index ba5576d1..6c1e91c6 100644 --- a/Timeline/Services/TimelineService.cs +++ b/Timeline/Services/TimelineService.cs @@ -15,6 +15,23 @@ using static Timeline.Resources.Services.TimelineService; namespace Timeline.Services { + public static class TimelineHelper + { + public static string ExtractTimelineName(string name, out bool isPersonal) + { + if (name.StartsWith("@", StringComparison.OrdinalIgnoreCase)) + { + isPersonal = true; + return name.Substring(1); + } + else + { + isPersonal = false; + return name; + } + } + } + public enum TimelineUserRelationshipType { Own = 0b1, @@ -383,19 +400,7 @@ namespace Timeline.Services }; } - private static string ExtractTimelineName(string name, out bool isPersonal) - { - if (name.StartsWith("@", StringComparison.OrdinalIgnoreCase)) - { - isPersonal = true; - return name.Substring(1); - } - else - { - isPersonal = false; - return name; - } - } + // Get timeline id by name. If it is a personal timeline and it does not exist, it will be created. // @@ -407,7 +412,7 @@ namespace Timeline.Services // It follows all timeline-related function common interface contracts. private async Task FindTimelineId(string timelineName) { - timelineName = ExtractTimelineName(timelineName, out var isPersonal); + timelineName = TimelineHelper.ExtractTimelineName(timelineName, out var isPersonal); if (isPersonal) { @@ -713,16 +718,26 @@ namespace Timeline.Services var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync(); + var changed = false; + if (newProperties.Description != null) { + changed = true; timelineEntity.Description = newProperties.Description; } if (newProperties.Visibility.HasValue) { + changed = true; timelineEntity.Visibility = newProperties.Visibility.Value; } + if (changed) + { + var currentTime = _clock.GetCurrentTime(); + timelineEntity.LastModified = currentTime; + } + await _database.SaveChangesAsync(); } @@ -768,8 +783,17 @@ namespace Timeline.Services simplifiedAdd.Remove(u); simplifiedRemove.Remove(u); } + + if (simplifiedAdd.Count == 0) + simplifiedAdd = null; + + if (simplifiedRemove.Count == 0) + simplifiedRemove = null; } + if (simplifiedAdd == null && simplifiedRemove == null) + return; + var timelineId = await FindTimelineId(timelineName); async Task?> CheckExistenceAndGetId(List? list) @@ -799,6 +823,9 @@ namespace Timeline.Services _database.TimelineMembers.RemoveRange(membersToRemove); } + var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync(); + timelineEntity.LastModified = _clock.GetCurrentTime(); + await _database.SaveChangesAsync(); } -- cgit v1.2.3 From c5c50332aebd9a3e7d5d2c9163f0cad6c6ba241b Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 18 Jun 2020 17:49:02 +0800 Subject: feat(back): Add last modified to timeline. --- .../IntegratedTests/IntegratedTestBase.cs | 3 +- Timeline.Tests/IntegratedTests/TimelineTest.cs | 72 ++++++++++++++++++---- Timeline/Models/Http/Timeline.cs | 3 + 3 files changed, 65 insertions(+), 13 deletions(-) (limited to 'Timeline.Tests') diff --git a/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs b/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs index b5aec512..7cf27297 100644 --- a/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs +++ b/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.TestHost; +using FluentAssertions; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; diff --git a/Timeline.Tests/IntegratedTests/TimelineTest.cs b/Timeline.Tests/IntegratedTests/TimelineTest.cs index b6a56e94..6736fecd 100644 --- a/Timeline.Tests/IntegratedTests/TimelineTest.cs +++ b/Timeline.Tests/IntegratedTests/TimelineTest.cs @@ -78,10 +78,12 @@ namespace Timeline.Tests.IntegratedTests return $"timelines/t{id}/{(subpath ?? "")}"; } + public delegate string TimelineUrlGenerator(int userId, string subpath = null); + public static IEnumerable TimelineUrlGeneratorData() { - yield return new[] { new Func(GeneratePersonalTimelineUrl) }; - yield return new[] { new Func(GenerateOrdinaryTimelineUrl) }; + yield return new[] { new TimelineUrlGenerator(GeneratePersonalTimelineUrl) }; + yield return new[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl) }; } private static string GeneratePersonalTimelineUrlByName(string name, string subpath = null) @@ -545,7 +547,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task Description_Should_Work(Func generator) + public async Task Description_Should_Work(TimelineUrlGenerator generator) { using var client = await CreateClientAsUser(); @@ -585,7 +587,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task Member_Should_Work(Func generator) + public async Task Member_Should_Work(TimelineUrlGenerator generator) { var getUrl = generator(1, null); using var client = await CreateClientAsUser(); @@ -682,7 +684,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task Visibility_Test(Func generator) + public async Task Visibility_Test(TimelineUrlGenerator generator) { var userUrl = generator(1, "posts"); var adminUrl = generator(0, "posts"); @@ -765,7 +767,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task Permission_Post_Create(Func generator) + public async Task Permission_Post_Create(TimelineUrlGenerator generator) { using (var client = await CreateClientAsUser()) { @@ -817,7 +819,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task Permission_Post_Delete(Func generator) + public async Task Permission_Post_Delete(TimelineUrlGenerator generator) { async Task CreatePost(int userNumber) { @@ -885,7 +887,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task TextPost_ShouldWork(Func generator) + public async Task TextPost_ShouldWork(TimelineUrlGenerator generator) { { using var client = await CreateClientAsUser(); @@ -963,7 +965,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task GetPost_Should_Ordered(Func generator) + public async Task GetPost_Should_Ordered(TimelineUrlGenerator generator) { using var client = await CreateClientAsUser(); @@ -991,7 +993,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task CreatePost_InvalidModel(Func generator) + public async Task CreatePost_InvalidModel(TimelineUrlGenerator generator) { using var client = await CreateClientAsUser(); @@ -1035,7 +1037,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task ImagePost_ShouldWork(Func generator) + public async Task ImagePost_ShouldWork(TimelineUrlGenerator generator) { var imageData = ImageHelper.CreatePngWithSize(100, 200); @@ -1119,7 +1121,7 @@ namespace Timeline.Tests.IntegratedTests [Theory] [MemberData(nameof(TimelineUrlGeneratorData))] - public async Task ImagePost_400(Func generator) + public async Task ImagePost_400(TimelineUrlGenerator generator) { using var client = await CreateClientAsUser(); @@ -1145,5 +1147,51 @@ namespace Timeline.Tests.IntegratedTests .And.HaveCommonBody(ErrorCodes.TimelineController.PostNoData); } } + + [Theory] + [MemberData(nameof(TimelineUrlGeneratorData))] + public async Task LastModified(TimelineUrlGenerator generator) + { + using var client = await CreateClientAsUser(); + + DateTime lastModified; + + { + var res = await client.GetAsync(generator(1)); + lastModified = res.Should().HaveStatusCode(200) + .And.HaveJsonBody() + .Which.LastModified; + } + + await Task.Delay(1000); + + { + var res = await client.PatchAsJsonAsync(generator(1), new TimelinePatchRequest { Description = "123" }); + lastModified = res.Should().HaveStatusCode(200) + .And.HaveJsonBody() + .Which.LastModified.Should().BeAfter(lastModified).And.Subject.Value; + } + + { + var res = await client.GetAsync(generator(1)); + res.Should().HaveStatusCode(200) + .And.HaveJsonBody() + .Which.LastModified.Should().Be(lastModified); + } + + await Task.Delay(1000); + + { + var res = await client.PutAsync(generator(1, "members/user2"), null); + res.Should().HaveStatusCode(200); + } + + { + var res = await client.GetAsync(generator(1)); + res.Should().HaveStatusCode(200) + .And.HaveJsonBody() + .Which.LastModified.Should().BeAfter(lastModified); + } + } } } diff --git a/Timeline/Models/Http/Timeline.cs b/Timeline/Models/Http/Timeline.cs index a942db1e..80e6e69d 100644 --- a/Timeline/Models/Http/Timeline.cs +++ b/Timeline/Models/Http/Timeline.cs @@ -28,12 +28,15 @@ namespace Timeline.Models.Http { public string UniqueId { get; set; } = default!; public string Name { get; set; } = default!; + public DateTime NameLastModifed { get; set; } = default!; public string Description { get; set; } = default!; public UserInfo Owner { get; set; } = default!; public TimelineVisibility Visibility { get; set; } #pragma warning disable CA2227 // Collection properties should be read only public List Members { get; set; } = default!; #pragma warning restore CA2227 // Collection properties should be read only + public DateTime CreateTime { get; set; } = default!; + public DateTime LastModified { get; set; } = default!; #pragma warning disable CA1707 // Identifiers should not contain underscores public TimelineInfoLinks _links { get; set; } = default!; -- cgit v1.2.3