diff options
author | crupest <crupest@outlook.com> | 2020-11-13 17:08:20 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-11-13 17:08:20 +0800 |
commit | 48d53341db4953b3d583dd825b48d854c0a166e9 (patch) | |
tree | 6db1d56071e1fc27d3a21e6c6fb5d0342e2b17c4 | |
parent | 2a132acab30042f068577096f6b97f6961951b0e (diff) | |
download | timeline-48d53341db4953b3d583dd825b48d854c0a166e9.tar.gz timeline-48d53341db4953b3d583dd825b48d854c0a166e9.tar.bz2 timeline-48d53341db4953b3d583dd825b48d854c0a166e9.zip |
...
-rw-r--r-- | BackEnd/Timeline.Tests/ErrorCodeTest.cs | 2 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs | 16 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs | 25 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs | 7 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/ParameterInfoAssertions.cs | 60 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/ReflectionHelper.cs | 13 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs | 94 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/TestApplication.cs | 4 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Helpers/TestClock.cs | 2 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs | 8 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs | 71 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs | 23 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs | 22 | ||||
-rw-r--r-- | BackEnd/Timeline.Tests/Timeline.Tests.csproj | 1 | ||||
-rw-r--r-- | BackEnd/Timeline/Timeline.csproj | 2 |
15 files changed, 97 insertions, 253 deletions
diff --git a/BackEnd/Timeline.Tests/ErrorCodeTest.cs b/BackEnd/Timeline.Tests/ErrorCodeTest.cs index 258ebf4e..94e2a488 100644 --- a/BackEnd/Timeline.Tests/ErrorCodeTest.cs +++ b/BackEnd/Timeline.Tests/ErrorCodeTest.cs @@ -29,7 +29,7 @@ namespace Timeline.Tests .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(int)))
{
var name = type.FullName + "." + field.Name;
- var value = (int)field.GetRawConstantValue();
+ var value = (int)field.GetRawConstantValue()!;
_output.WriteLine($"Find error code {name} , value is {value}.");
value.Should().BeInRange(1000_0000, 9999_9999, "Error code should have exactly 8 digits.");
diff --git a/BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs b/BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs index b3709a28..ef230cb0 100644 --- a/BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs +++ b/BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs @@ -17,31 +17,33 @@ namespace Timeline.Tests.Helpers var res = await client.GetAsync(getUrl);
res.Should().HaveStatusCode(200);
var cacheControlHeader = res.Headers.CacheControl;
- cacheControlHeader.NoCache.Should().BeTrue();
+ cacheControlHeader.Should().NotBeNull();
+ cacheControlHeader!.NoCache.Should().BeTrue();
cacheControlHeader.NoStore.Should().BeFalse();
cacheControlHeader.Private.Should().BeTrue();
cacheControlHeader.Public.Should().BeFalse();
cacheControlHeader.MustRevalidate.Should().BeTrue();
cacheControlHeader.MaxAge.Should().NotBeNull().And.Be(TimeSpan.FromDays(14));
- eTag = res.Headers.ETag;
+ res.Headers.ETag.Should().NotBeNull();
+ eTag = res.Headers.ETag!;
}
{
using var request = new HttpRequestMessage()
{
- RequestUri = new Uri(client.BaseAddress, getUrl),
+ RequestUri = new Uri(client.BaseAddress!, getUrl),
Method = HttpMethod.Get,
};
request.Headers.TryAddWithoutValidation("If-None-Match", "\"dsdfd");
var res = await client.SendAsync(request);
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
- .And.HaveCommonBody(ErrorCodes.Common.Header.IfNonMatch_BadFormat);
+ await res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
+ .And.HaveCommonBodyWithCodeAsync(ErrorCodes.Common.Header.IfNonMatch_BadFormat);
}
{
using var request = new HttpRequestMessage()
{
- RequestUri = new Uri(client.BaseAddress, getUrl),
+ RequestUri = new Uri(client.BaseAddress!, getUrl),
Method = HttpMethod.Get,
};
request.Headers.TryAddWithoutValidation("If-None-Match", "\"aaa\"");
@@ -52,7 +54,7 @@ namespace Timeline.Tests.Helpers {
using var request = new HttpRequestMessage()
{
- RequestUri = new Uri(client.BaseAddress, getUrl),
+ RequestUri = new Uri(client.BaseAddress!, getUrl),
Method = HttpMethod.Get,
};
request.Headers.Add("If-None-Match", eTag.ToString());
diff --git a/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs b/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs index 6513bbe7..47335a22 100644 --- a/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs +++ b/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs @@ -1,5 +1,4 @@ -using Newtonsoft.Json;
-using System;
+using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
@@ -10,41 +9,27 @@ namespace Timeline.Tests.Helpers {
public static class HttpClientExtensions
{
- public static Task<HttpResponseMessage> PatchAsJsonAsync<T>(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<HttpResponseMessage> PatchAsJsonAsync<T>(this HttpClient client, Uri url, T body)
- {
- return client.PatchAsync(url, new StringContent(
- JsonConvert.SerializeObject(body), Encoding.UTF8, MediaTypeNames.Application.Json));
- }
-
public static Task<HttpResponseMessage> 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<HttpResponseMessage> PutByteArrayAsync(this HttpClient client, Uri url, byte[] body, string mimeType)
{
- var content = new ByteArrayContent(body);
+ using var content = new ByteArrayContent(body);
content.Headers.ContentLength = body.Length;
content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
return client.PutAsync(url, content);
}
- public static Task<HttpResponseMessage> PutStringAsync(this HttpClient client, string url, string body, string mimeType = null)
+ public static Task<HttpResponseMessage> PutStringAsync(this HttpClient client, string url, string body, string? mimeType = null)
{
return client.PutStringAsync(new Uri(url, UriKind.RelativeOrAbsolute), body, mimeType);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
- public static Task<HttpResponseMessage> PutStringAsync(this HttpClient client, Uri url, string body, string mimeType = null)
+ public static Task<HttpResponseMessage> PutStringAsync(this HttpClient client, Uri url, string body, string? mimeType = null)
{
- var content = new StringContent(body, Encoding.UTF8, mimeType ?? MediaTypeNames.Text.Plain);
+ using var content = new StringContent(body, Encoding.UTF8, mimeType ?? MediaTypeNames.Text.Plain);
return client.PutAsync(url, content);
}
}
diff --git a/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs b/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs index 2bd497f1..01497434 100644 --- a/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs +++ b/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs @@ -21,15 +21,10 @@ namespace Timeline.Tests.Helpers JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter());
}
- public static async Task<T> ReadBodyAsJsonAsync<T>(this HttpResponseMessage response)
+ public static async Task<T?> ReadBodyAsJsonAsync<T>(this HttpResponseMessage response)
{
var stream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<T>(stream, JsonSerializerOptions);
}
-
- public static Task<CommonResponse> ReadBodyAsCommonResponseAsync(this HttpResponseMessage response)
- {
- return response.ReadBodyAsJsonAsync<CommonResponse>();
- }
}
}
diff --git a/BackEnd/Timeline.Tests/Helpers/ParameterInfoAssertions.cs b/BackEnd/Timeline.Tests/Helpers/ParameterInfoAssertions.cs deleted file mode 100644 index d3e5a41e..00000000 --- a/BackEnd/Timeline.Tests/Helpers/ParameterInfoAssertions.cs +++ /dev/null @@ -1,60 +0,0 @@ -using FluentAssertions;
-using FluentAssertions.Execution;
-using FluentAssertions.Formatting;
-using FluentAssertions.Primitives;
-using System;
-using System.Reflection;
-
-namespace Timeline.Tests.Helpers
-{
- public class ParameterInfoValueFormatter : IValueFormatter
- {
- public bool CanHandle(object value)
- {
- return value is ParameterInfo;
- }
-
- public string Format(object value, FormattingContext context, FormatChild formatChild)
- {
- var param = (ParameterInfo)value;
- return $"{param.Member.DeclaringType.FullName}.{param.Member.Name}#{param.Name}";
- }
- }
-
- public class ParameterInfoAssertions : ReferenceTypeAssertions<ParameterInfo, ParameterInfoAssertions>
- {
- static ParameterInfoAssertions()
- {
- Formatter.AddFormatter(new ParameterInfoValueFormatter());
- }
-
- public ParameterInfoAssertions(ParameterInfo parameterInfo)
- {
- Subject = parameterInfo;
- }
-
- protected override string Identifier => "parameter";
-
- public AndWhichConstraint<ParameterInfoAssertions, TAttribute> BeDecoratedWith<TAttribute>(string because = "", params object[] becauseArgs)
- where TAttribute : Attribute
- {
- var attribute = Subject.GetCustomAttribute<TAttribute>(false);
-
- Execute.Assertion
- .BecauseOf(because, becauseArgs)
- .ForCondition(attribute != null)
- .FailWith("Expected {0} {1} to be decorated with {2}{reason}, but that attribute was not found.",
- Identifier, Subject, typeof(TAttribute).FullName);
-
- return new AndWhichConstraint<ParameterInfoAssertions, TAttribute>(this, attribute);
- }
- }
-
- public static class ParameterInfoAssertionExtensions
- {
- public static ParameterInfoAssertions Should(this ParameterInfo parameterInfo)
- {
- return new ParameterInfoAssertions(parameterInfo);
- }
- }
-}
diff --git a/BackEnd/Timeline.Tests/Helpers/ReflectionHelper.cs b/BackEnd/Timeline.Tests/Helpers/ReflectionHelper.cs deleted file mode 100644 index 3f6036e3..00000000 --- a/BackEnd/Timeline.Tests/Helpers/ReflectionHelper.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Linq;
-using System.Reflection;
-
-namespace Timeline.Tests.Helpers
-{
- public static class ReflectionHelper
- {
- public static ParameterInfo GetParameter(this MethodInfo methodInfo, string name)
- {
- return methodInfo.GetParameters().Where(p => p.Name == name).Single();
- }
- }
-}
diff --git a/BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs b/BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs index 024732f5..95df3eda 100644 --- a/BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs +++ b/BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs @@ -6,9 +6,11 @@ using System; using System.Globalization;
using System.Net;
using System.Net.Http;
+using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
+using System.Threading.Tasks;
using Timeline.Models.Converters;
using Timeline.Models.Http;
@@ -27,27 +29,7 @@ namespace Timeline.Tests.Helpers string padding = new string('\t', context.Depth);
var res = (HttpResponseMessage)value;
-
- var builder = new StringBuilder();
- builder.Append($"{newline}{padding} Status Code: {res.StatusCode} ; Body: ");
-
- try
- {
- var task = res.Content.ReadAsStringAsync();
- task.Wait();
- var body = task.Result;
- if (body.Length > 40)
- {
- body = body[0..40] + " ...";
- }
- builder.Append(body);
- }
- catch (AggregateException)
- {
- builder.Append("NOT A STRING.");
- }
-
- return builder.ToString();
+ return $"{newline}{padding} Status Code: {res.StatusCode}";
}
}
@@ -79,41 +61,17 @@ namespace Timeline.Tests.Helpers return new AndConstraint<HttpResponseMessageAssertions>(this);
}
- public AndWhichConstraint<HttpResponseMessageAssertions, T> HaveJsonBody<T>(string because = "", params object[] becauseArgs)
+ public async Task<T> HaveAndGetJsonBodyAsync<T>(string because = "", params object[] becauseArgs)
{
var a = Execute.Assertion.BecauseOf(because, becauseArgs);
- string body;
- try
- {
- var task = Subject.Content.ReadAsStringAsync();
- task.Wait();
- body = task.Result;
- }
- 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.InnerExceptions);
- return new AndWhichConstraint<HttpResponseMessageAssertions, T>(this, null);
- }
-
- try
- {
- var options = new JsonSerializerOptions
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase
- };
- options.Converters.Add(new JsonStringEnumConverter());
- options.Converters.Add(new JsonDateTimeConverter());
-
- var result = JsonSerializer.Deserialize<T>(body, options);
-
- return new AndWhichConstraint<HttpResponseMessageAssertions, T>(this, result);
- }
- catch (JsonException e)
+ var body = await Subject.ReadBodyAsJsonAsync<T>();
+ if (body == null)
{
- a.FailWith("Expected response body of {context:HttpResponseMessage} to be json string{reason}, but failed to deserialize it. Exception is {0}.", e);
- return new AndWhichConstraint<HttpResponseMessageAssertions, T>(this, null);
+ a.FailWith("Expected response body of {context:HttpResponseMessage} to be json string of type {0}{reason}, but failed to read it or it was not a valid json string.", typeof(T).FullName);
+ return default!;
}
+ return body;
}
}
@@ -124,47 +82,45 @@ namespace Timeline.Tests.Helpers return new HttpResponseMessageAssertions(instance);
}
- public static AndWhichConstraint<HttpResponseMessageAssertions, CommonResponse> HaveCommonBody(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
+ public static Task<CommonResponse> HaveAndGetCommonBodyAsync(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
{
- return assertions.HaveJsonBody<CommonResponse>(because, becauseArgs);
+ return assertions.HaveAndGetJsonBodyAsync<CommonResponse>(because, becauseArgs);
}
- public static void HaveCommonBody(this HttpResponseMessageAssertions assertions, int code, string message = null, params object[] messageArgs)
+ public static async Task HaveCommonBodyWithCodeAsync(this HttpResponseMessageAssertions assertions, int code, string? message = null, params object[] messageArgs)
{
message = string.IsNullOrEmpty(message) ? "" : ", " + string.Format(CultureInfo.CurrentCulture, message, messageArgs);
- var body = assertions.HaveCommonBody("Response body should be CommonResponse{0}", message).Which;
+ var body = await assertions.HaveAndGetCommonBodyAsync("Response body should be CommonResponse{0}", message);
body.Code.Should().Be(code, "Response body code is not the specified one{0}", message);
}
- public static AndWhichConstraint<HttpResponseMessageAssertions, CommonDataResponse<TData>> HaveCommonDataBody<TData>(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
+ public static Task<CommonDataResponse<TData>> HaveAndGetCommonDataBodyAsync<TData>(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
{
- return assertions.HaveJsonBody<CommonDataResponse<TData>>(because, becauseArgs);
+ return assertions.HaveAndGetJsonBodyAsync<CommonDataResponse<TData>>(because, becauseArgs);
}
- public static void BePut(this HttpResponseMessageAssertions assertions, bool create, string because = "", params object[] becauseArgs)
+ public static async Task BePutAsync(this HttpResponseMessageAssertions assertions, bool create, string because = "", params object[] becauseArgs)
{
- var body = assertions.HaveStatusCode(create ? 201 : 200, because, becauseArgs)
- .And.HaveJsonBody<CommonPutResponse>(because, becauseArgs)
- .Which;
+ var body = await assertions.HaveStatusCode(create ? 201 : 200, because, becauseArgs)
+ .And.HaveAndGetJsonBodyAsync<CommonPutResponse>(because, becauseArgs);
body.Code.Should().Be(0);
body.Data.Create.Should().Be(create);
}
- public static void BeDelete(this HttpResponseMessageAssertions assertions, bool delete, string because = "", params object[] becauseArgs)
+ public static async Task BeDeleteAsync(this HttpResponseMessageAssertions assertions, bool delete, string because = "", params object[] becauseArgs)
{
- var body = assertions.HaveStatusCode(200, because, becauseArgs)
- .And.HaveJsonBody<CommonDeleteResponse>(because, becauseArgs)
- .Which;
+ var body = await assertions.HaveStatusCode(200, because, becauseArgs)
+ .And.HaveAndGetJsonBodyAsync<CommonDeleteResponse>(because, becauseArgs);
body.Code.Should().Be(0);
body.Data.Delete.Should().Be(delete);
}
- public static void BeInvalidModel(this HttpResponseMessageAssertions assertions, string message = null)
+ public static async Task BeInvalidModelAsync(this HttpResponseMessageAssertions assertions, string message = null)
{
message = string.IsNullOrEmpty(message) ? "" : ", " + message;
- assertions.HaveStatusCode(400, "Invalid Model Error must have 400 status code{0}", message)
- .And.HaveCommonBody("Invalid Model Error must have CommonResponse body{0}", message)
- .Which.Code.Should().Be(ErrorCodes.Common.InvalidModel,
+ var body = await assertions.HaveStatusCode(400, "Invalid Model Error must have 400 status code{0}", message)
+ .And.HaveAndGetCommonBodyAsync("Invalid Model Error must have CommonResponse body{0}", message);
+ body.Code.Should().Be(ErrorCodes.Common.InvalidModel,
"Invalid Model Error must have code {0} in body{1}",
ErrorCodes.Common.InvalidModel, message);
}
diff --git a/BackEnd/Timeline.Tests/Helpers/TestApplication.cs b/BackEnd/Timeline.Tests/Helpers/TestApplication.cs index 33d8b318..da8dea46 100644 --- a/BackEnd/Timeline.Tests/Helpers/TestApplication.cs +++ b/BackEnd/Timeline.Tests/Helpers/TestApplication.cs @@ -17,9 +17,9 @@ namespace Timeline.Tests.Helpers {
public TestDatabase Database { get; }
- public IHost Host { get; private set; }
+ public IHost Host { get; private set; } = default!;
- public string WorkDir { get; private set; }
+ public string WorkDir { get; private set; } = default!;
public TestApplication()
{
diff --git a/BackEnd/Timeline.Tests/Helpers/TestClock.cs b/BackEnd/Timeline.Tests/Helpers/TestClock.cs index a04a3eb6..7fa17fbe 100644 --- a/BackEnd/Timeline.Tests/Helpers/TestClock.cs +++ b/BackEnd/Timeline.Tests/Helpers/TestClock.cs @@ -33,7 +33,7 @@ namespace Timeline.Tests.Helpers {
if (_currentTime == null)
return SetMockCurrentTime();
- _currentTime += timeSpan;
+ _currentTime = _currentTime.Value + timeSpan;
return _currentTime.Value;
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs index 39a6e545..86cde11f 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs @@ -14,7 +14,9 @@ namespace Timeline.Tests.IntegratedTests using var client = await CreateDefaultClient(false);
var res = await client.GetAsync("index.html");
res.Should().HaveStatusCode(200);
- res.Content.Headers.ContentType.MediaType.Should().Be(MediaTypeNames.Text.Html);
+ var contentTypeHeader = res.Content.Headers.ContentType;
+ contentTypeHeader.Should().NotBeNull();
+ contentTypeHeader!.MediaType.Should().Be(MediaTypeNames.Text.Html);
}
[Fact]
@@ -23,7 +25,9 @@ namespace Timeline.Tests.IntegratedTests using var client = await CreateDefaultClient(false);
var res = await client.GetAsync("aaaaaaaaaaaaaaa");
res.Should().HaveStatusCode(200);
- res.Content.Headers.ContentType.MediaType.Should().Be(MediaTypeNames.Text.Html);
+ var contentTypeHeader = res.Content.Headers.ContentType;
+ contentTypeHeader.Should().NotBeNull();
+ contentTypeHeader!.MediaType.Should().Be(MediaTypeNames.Text.Html);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs index f75ce69c..79d2d5bf 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs @@ -19,8 +19,6 @@ namespace Timeline.Tests.IntegratedTests {
protected TestApplication TestApp { get; }
- public IReadOnlyList<UserInfo> UserInfos { get; private set; }
-
private readonly int _userCount;
public IntegratedTestBase() : this(1)
@@ -48,54 +46,45 @@ namespace Timeline.Tests.IntegratedTests return Task.CompletedTask;
}
+ protected virtual void OnInitialize()
+ {
+
+ }
+
protected virtual void OnDispose()
{
}
- public async Task InitializeAsync()
+ private async Task CreateUsers()
{
- await TestApp.InitializeAsync();
+ using var scope = TestApp.Host.Services.CreateScope();
- using (var scope = TestApp.Host.Services.CreateScope())
- {
- var users = new List<(string username, string password, string nickname)>()
+ var users = new List<(string username, string password, string nickname)>()
{
("admin", "adminpw", "administrator")
};
- for (int i = 1; i <= _userCount; i++)
- {
- users.Add(($"user{i}", $"user{i}pw", $"imuser{i}"));
- }
-
- var userInfoList = new List<UserInfo>();
-
- var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
- foreach (var user in users)
- {
- var (username, password, nickname) = user;
- var u = await userService.CreateUser(username, password);
- await userService.ModifyUser(u.Id, new ModifyUserParams() { Nickname = nickname });
- }
-
- using var client = await CreateDefaultClient();
- var options = new JsonSerializerOptions
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase
- };
- options.Converters.Add(new JsonStringEnumConverter());
- options.Converters.Add(new JsonDateTimeConverter());
- foreach (var user in users)
- {
- var s = await client.GetStringAsync($"users/{user.username}");
- userInfoList.Add(JsonSerializer.Deserialize<UserInfo>(s, options));
- }
+ for (int i = 1; i <= _userCount; i++)
+ {
+ users.Add(($"user{i}", $"user{i}pw", $"imuser{i}"));
+ }
- UserInfos = userInfoList;
+ var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
+ foreach (var user in users)
+ {
+ var (username, password, nickname) = user;
+ var u = await userService.CreateUser(username, password);
+ await userService.ModifyUser(u.Id, new ModifyUserParams() { Nickname = nickname });
}
+ }
+ public async Task InitializeAsync()
+ {
+ await TestApp.InitializeAsync();
+ await CreateUsers();
await OnInitializeAsync();
+ OnInitialize();
}
public async Task DisposeAsync()
@@ -110,22 +99,18 @@ namespace Timeline.Tests.IntegratedTests var client = TestApp.Host.GetTestServer().CreateClient();
if (setApiBase)
{
- client.BaseAddress = new Uri(client.BaseAddress, "api/");
+ client.BaseAddress = new Uri(client.BaseAddress!, "api/");
}
return Task.FromResult(client);
}
public async Task<HttpClient> CreateClientWithCredential(string username, string password, bool setApiBase = true)
{
- var client = TestApp.Host.GetTestServer().CreateClient();
- if (setApiBase)
- {
- client.BaseAddress = new Uri(client.BaseAddress, "api/");
- }
+ var client = await CreateDefaultClient(setApiBase);
var response = await client.PostAsJsonAsync("token/create",
new CreateTokenRequest { Username = username, Password = password });
- var token = response.Should().HaveStatusCode(200)
- .And.HaveJsonBody<CreateTokenResponse>().Which.Token;
+ var token = (await response.Should().HaveStatusCode(200)
+ .And.HaveAndGetJsonBodyAsync<CreateTokenResponse>()).Token;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
return client;
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs index ec46b96a..fd574a82 100644 --- a/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs +++ b/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs @@ -55,22 +55,17 @@ namespace Timeline.Tests.IntegratedTests await CreateTestTimelines();
}
- private List<TimelineInfo> _testTimelines;
-
private async Task CreateTestTimelines()
{
- _testTimelines = new List<TimelineInfo>();
for (int i = 0; i <= 3; i++)
{
var client = await CreateClientAs(i);
var res = await client.PostAsJsonAsync("timelines", new TimelineCreateRequest { Name = $"t{i}" });
- var timelineInfo = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
- _testTimelines.Add(timelineInfo);
+ res.Should().HaveStatusCode(200);
}
}
- private static string CalculateUrlTail(string subpath, ICollection<KeyValuePair<string, string>> query)
+ private static string CalculateUrlTail(string? subpath, ICollection<KeyValuePair<string, string>>? query)
{
StringBuilder result = new StringBuilder();
if (subpath != null)
@@ -96,12 +91,12 @@ namespace Timeline.Tests.IntegratedTests return result.ToString();
}
- private static string GeneratePersonalTimelineUrl(int id, string subpath = null, ICollection<KeyValuePair<string, string>> query = null)
+ private static string GeneratePersonalTimelineUrl(int id, string? subpath = null, ICollection<KeyValuePair<string, string>>? query = null)
{
return $"timelines/@{(id == 0 ? "admin" : ("user" + id))}{CalculateUrlTail(subpath, query)}";
}
- private static string GenerateOrdinaryTimelineUrl(int id, string subpath = null, ICollection<KeyValuePair<string, string>> query = null)
+ private static string GenerateOrdinaryTimelineUrl(int id, string? subpath = null, ICollection<KeyValuePair<string, string>>? query = null)
{
return $"timelines/t{id}{CalculateUrlTail(subpath, query)}";
}
@@ -114,12 +109,12 @@ namespace Timeline.Tests.IntegratedTests yield return new[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl) };
}
- private static string GeneratePersonalTimelineUrlByName(string name, string subpath = null)
+ private static string GeneratePersonalTimelineUrlByName(string name, string? subpath = null)
{
return $"timelines/@{name}{(subpath == null ? "" : "/" + subpath)}";
}
- private static string GenerateOrdinaryTimelineUrlByName(string name, string subpath = null)
+ private static string GenerateOrdinaryTimelineUrlByName(string name, string? subpath = null)
{
return $"timelines/{name}{(subpath == null ? "" : "/" + subpath)}";
}
@@ -136,9 +131,9 @@ namespace Timeline.Tests.IntegratedTests using var client = await CreateDefaultClient();
{
var res = await client.GetAsync("timelines/@user1");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
- body.Owner.Should().BeEquivalentTo(UserInfos[1]);
+ var body = await res.Should().HaveStatusCode(200)
+ .And.HaveAndGetJsonBodyAsync<TimelineInfo>();
+ body.Owner.Should().;
body.Visibility.Should().Be(TimelineVisibility.Register);
body.Description.Should().Be("");
body.Members.Should().NotBeNull().And.BeEmpty();
diff --git a/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs b/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs index 73fdd32f..5f2c20e8 100644 --- a/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs +++ b/BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs @@ -22,19 +22,15 @@ namespace Timeline.Tests.Services private readonly TestClock _clock = new TestClock();
- private DataManager _dataManager;
+ private DataManager _dataManager = default!;
- private UserPermissionService _userPermissionService;
+ private UserPermissionService _userPermissionService = default!;
- private UserService _userService;
+ private UserService _userService = default!;
- private TimelineService _timelineService;
+ private TimelineService _timelineService = default!;
- private UserDeleteService _userDeleteService;
-
- public TimelineServiceTest()
- {
- }
+ private UserDeleteService _userDeleteService = default!;
protected override void OnDatabaseCreated()
{
@@ -140,7 +136,7 @@ namespace Timeline.Tests.Services var posts = await _timelineService.GetPosts(timelineName, testPoint);
posts.Should().HaveCount(3)
- .And.Subject.Select(p => (p.Content as TextTimelinePostContent).Text).Should().Equal(postContentList.Skip(1));
+ .And.Subject.Select(p => ((TextTimelinePostContent)p.Content!).Text).Should().Equal(postContentList.Skip(1));
}
[Theory]
@@ -164,7 +160,7 @@ namespace Timeline.Tests.Services var posts = await _timelineService.GetPosts(timelineName);
posts.Should().HaveCount(4);
posts.Select(p => p.Deleted).Should().Equal(Enumerable.Repeat(false, posts.Count));
- posts.Select(p => ((TextTimelinePostContent)p.Content).Text).Should().Equal(postContentList);
+ posts.Select(p => ((TextTimelinePostContent)p.Content!).Text).Should().Equal(postContentList);
foreach (var id in new long[] { posts[0].Id, posts[2].Id })
{
@@ -174,12 +170,12 @@ namespace Timeline.Tests.Services posts = await _timelineService.GetPosts(timelineName);
posts.Should().HaveCount(2);
posts.Select(p => p.Deleted).Should().Equal(Enumerable.Repeat(false, posts.Count));
- posts.Select(p => ((TextTimelinePostContent)p.Content).Text).Should().Equal(new string[] { "b", "d" });
+ posts.Select(p => ((TextTimelinePostContent)p.Content!).Text).Should().Equal(new string[] { "b", "d" });
posts = await _timelineService.GetPosts(timelineName, includeDeleted: true);
posts.Should().HaveCount(4);
posts.Select(p => p.Deleted).Should().Equal(new bool[] { true, false, true, false });
- posts.Where(p => !p.Deleted).Select(p => ((TextTimelinePostContent)p.Content).Text).Should().Equal(new string[] { "b", "d" });
+ posts.Where(p => !p.Deleted).Select(p => ((TextTimelinePostContent)p.Content!).Text).Should().Equal(new string[] { "b", "d" });
}
[Theory]
diff --git a/BackEnd/Timeline.Tests/Timeline.Tests.csproj b/BackEnd/Timeline.Tests/Timeline.Tests.csproj index 624014d9..95bde9d2 100644 --- a/BackEnd/Timeline.Tests/Timeline.Tests.csproj +++ b/BackEnd/Timeline.Tests/Timeline.Tests.csproj @@ -4,6 +4,7 @@ <TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
diff --git a/BackEnd/Timeline/Timeline.csproj b/BackEnd/Timeline/Timeline.csproj index b6c6b4ba..0cb1b5ba 100644 --- a/BackEnd/Timeline/Timeline.csproj +++ b/BackEnd/Timeline/Timeline.csproj @@ -9,8 +9,6 @@ <LangVersion>9.0</LangVersion>
<Nullable>enable</Nullable>
- <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
- <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
<SpaRoot>ClientApp\</SpaRoot>
<Version>0.3.0</Version>
|