aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline.Tests
diff options
context:
space:
mode:
Diffstat (limited to 'BackEnd/Timeline.Tests')
-rw-r--r--BackEnd/Timeline.Tests/ErrorCodeTest.cs2
-rw-r--r--BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs64
-rw-r--r--BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs51
-rw-r--r--BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs35
-rw-r--r--BackEnd/Timeline.Tests/Helpers/ParameterInfoAssertions.cs60
-rw-r--r--BackEnd/Timeline.Tests/Helpers/ReflectionHelper.cs13
-rw-r--r--BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs172
-rw-r--r--BackEnd/Timeline.Tests/Helpers/TestApplication.cs4
-rw-r--r--BackEnd/Timeline.Tests/Helpers/TestClock.cs2
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/CacheTestHelper.cs55
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/CommonJsonSerializeOptions.cs21
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs14
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/HttpClientTestExtensions.cs273
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/HttpClientTimelineExtensions.cs21
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/HttpClientUserExtensions.cs12
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs82
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs1216
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs58
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UnknownEndpointTest.cs9
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UserAvatarTest.cs151
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs175
-rw-r--r--BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs225
-rw-r--r--BackEnd/Timeline.Tests/Services/DatabaseBasedTest.cs2
-rw-r--r--BackEnd/Timeline.Tests/Services/TimelineServiceTest.cs22
-rw-r--r--BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs2
-rw-r--r--BackEnd/Timeline.Tests/Timeline.Tests.csproj1
-rw-r--r--BackEnd/Timeline.Tests/UsernameValidatorUnitTest.cs1
27 files changed, 910 insertions, 1833 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
deleted file mode 100644
index b3709a28..00000000
--- a/BackEnd/Timeline.Tests/Helpers/CacheTestHelper.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-using FluentAssertions;
-using System;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Threading.Tasks;
-using Timeline.Models.Http;
-
-namespace Timeline.Tests.Helpers
-{
- public static class CacheTestHelper
- {
- public static async Task TestCache(HttpClient client, string getUrl)
- {
- EntityTagHeaderValue eTag;
- {
- var res = await client.GetAsync(getUrl);
- res.Should().HaveStatusCode(200);
- var cacheControlHeader = res.Headers.CacheControl;
- 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;
- }
-
- {
- using var request = new HttpRequestMessage()
- {
- 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);
- }
-
- {
- using var request = new HttpRequestMessage()
- {
- RequestUri = new Uri(client.BaseAddress, getUrl),
- Method = HttpMethod.Get,
- };
- request.Headers.TryAddWithoutValidation("If-None-Match", "\"aaa\"");
- var res = await client.SendAsync(request);
- res.Should().HaveStatusCode(HttpStatusCode.OK);
- }
-
- {
- using var request = new HttpRequestMessage()
- {
- RequestUri = new Uri(client.BaseAddress, getUrl),
- Method = HttpMethod.Get,
- };
- request.Headers.Add("If-None-Match", eTag.ToString());
- var res = await client.SendAsync(request);
- res.Should().HaveStatusCode(HttpStatusCode.NotModified);
- }
- }
- }
-}
diff --git a/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs b/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs
deleted file mode 100644
index 6513bbe7..00000000
--- a/BackEnd/Timeline.Tests/Helpers/HttpClientExtensions.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using Newtonsoft.Json;
-using System;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Mime;
-using System.Text;
-using System.Threading.Tasks;
-
-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);
- 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)
- {
- 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)
- {
- 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
deleted file mode 100644
index 2bd497f1..00000000
--- a/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.Net.Http;
-using System.Text.Json;
-using System.Text.Json.Serialization;
-using System.Threading.Tasks;
-using Timeline.Models.Converters;
-using Timeline.Models.Http;
-
-namespace Timeline.Tests.Helpers
-{
- public static class HttpResponseExtensions
- {
- public static JsonSerializerOptions JsonSerializerOptions { get; }
-
- static HttpResponseExtensions()
- {
- JsonSerializerOptions = new JsonSerializerOptions
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase
- };
- JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
- JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter());
- }
-
- 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
deleted file mode 100644
index 024732f5..00000000
--- a/BackEnd/Timeline.Tests/Helpers/ResponseAssertions.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-using FluentAssertions;
-using FluentAssertions.Execution;
-using FluentAssertions.Formatting;
-using FluentAssertions.Primitives;
-using System;
-using System.Globalization;
-using System.Net;
-using System.Net.Http;
-using System.Text;
-using System.Text.Json;
-using System.Text.Json.Serialization;
-using Timeline.Models.Converters;
-using Timeline.Models.Http;
-
-namespace Timeline.Tests.Helpers
-{
- public class HttpResponseMessageValueFormatter : IValueFormatter
- {
- public bool CanHandle(object value)
- {
- return value is HttpResponseMessage;
- }
-
- public string Format(object value, FormattingContext context, FormatChild formatChild)
- {
- string newline = context.UseLineBreaks ? Environment.NewLine : "";
- 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();
- }
- }
-
- public class HttpResponseMessageAssertions
- : ReferenceTypeAssertions<HttpResponseMessage, HttpResponseMessageAssertions>
- {
- static HttpResponseMessageAssertions()
- {
- Formatter.AddFormatter(new HttpResponseMessageValueFormatter());
- }
-
- public HttpResponseMessageAssertions(HttpResponseMessage instance)
- {
- Subject = instance;
- }
-
- protected override string Identifier => "HttpResponseMessage";
-
- public AndConstraint<HttpResponseMessageAssertions> HaveStatusCode(int expected, string because = "", params object[] becauseArgs)
- {
- return HaveStatusCode((HttpStatusCode)expected, because, becauseArgs);
- }
-
- public AndConstraint<HttpResponseMessageAssertions> HaveStatusCode(HttpStatusCode expected, string because = "", params object[] becauseArgs)
- {
- Execute.Assertion.BecauseOf(because, becauseArgs)
- .ForCondition(Subject.StatusCode == expected)
- .FailWith("Expected status code of {context:HttpResponseMessage} to be {0}{reason}, but found {1}.", expected, Subject.StatusCode);
- return new AndConstraint<HttpResponseMessageAssertions>(this);
- }
-
- public AndWhichConstraint<HttpResponseMessageAssertions, T> HaveJsonBody<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)
- {
- 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);
- }
- }
- }
-
- public static class AssertionResponseExtensions
- {
- public static HttpResponseMessageAssertions Should(this HttpResponseMessage instance)
- {
- return new HttpResponseMessageAssertions(instance);
- }
-
- public static AndWhichConstraint<HttpResponseMessageAssertions, CommonResponse> HaveCommonBody(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
- {
- return assertions.HaveJsonBody<CommonResponse>(because, becauseArgs);
- }
-
- public static void HaveCommonBody(this HttpResponseMessageAssertions assertions, int code, string message = null, params object[] messageArgs)
- {
- message = string.IsNullOrEmpty(message) ? "" : ", " + string.Format(CultureInfo.CurrentCulture, message, messageArgs);
- var body = assertions.HaveCommonBody("Response body should be CommonResponse{0}", message).Which;
- body.Code.Should().Be(code, "Response body code is not the specified one{0}", message);
- }
-
- public static AndWhichConstraint<HttpResponseMessageAssertions, CommonDataResponse<TData>> HaveCommonDataBody<TData>(this HttpResponseMessageAssertions assertions, string because = "", params object[] becauseArgs)
- {
- return assertions.HaveJsonBody<CommonDataResponse<TData>>(because, becauseArgs);
- }
-
- public static void BePut(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;
- 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)
- {
- var body = assertions.HaveStatusCode(200, because, becauseArgs)
- .And.HaveJsonBody<CommonDeleteResponse>(because, becauseArgs)
- .Which;
- body.Code.Should().Be(0);
- body.Data.Delete.Should().Be(delete);
- }
-
- public static void BeInvalidModel(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,
- "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/CacheTestHelper.cs b/BackEnd/Timeline.Tests/IntegratedTests/CacheTestHelper.cs
new file mode 100644
index 00000000..8308eca8
--- /dev/null
+++ b/BackEnd/Timeline.Tests/IntegratedTests/CacheTestHelper.cs
@@ -0,0 +1,55 @@
+using FluentAssertions;
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading.Tasks;
+using Timeline.Models.Http;
+
+namespace Timeline.Tests.IntegratedTests
+{
+ public static class CacheTestHelper
+ {
+ public static async Task TestCache(HttpClient client, string getUrl)
+ {
+ EntityTagHeaderValue eTag;
+
+ {
+ var res = await client.GetAsync(getUrl);
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
+ var cacheControlHeader = res.Headers.CacheControl;
+ 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));
+ res.Headers.ETag.Should().NotBeNull();
+ eTag = res.Headers.ETag!;
+ }
+
+ await client.TestSendAssertErrorAsync(HttpMethod.Get, getUrl,
+ expectedStatusCode: HttpStatusCode.BadRequest,
+ errorCode: ErrorCodes.Common.Header.IfNonMatch_BadFormat,
+ headerSetup: static (headers, _) =>
+ {
+ headers.TryAddWithoutValidation("If-None-Match", "\"dsdfd");
+ });
+
+ await client.TestSendAsync(HttpMethod.Get, getUrl,
+ expectedStatusCode: HttpStatusCode.OK,
+ headerSetup: static (headers, _) =>
+ {
+ headers.TryAddWithoutValidation("If-None-Match", "\"aaa\"");
+ });
+
+ await client.TestSendAsync(HttpMethod.Get, getUrl,
+ expectedStatusCode: HttpStatusCode.NotModified,
+ headerSetup: (headers, _) =>
+ {
+ headers.Add("If-None-Match", eTag.ToString());
+ });
+ }
+ }
+}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/CommonJsonSerializeOptions.cs b/BackEnd/Timeline.Tests/IntegratedTests/CommonJsonSerializeOptions.cs
new file mode 100644
index 00000000..a14c8eef
--- /dev/null
+++ b/BackEnd/Timeline.Tests/IntegratedTests/CommonJsonSerializeOptions.cs
@@ -0,0 +1,21 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Timeline.Models.Converters;
+
+namespace Timeline.Tests.IntegratedTests
+{
+ public static class CommonJsonSerializeOptions
+ {
+ public static JsonSerializerOptions Options { get; }
+
+ static CommonJsonSerializeOptions()
+ {
+ Options = new JsonSerializerOptions
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+ };
+ Options.Converters.Add(new JsonStringEnumConverter());
+ Options.Converters.Add(new JsonDateTimeConverter());
+ }
+ }
+}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs
index 39a6e545..1843c412 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/FrontEndTest.cs
@@ -1,7 +1,7 @@
using FluentAssertions;
+using System.Net;
using System.Net.Mime;
using System.Threading.Tasks;
-using Timeline.Tests.Helpers;
using Xunit;
namespace Timeline.Tests.IntegratedTests
@@ -13,8 +13,10 @@ 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);
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
+ var contentTypeHeader = res.Content.Headers.ContentType;
+ contentTypeHeader.Should().NotBeNull();
+ contentTypeHeader!.MediaType.Should().Be(MediaTypeNames.Text.Html);
}
[Fact]
@@ -22,8 +24,10 @@ 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);
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
+ var contentTypeHeader = res.Content.Headers.ContentType;
+ contentTypeHeader.Should().NotBeNull();
+ contentTypeHeader!.MediaType.Should().Be(MediaTypeNames.Text.Html);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTestExtensions.cs b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTestExtensions.cs
new file mode 100644
index 00000000..7cff0c39
--- /dev/null
+++ b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTestExtensions.cs
@@ -0,0 +1,273 @@
+using FluentAssertions;
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Threading.Tasks;
+using Timeline.Models.Http;
+
+namespace Timeline.Tests.IntegratedTests
+{
+ public delegate void HeaderSetup(HttpRequestHeaders requestHeaders, HttpContentHeaders? contentHeaders);
+
+ public static class HttpClientTestExtensions
+ {
+ public static async Task<HttpResponseMessage> TestSendAsync(this HttpClient client, HttpMethod method, string url, HttpContent? body = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, HeaderSetup? headerSetup = null)
+ {
+ using var req = new HttpRequestMessage
+ {
+ Method = method,
+ RequestUri = new Uri(url, UriKind.Relative),
+ Content = body
+ };
+ headerSetup?.Invoke(req.Headers, body?.Headers);
+ var res = await client.SendAsync(req);
+ res.StatusCode.Should().Be(expectedStatusCode);
+ return res;
+ }
+
+ public static async Task<T> AssertJsonBodyAsync<T>(HttpResponseMessage response)
+ {
+ var body = await response.Content.ReadFromJsonAsync<T>(CommonJsonSerializeOptions.Options);
+ body.Should().NotBeNull($"Body is not json format of type {typeof(T).FullName}");
+ return body!;
+ }
+
+ public static async Task TestJsonSendAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, HeaderSetup? headerSetup = null)
+ {
+ using JsonContent? reqContent = jsonBody == null ? null : JsonContent.Create(jsonBody, options: CommonJsonSerializeOptions.Options);
+ await client.TestSendAsync(method, url, reqContent, expectedStatusCode, headerSetup);
+ }
+
+ public static async Task<T> TestJsonSendAsync<T>(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, HeaderSetup? headerSetup = null)
+ {
+ using JsonContent? reqContent = jsonBody == null ? null : JsonContent.Create(jsonBody, options: CommonJsonSerializeOptions.Options);
+ var res = await client.TestSendAsync(method, url, reqContent, expectedStatusCode, headerSetup);
+ var resBody = await AssertJsonBodyAsync<T>(res);
+ return resBody;
+ }
+
+ public static async Task TestGetAsync(this HttpClient client, string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAsync(HttpMethod.Get, url, expectedStatusCode: expectedStatusCode, headerSetup: headerSetup);
+ }
+
+ public static async Task<T> TestGetAsync<T>(this HttpClient client, string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, HeaderSetup? headerSetup = null)
+ {
+ return await client.TestJsonSendAsync<T>(HttpMethod.Get, url, expectedStatusCode: expectedStatusCode, headerSetup: headerSetup);
+ }
+
+ public static async Task TestPostAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ await client.TestJsonSendAsync(HttpMethod.Post, url, jsonBody, expectedStatusCode: expectedStatusCode);
+ }
+
+ public static async Task<T> TestPostAsync<T>(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ return await client.TestJsonSendAsync<T>(HttpMethod.Post, url, jsonBody, expectedStatusCode: expectedStatusCode);
+ }
+
+ public static async Task TestPutAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ await client.TestJsonSendAsync(HttpMethod.Put, url, jsonBody, expectedStatusCode: expectedStatusCode);
+ }
+
+ public static async Task<T> TestPutAsync<T>(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ return await client.TestJsonSendAsync<T>(HttpMethod.Put, url, jsonBody, expectedStatusCode: expectedStatusCode);
+ }
+
+ public static async Task<T> TestPatchAsync<T>(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ return await client.TestJsonSendAsync<T>(HttpMethod.Patch, url, jsonBody, expectedStatusCode: expectedStatusCode);
+ }
+
+ public static async Task TestDeleteAsync(this HttpClient client, string url, bool? delete = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ if (delete.HasValue)
+ {
+ var body = await client.TestJsonSendAsync<CommonDeleteResponse>(HttpMethod.Delete, url, expectedStatusCode: expectedStatusCode);
+ body.Data.Delete.Should().Be(delete.Value);
+ }
+ else
+ {
+ await client.TestJsonSendAsync(HttpMethod.Delete, url, expectedStatusCode: expectedStatusCode);
+ }
+ }
+
+ public static async Task TestSendAssertErrorAsync(this HttpClient client, HttpMethod method, string url, HttpContent? body = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ var res = await client.TestSendAsync(method, url, body, expectedStatusCode, headerSetup);
+ if (errorCode.HasValue)
+ {
+ var resBody = await AssertJsonBodyAsync<CommonResponse>(res);
+ resBody.Code.Should().Be(errorCode.Value);
+ }
+ }
+
+ public static async Task TestJsonSendAssertErrorAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ using JsonContent? reqContent = jsonBody == null ? null : JsonContent.Create(jsonBody, options: CommonJsonSerializeOptions.Options);
+ await client.TestSendAssertErrorAsync(method, url, reqContent, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestGetAssertErrorAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(HttpMethod.Get, url, jsonBody, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestPostAssertErrorAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(HttpMethod.Post, url, jsonBody, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestPutAssertErrorAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(HttpMethod.Put, url, jsonBody, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestPatchAssertErrorAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(HttpMethod.Patch, url, jsonBody, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestDeleteAssertErrorAsync(this HttpClient client, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(HttpMethod.Delete, url, jsonBody, expectedStatusCode, errorCode, headerSetup);
+ }
+
+ public static async Task TestSendAssertInvalidModelAsync(this HttpClient client, HttpMethod method, string url, HttpContent? body = null)
+ {
+ await client.TestSendAssertErrorAsync(method, url, body, expectedStatusCode: HttpStatusCode.BadRequest, errorCode: ErrorCodes.Common.InvalidModel);
+ }
+
+ public static async Task TestJsonSendAssertInvalidModelAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(method, url, jsonBody, expectedStatusCode: HttpStatusCode.BadRequest, errorCode: ErrorCodes.Common.InvalidModel);
+ }
+
+ public static async Task TestGetAssertInvalidModelAsync(this HttpClient client, string url)
+ {
+ await client.TestJsonSendAssertInvalidModelAsync(HttpMethod.Get, url);
+ }
+
+ public static async Task TestPostAssertInvalidModelAsync(this HttpClient client, string url, object? jsonBody = null)
+ {
+ await client.TestJsonSendAssertInvalidModelAsync(HttpMethod.Post, url, jsonBody);
+ }
+
+ public static async Task TestPutAssertInvalidModelAsync(this HttpClient client, string url, object? jsonBody = null)
+ {
+ await client.TestJsonSendAssertInvalidModelAsync(HttpMethod.Put, url, jsonBody);
+ }
+
+ public static async Task TestPatchAssertInvalidModelAsync(this HttpClient client, string url, object? jsonBody = null)
+ {
+ await client.TestJsonSendAssertInvalidModelAsync(HttpMethod.Patch, url, jsonBody);
+ }
+
+ public static async Task TestDeleteAssertInvalidModelAsync(this HttpClient client, string url, object? jsonBody = null)
+ {
+ await client.TestJsonSendAssertInvalidModelAsync(HttpMethod.Delete, url, jsonBody);
+ }
+
+ public static async Task TestJsonSendAssertUnauthorizedAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(method, url, jsonBody, HttpStatusCode.Unauthorized, errorCode, headerSetup);
+ }
+
+ public static async Task TestGetAssertUnauthorizedAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertUnauthorizedAsync(HttpMethod.Get, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPostAssertUnauthorizedAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertUnauthorizedAsync(HttpMethod.Post, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPatchAssertUnauthorizedAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertUnauthorizedAsync(HttpMethod.Patch, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestDeleteAssertUnauthorizedAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertUnauthorizedAsync(HttpMethod.Delete, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestJsonSendAssertForbiddenAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(method, url, jsonBody, HttpStatusCode.Forbidden, errorCode, headerSetup);
+ }
+
+ public static async Task TestGetAssertForbiddenAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertForbiddenAsync(HttpMethod.Get, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPostAssertForbiddenAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertForbiddenAsync(HttpMethod.Post, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPatchAssertForbiddenAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertForbiddenAsync(HttpMethod.Patch, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestDeleteAssertForbiddenAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertForbiddenAsync(HttpMethod.Delete, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestJsonSendAssertNotFoundAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertErrorAsync(method, url, jsonBody, HttpStatusCode.NotFound, errorCode, headerSetup);
+ }
+
+ public static async Task TestGetAssertNotFoundAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertNotFoundAsync(HttpMethod.Get, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPutAssertNotFoundAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertNotFoundAsync(HttpMethod.Put, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestPatchAssertNotFoundAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertNotFoundAsync(HttpMethod.Patch, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task TestDeleteAssertNotFoundAsync(this HttpClient client, string url, object? jsonBody = null, int? errorCode = null, HeaderSetup? headerSetup = null)
+ {
+ await client.TestJsonSendAssertNotFoundAsync(HttpMethod.Delete, url, jsonBody, errorCode, headerSetup);
+ }
+
+ public static async Task<HttpResponseMessage> TestPutByteArrayAsync(this HttpClient client, string url, byte[] body, string mimeType, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
+ {
+ using var content = new ByteArrayContent(body);
+ content.Headers.ContentLength = body.Length;
+ content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
+ return await client.TestSendAsync(HttpMethod.Put, url, content, expectedStatusCode);
+ }
+
+ public static async Task TestPutByteArrayAssertErrorAsync(this HttpClient client, string url, byte[] body, string mimeType, HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest, int? errorCode = null)
+ {
+ var res = await client.TestPutByteArrayAsync(url, body, mimeType, expectedStatusCode);
+ if (errorCode.HasValue)
+ {
+ var resBody = await AssertJsonBodyAsync<CommonResponse>(res);
+ resBody.Code.Should().Be(errorCode.Value);
+ }
+ }
+
+ public static async Task TestPutByteArrayAssertInvalidModelAsync(this HttpClient client, string url, byte[] body, string mimeType)
+ {
+ await client.TestPutByteArrayAssertErrorAsync(url, body, mimeType, errorCode: ErrorCodes.Common.InvalidModel);
+ }
+ }
+}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTimelineExtensions.cs b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTimelineExtensions.cs
new file mode 100644
index 00000000..8e48ccbf
--- /dev/null
+++ b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientTimelineExtensions.cs
@@ -0,0 +1,21 @@
+using System.Net.Http;
+using System.Threading.Tasks;
+using Timeline.Models.Http;
+
+namespace Timeline.Tests.IntegratedTests
+{
+ public static class HttpClientTimelineExtensions
+ {
+ public static Task<TimelineInfo> GetTimelineAsync(this HttpClient client, string timelineName)
+ => client.TestGetAsync<TimelineInfo>($"timelines/{timelineName}");
+
+ public static Task<TimelineInfo> PatchTimelineAsync(this HttpClient client, string timelineName, TimelinePatchRequest body)
+ => client.TestPatchAsync<TimelineInfo>($"timelines/{timelineName}", body);
+
+ public static Task PutTimelineMemberAsync(this HttpClient client, string timelineName, string memberUsername)
+ => client.TestPutAsync($"timelines/{timelineName}/members/{memberUsername}");
+
+ public static Task DeleteTimelineMemberAsync(this HttpClient client, string timelineName, string memberUsername, bool? delete)
+ => client.TestDeleteAsync($"timelines/{timelineName}/members/{memberUsername}", delete);
+ }
+}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/HttpClientUserExtensions.cs b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientUserExtensions.cs
new file mode 100644
index 00000000..81787eef
--- /dev/null
+++ b/BackEnd/Timeline.Tests/IntegratedTests/HttpClientUserExtensions.cs
@@ -0,0 +1,12 @@
+using System.Net.Http;
+using System.Threading.Tasks;
+using Timeline.Models.Http;
+
+namespace Timeline.Tests.IntegratedTests
+{
+ public static class HttpClientUserExtensions
+ {
+ public static Task<UserInfo> GetUserAsync(this HttpClient client, string username)
+ => client.TestGetAsync<UserInfo>($"users/{username}");
+ }
+}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs
index f75ce69c..e426ac98 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/IntegratedTestBase.cs
@@ -1,13 +1,9 @@
-using FluentAssertions;
-using Microsoft.AspNetCore.TestHost;
+using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Net.Http;
-using System.Text.Json;
-using System.Text.Json.Serialization;
using System.Threading.Tasks;
-using Timeline.Models.Converters;
using Timeline.Models.Http;
using Timeline.Services;
using Timeline.Tests.Helpers;
@@ -19,9 +15,7 @@ namespace Timeline.Tests.IntegratedTests
{
protected TestApplication TestApp { get; }
- public IReadOnlyList<UserInfo> UserInfos { get; private set; }
-
- private readonly int _userCount;
+ protected int TestUserCount { get; }
public IntegratedTestBase() : this(1)
{
@@ -33,7 +27,7 @@ namespace Timeline.Tests.IntegratedTests
if (userCount < 0)
throw new ArgumentOutOfRangeException(nameof(userCount), userCount, "User count can't be negative.");
- _userCount = userCount;
+ TestUserCount = userCount;
TestApp = new TestApplication();
}
@@ -48,54 +42,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 <= TestUserCount; 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 +95,17 @@ 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 response = await client.PostAsJsonAsync("token/create",
+ var client = await CreateDefaultClient(setApiBase);
+ var res = await client.TestPostAsync<CreateTokenResponse>("token/create",
new CreateTokenRequest { Username = username, Password = password });
- var token = response.Should().HaveStatusCode(200)
- .And.HaveJsonBody<CreateTokenResponse>().Which.Token;
+ var token = res.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..9845e1b1 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/TimelineTest.cs
@@ -8,8 +8,6 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
-using System.Net.Http;
-using System.Text;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Models;
@@ -55,90 +53,27 @@ 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);
+ using var client = await CreateClientAs(i);
+ await client.TestPostAsync("timelines", new TimelineCreateRequest { Name = $"t{i}" });
}
}
- private static string CalculateUrlTail(string subpath, ICollection<KeyValuePair<string, string>> query)
- {
- StringBuilder result = new StringBuilder();
- if (subpath != null)
- {
- if (!subpath.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- result.Append('/');
- result.Append(subpath);
- }
-
- if (query != null && query.Count != 0)
- {
- result.Append('?');
- foreach (var (key, value, index) in query.Select((pair, index) => (pair.Key, pair.Value, index)))
- {
- result.Append(WebUtility.UrlEncode(key));
- result.Append('=');
- result.Append(WebUtility.UrlEncode(value));
- if (index != query.Count - 1)
- result.Append('&');
- }
- }
-
- return result.ToString();
- }
-
- 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)
- {
- return $"timelines/t{id}{CalculateUrlTail(subpath, query)}";
- }
-
- public delegate string TimelineUrlGenerator(int userId, string subpath = null, ICollection<KeyValuePair<string, string>> query = null);
-
- public static IEnumerable<object[]> TimelineUrlGeneratorData()
- {
- yield return new[] { new TimelineUrlGenerator(GeneratePersonalTimelineUrl) };
- yield return new[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl) };
- }
-
- private static string GeneratePersonalTimelineUrlByName(string name, string subpath = null)
- {
- return $"timelines/@{name}{(subpath == null ? "" : "/" + subpath)}";
- }
-
- private static string GenerateOrdinaryTimelineUrlByName(string name, string subpath = null)
- {
- return $"timelines/{name}{(subpath == null ? "" : "/" + subpath)}";
- }
-
- public static IEnumerable<object[]> TimelineUrlByNameGeneratorData()
- {
- yield return new[] { new Func<string, string, string>(GeneratePersonalTimelineUrlByName) };
- yield return new[] { new Func<string, string, string>(GenerateOrdinaryTimelineUrlByName) };
- }
-
[Fact]
public async Task TimelineGet_Should_Work()
{
using var client = await CreateDefaultClient();
+
+ await client.TestGetAssertInvalidModelAsync("timelines/@!!!");
+ await client.TestGetAssertInvalidModelAsync("timelines/!!!");
+
+
{
- 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 client.TestGetAsync<TimelineInfo>("timelines/@user1");
+ body.Owner.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
body.Visibility.Should().Be(TimelineVisibility.Register);
body.Description.Should().Be("");
body.Members.Should().NotBeNull().And.BeEmpty();
@@ -149,10 +84,8 @@ namespace Timeline.Tests.IntegratedTests
}
{
- var res = await client.GetAsync("timelines/t1");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
- body.Owner.Should().BeEquivalentTo(UserInfos[1]);
+ var body = await client.TestGetAsync<TimelineInfo>("timelines/t1");
+ body.Owner.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
body.Visibility.Should().Be(TimelineVisibility.Register);
body.Description.Should().Be("");
body.Members.Should().NotBeNull().And.BeEmpty();
@@ -164,33 +97,36 @@ namespace Timeline.Tests.IntegratedTests
}
[Fact]
- public async Task TimelineList()
+ public async Task TimelineList_Should_Work()
{
- TimelineInfo user1Timeline;
+ using var client = await CreateDefaultClient();
- var client = await CreateDefaultClient();
+ var result = new List<TimelineInfo>
+ {
+ await client.GetTimelineAsync("@user1")
+ };
+ for (int i = 0; i <= TestUserCount; i++)
{
- var res = await client.GetAsync("timelines/@user1");
- user1Timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ result.Add(await client.GetTimelineAsync($"t{i}"));
}
- {
- var testResult = new List<TimelineInfo>();
- testResult.Add(user1Timeline);
- testResult.AddRange(_testTimelines);
- var res = await client.GetAsync("timelines");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which.Should().BeEquivalentTo(testResult);
- }
+ var body = await client.TestGetAsync<List<TimelineInfo>>("timelines");
+ body.Should().BeEquivalentTo(result);
}
[Fact]
- public async Task TimelineList_WithQuery()
+ public async Task TimelineListWithQuery_Should_Work()
{
+ {
+ using var client = await CreateDefaultClient();
+
+ await client.TestGetAssertInvalidModelAsync("timelines?relate=us!!");
+ await client.TestGetAssertInvalidModelAsync("timelines?relateType=aaa");
+ await client.TestGetAssertInvalidModelAsync("timelines?visibility=aaa");
+ }
+
var testResultRelate = new List<TimelineInfo>();
var testResultOwn = new List<TimelineInfo>();
var testResultJoin = new List<TimelineInfo>();
@@ -201,32 +137,15 @@ namespace Timeline.Tests.IntegratedTests
var testResultPublic = new List<TimelineInfo>();
{
- var client = await CreateClientAsUser();
-
- {
- var res = await client.PutAsync("timelines/@user1/members/user3", null);
- res.Should().HaveStatusCode(200);
- }
-
- {
- var res = await client.PutAsync("timelines/t1/members/user3", null);
- res.Should().HaveStatusCode(200);
- }
-
- {
- var res = await client.PatchAsJsonAsync("timelines/@user1", new TimelinePatchRequest { Visibility = TimelineVisibility.Public });
- res.Should().HaveStatusCode(200);
- }
+ using var client = await CreateClientAsUser();
- {
- var res = await client.PatchAsJsonAsync("timelines/t1", new TimelinePatchRequest { Visibility = TimelineVisibility.Register });
- res.Should().HaveStatusCode(200);
- }
+ await client.PutTimelineMemberAsync("@user1", "user3");
+ await client.PutTimelineMemberAsync("t1", "user3");
+ await client.PatchTimelineAsync("@user1", new() { Visibility = TimelineVisibility.Public });
+ await client.PatchTimelineAsync("t1", new() { Visibility = TimelineVisibility.Register });
{
- var res = await client.GetAsync("timelines/@user1");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("@user1");
testResultRelate.Add(timeline);
testResultJoin.Add(timeline);
testResultRelatePublic.Add(timeline);
@@ -234,9 +153,7 @@ namespace Timeline.Tests.IntegratedTests
}
{
- var res = await client.GetAsync("timelines/t1");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("t1");
testResultRelate.Add(timeline);
testResultJoin.Add(timeline);
testResultRelateRegister.Add(timeline);
@@ -244,41 +161,22 @@ namespace Timeline.Tests.IntegratedTests
}
{
- var client = await CreateClientAs(2);
-
- {
- var res = await client.PutAsync("timelines/@user2/members/user3", null);
- res.Should().HaveStatusCode(200);
- }
-
- {
- var res = await client.PutAsync("timelines/t2/members/user3", null);
- res.Should().HaveStatusCode(200);
- }
-
- {
- var res = await client.PatchAsJsonAsync("timelines/@user2", new TimelinePatchRequest { Visibility = TimelineVisibility.Register });
- res.Should().HaveStatusCode(200);
- }
+ using var client = await CreateClientAs(2);
- {
- var res = await client.PatchAsJsonAsync("timelines/t2", new TimelinePatchRequest { Visibility = TimelineVisibility.Private });
- res.Should().HaveStatusCode(200);
- }
+ await client.PutTimelineMemberAsync("@user2", "user3");
+ await client.PutTimelineMemberAsync("t2", "user3");
+ await client.PatchTimelineAsync("@user2", new() { Visibility = TimelineVisibility.Register });
+ await client.PatchTimelineAsync("t2", new() { Visibility = TimelineVisibility.Private });
{
- var res = await client.GetAsync("timelines/@user2");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("@user2");
testResultRelate.Add(timeline);
testResultJoin.Add(timeline);
testResultRelateRegister.Add(timeline);
}
{
- var res = await client.GetAsync("timelines/t2");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("t2");
testResultRelate.Add(timeline);
testResultJoin.Add(timeline);
testResultJoinPrivate.Add(timeline);
@@ -286,31 +184,19 @@ namespace Timeline.Tests.IntegratedTests
}
{
- var client = await CreateClientAs(3);
-
- {
- var res = await client.PatchAsJsonAsync("timelines/@user3", new TimelinePatchRequest { Visibility = TimelineVisibility.Private });
- res.Should().HaveStatusCode(200);
- }
-
- {
- var res = await client.PatchAsJsonAsync("timelines/t3", new TimelinePatchRequest { Visibility = TimelineVisibility.Register });
- res.Should().HaveStatusCode(200);
- }
+ using var client = await CreateClientAs(3);
+ await client.PatchTimelineAsync("@user3", new TimelinePatchRequest { Visibility = TimelineVisibility.Private });
+ await client.PatchTimelineAsync("t3", new TimelinePatchRequest { Visibility = TimelineVisibility.Register });
{
- var res = await client.GetAsync("timelines/@user3");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("@user3");
testResultRelate.Add(timeline);
testResultOwn.Add(timeline);
testResultOwnPrivate.Add(timeline);
}
{
- var res = await client.GetAsync("timelines/t3");
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var timeline = await client.GetTimelineAsync("t3");
testResultRelate.Add(timeline);
testResultOwn.Add(timeline);
testResultRelateRegister.Add(timeline);
@@ -318,86 +204,21 @@ namespace Timeline.Tests.IntegratedTests
}
{
- var client = await CreateClientAs(3);
- {
- var res = await client.GetAsync("timelines?relate=user3");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultRelate);
- }
-
- {
- var res = await client.GetAsync("timelines?relate=user3&relateType=own");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultOwn);
- }
-
- {
- var res = await client.GetAsync("timelines?relate=user3&visibility=public");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultRelatePublic);
- }
-
- {
- var res = await client.GetAsync("timelines?relate=user3&visibility=register");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultRelateRegister);
- }
+ using var client = await CreateDefaultClient();
+ async Task TestAgainst(string url, List<TimelineInfo> against)
{
- var res = await client.GetAsync("timelines?relate=user3&relateType=join&visibility=private");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultJoinPrivate);
+ var body = await client.TestGetAsync<List<TimelineInfo>>(url);
+ body.Should().BeEquivalentTo(against);
}
- {
- var res = await client.GetAsync("timelines?relate=user3&relateType=own&visibility=private");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultOwnPrivate);
- }
- }
-
- {
- var client = await CreateDefaultClient();
- {
- var res = await client.GetAsync("timelines?visibility=public");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelineInfo>>()
- .Which;
- body.Should().BeEquivalentTo(testResultPublic);
- }
- }
- }
-
- [Fact]
- public async Task TimelineList_InvalidModel()
- {
- var client = await CreateClientAsUser();
-
- {
- var res = await client.GetAsync("timelines?relate=us!!");
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.GetAsync("timelines?relateType=aaa");
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.GetAsync("timelines?visibility=aaa");
- res.Should().BeInvalidModel();
+ await TestAgainst("timelines?relate=user3", testResultRelate);
+ await TestAgainst("timelines?relate=user3&relateType=own", testResultOwn);
+ await TestAgainst("timelines?relate=user3&visibility=public", testResultRelatePublic);
+ await TestAgainst("timelines?relate=user3&visibility=register", testResultRelateRegister);
+ await TestAgainst("timelines?relate=user3&relateType=join&visibility=private", testResultJoinPrivate);
+ await TestAgainst("timelines?relate=user3&relateType=own&visibility=private", testResultOwnPrivate);
+ await TestAgainst("timelines?visibility=public", testResultPublic);
}
}
@@ -406,36 +227,20 @@ namespace Timeline.Tests.IntegratedTests
{
{
using var client = await CreateDefaultClient();
- var res = await client.PostAsJsonAsync("timelines", new TimelineCreateRequest { Name = "aaa" });
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
+ await client.TestPostAssertUnauthorizedAsync("timelines", new TimelineCreateRequest { Name = "aaa" });
}
- using (var client = await CreateClientAsUser())
{
- {
- var res = await client.PostAsJsonAsync("timelines", new TimelineCreateRequest { Name = "!!!" });
- res.Should().BeInvalidModel();
- }
+ using var client = await CreateClientAsUser();
- TimelineInfo timelineInfo;
- {
- var res = await client.PostAsJsonAsync("timelines", new TimelineCreateRequest { Name = "aaa" });
- timelineInfo = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
- }
+ await client.TestPostAssertInvalidModelAsync("timelines", new TimelineCreateRequest { Name = "!!!" });
{
- var res = await client.GetAsync("timelines/aaa");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Should().BeEquivalentTo(timelineInfo);
+ var body = await client.TestPostAsync<TimelineInfo>("timelines", new TimelineCreateRequest { Name = "aaa" });
+ body.Should().BeEquivalentTo(await client.GetTimelineAsync("aaa"));
}
- {
- var res = await client.PostAsJsonAsync("timelines", new TimelineCreateRequest { Name = "aaa" });
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.TimelineController.NameConflict);
- }
+ await client.TestPostAssertErrorAsync("timelines", new TimelineCreateRequest { Name = "aaa" }, errorCode: ErrorCodes.TimelineController.NameConflict);
}
}
@@ -444,569 +249,326 @@ namespace Timeline.Tests.IntegratedTests
{
{
using var client = await CreateDefaultClient();
- var res = await client.DeleteAsync("timelines/t1");
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
+ await client.TestDeleteAssertUnauthorizedAsync("timelines/t1");
}
{
using var client = await CreateClientAs(2);
- var res = await client.DeleteAsync("timelines/t1");
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
+ await client.TestDeleteAssertForbiddenAsync("timelines/t1");
}
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.DeleteAsync("timelines/!!!");
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.DeleteAsync("timelines/t2");
- res.Should().BeDelete(true);
- }
-
- {
- var res = await client.DeleteAsync("timelines/t2");
- res.Should().BeDelete(false);
- }
+ await client.TestDeleteAssertInvalidModelAsync("timelines/!!!");
+ await client.TestDeleteAsync("timelines/t2", true);
+ await client.TestDeleteAsync("timelines/t2", false);
}
{
using var client = await CreateClientAs(1);
- {
- var res = await client.DeleteAsync("timelines/!!!");
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.DeleteAsync("timelines/t1");
- res.Should().BeDelete(true);
- }
-
- {
- var res = await client.DeleteAsync("timelines/t1");
- res.Should().HaveStatusCode(400);
- }
+ await client.TestDeleteAssertInvalidModelAsync("timelines/!!!");
+ await client.TestDeleteAsync("timelines/t1", true);
+ await client.TestDeleteAssertErrorAsync("timelines/t1");
}
}
- [Theory]
- [MemberData(nameof(TimelineUrlByNameGeneratorData))]
- public async Task InvalidModel_BadName(Func<string, string, string> generator)
- {
- using var client = await CreateClientAsAdministrator();
- {
- var res = await client.GetAsync(generator("aaa!!!", null));
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.PatchAsJsonAsync(generator("aaa!!!", null), new TimelinePatchRequest { });
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.PutAsync(generator("aaa!!!", "members/user1"), null);
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.DeleteAsync(generator("aaa!!!", "members/user1"));
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.GetAsync(generator("aaa!!!", "posts"));
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.PostAsJsonAsync(generator("aaa!!!", "posts"), TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.DeleteAsync(generator("aaa!!!", "posts/123"));
- res.Should().BeInvalidModel();
- }
- {
- var res = await client.GetAsync(generator("aaa!!!", "posts/123/data"));
- res.Should().BeInvalidModel();
- }
- }
+ public static string CreatePersonalTimelineName(int i) => i == 0 ? "@admin" : $"@user{i}";
+ public static string CreateOrdinaryTimelineName(int i) => $"t{i}";
+ public delegate string TimelineNameGenerator(int i);
- [Theory]
- [MemberData(nameof(TimelineUrlByNameGeneratorData))]
- public async Task Ordinary_NotFound(Func<string, string, string> generator)
+ public static IEnumerable<object[]> TimelineNameGeneratorTestData()
{
- var errorCode = generator == GenerateOrdinaryTimelineUrlByName ? ErrorCodes.TimelineController.NotExist : ErrorCodes.UserCommon.NotExist;
-
- using var client = await CreateClientAsAdministrator();
- {
- var res = await client.GetAsync(generator("notexist", null));
- res.Should().HaveStatusCode(404).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.PatchAsJsonAsync(generator("notexist", null), new TimelinePatchRequest { });
- res.Should().HaveStatusCode(400).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.PutAsync(generator("notexist", "members/user1"), null);
- res.Should().HaveStatusCode(400).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.DeleteAsync(generator("notexist", "members/user1"));
- res.Should().HaveStatusCode(400).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.GetAsync(generator("notexist", "posts"));
- res.Should().HaveStatusCode(404).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.PostAsJsonAsync(generator("notexist", "posts"), TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(400).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.DeleteAsync(generator("notexist", "posts/123"));
- res.Should().HaveStatusCode(400).And.HaveCommonBody(errorCode);
- }
- {
- var res = await client.GetAsync(generator("notexist", "posts/123/data"));
- res.Should().HaveStatusCode(404).And.HaveCommonBody(errorCode);
- }
+ yield return new object[] { new TimelineNameGenerator(CreatePersonalTimelineName) };
+ yield return new object[] { new TimelineNameGenerator(CreateOrdinaryTimelineName) };
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Description_Should_Work(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task TimelineDescription_Should_Work(TimelineNameGenerator generator)
{
+ // TODO! Permission tests.
+
using var client = await CreateClientAsUser();
+ var timelineName = generator(1);
- async Task AssertDescription(string description)
{
- var res = await client.GetAsync(generator(1, null));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Description.Should().Be(description);
+ var timeline = await client.GetTimelineAsync(timelineName);
+ timeline.Description.Should().BeEmpty();
}
const string mockDescription = "haha";
- await AssertDescription("");
- {
- var res = await client.PatchAsJsonAsync(generator(1, null),
- new TimelinePatchRequest { Description = mockDescription });
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which.Description.Should().Be(mockDescription);
- await AssertDescription(mockDescription);
- }
- {
- var res = await client.PatchAsJsonAsync(generator(1, null),
- new TimelinePatchRequest { Description = null });
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which.Description.Should().Be(mockDescription);
- await AssertDescription(mockDescription);
- }
{
- var res = await client.PatchAsJsonAsync(generator(1, null),
- new TimelinePatchRequest { Description = "" });
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which.Description.Should().Be("");
- await AssertDescription("");
+ var timeline = await client.PatchTimelineAsync(timelineName, new() { Description = mockDescription });
+ timeline.Description.Should().Be(mockDescription);
}
- }
-
- [Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Member_Should_Work(TimelineUrlGenerator generator)
- {
- var getUrl = generator(1, null);
- using var client = await CreateClientAsUser();
- async Task AssertMembers(IList<UserInfo> members)
{
- var res = await client.GetAsync(getUrl);
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Members.Should().NotBeNull().And.BeEquivalentTo(members);
+ var timeline = await client.GetTimelineAsync(timelineName);
+ timeline.Description.Should().Be(mockDescription);
}
- async Task AssertEmptyMembers()
{
- var res = await client.GetAsync(getUrl);
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Members.Should().NotBeNull().And.BeEmpty();
+ var timeline = await client.PatchTimelineAsync(timelineName, new() { Description = null });
+ timeline.Description.Should().Be(mockDescription);
}
- await AssertEmptyMembers();
- {
- var res = await client.PutAsync(generator(1, "members/usernotexist"), null);
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.TimelineController.MemberPut_NotExist);
- }
- await AssertEmptyMembers();
{
- var res = await client.PutAsync(generator(1, "members/user2"), null);
- res.Should().HaveStatusCode(200);
+ var timeline = await client.GetTimelineAsync(timelineName);
+ timeline.Description.Should().Be(mockDescription);
}
- await AssertMembers(new List<UserInfo> { UserInfos[2] });
+
{
- var res = await client.DeleteAsync(generator(1, "members/user2"));
- res.Should().BeDelete(true);
+ var timeline = await client.PatchTimelineAsync(timelineName, new() { Description = "" });
+ timeline.Description.Should().BeEmpty();
}
- await AssertEmptyMembers();
+
{
- var res = await client.DeleteAsync(generator(1, "members/aaa"));
- res.Should().BeDelete(false);
+ var timeline = await client.GetTimelineAsync(timelineName);
+ timeline.Description.Should().BeEmpty();
}
- await AssertEmptyMembers();
- }
-
- public static IEnumerable<object[]> Permission_Timeline_Data()
- {
- yield return new object[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl), -1, 200, 401, 401, 401, 401 };
- yield return new object[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl), 1, 200, 200, 403, 200, 403 };
- yield return new object[] { new TimelineUrlGenerator(GenerateOrdinaryTimelineUrl), 0, 200, 200, 200, 200, 200 };
- yield return new object[] { new TimelineUrlGenerator(GeneratePersonalTimelineUrl), -1, 200, 401, 401, 401, 401 };
- yield return new object[] { new TimelineUrlGenerator(GeneratePersonalTimelineUrl), 1, 200, 200, 403, 200, 403 };
- yield return new object[] { new TimelineUrlGenerator(GeneratePersonalTimelineUrl), 0, 200, 200, 200, 200, 200 };
}
[Theory]
- [MemberData(nameof(Permission_Timeline_Data))]
- public async Task Permission_Timeline(TimelineUrlGenerator generator, int userNumber, int get, int opPatchUser, int opPatchAdmin, int opMemberUser, int opMemberAdmin)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Member_Should_Work(TimelineNameGenerator generator)
{
- using var client = await CreateClientAs(userNumber);
- {
- var res = await client.GetAsync("timelines/t1");
- res.Should().HaveStatusCode(get);
- }
-
- {
- var res = await client.PatchAsJsonAsync(generator(1, null), new TimelinePatchRequest { Description = "hahaha" });
- res.Should().HaveStatusCode(opPatchUser);
- }
+ // TODO! Invalid model tests.
+ // TODO! Permission tests.
- {
- var res = await client.PatchAsJsonAsync(generator(0, null), new TimelinePatchRequest { Description = "hahaha" });
- res.Should().HaveStatusCode(opPatchAdmin);
- }
+ using var client = await CreateClientAsUser();
- {
- var res = await client.PutAsync(generator(1, "members/user2"), null);
- res.Should().HaveStatusCode(opMemberUser);
- }
+ var timelineName = generator(1);
+ async Task AssertMembers(List<UserInfo> members)
{
- var res = await client.DeleteAsync(generator(1, "members/user2"));
- res.Should().HaveStatusCode(opMemberUser);
+ var body = await client.GetTimelineAsync(timelineName);
+ body.Members.Should().NotBeNull().And.BeEquivalentTo(members);
}
+ async Task AssertEmptyMembers()
{
- var res = await client.PutAsync(generator(0, "members/user2"), null);
- res.Should().HaveStatusCode(opMemberAdmin);
+ var body = await client.GetTimelineAsync(timelineName);
+ body.Members.Should().NotBeNull().And.BeEmpty();
}
- {
- var res = await client.DeleteAsync(generator(0, "members/user2"));
- res.Should().HaveStatusCode(opMemberAdmin);
- }
+ await AssertEmptyMembers();
+ await client.TestPutAssertErrorAsync($"timelines/{timelineName}/members/usernotexist", errorCode: ErrorCodes.TimelineController.MemberPut_NotExist);
+ await AssertEmptyMembers();
+ await client.PutTimelineMemberAsync(timelineName, "user2");
+ await AssertMembers(new List<UserInfo> { await client.GetUserAsync("user2") });
+ await client.DeleteTimelineMemberAsync(timelineName, "user2", true);
+ await AssertEmptyMembers();
+ await client.DeleteTimelineMemberAsync(timelineName, "aaa", false);
+ await AssertEmptyMembers();
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Visibility_Test(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task GetPostsAndVisibility_Should_Work(TimelineNameGenerator generator)
{
- var userUrl = generator(1, "posts");
- var adminUrl = generator(0, "posts");
- {
-
- using var client = await CreateClientAsUser();
- using var content = new StringContent(@"{""visibility"":""abcdefg""}", System.Text.Encoding.UTF8, System.Net.Mime.MediaTypeNames.Application.Json);
- var res = await client.PatchAsync(generator(1, null), content);
- res.Should().BeInvalidModel();
- }
{ // default visibility is registered
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync(userUrl);
- res.Should().HaveStatusCode(403);
+ await client.TestGetAssertForbiddenAsync($"timelines/{generator(1)}/posts");
}
{
using var client = await CreateClientAsUser();
- var res = await client.GetAsync(adminUrl);
- res.Should().HaveStatusCode(200);
+ await client.TestGetAsync($"timelines/{generator(0)}/posts");
}
}
{ // change visibility to public
{
using var client = await CreateClientAsUser();
- var res = await client.PatchAsJsonAsync(generator(1, null),
- new TimelinePatchRequest { Visibility = TimelineVisibility.Public });
- res.Should().HaveStatusCode(200);
+ await client.PatchTimelineAsync(generator(1), new() { Visibility = TimelineVisibility.Public });
}
+
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync(userUrl);
- res.Should().HaveStatusCode(200);
+ await client.TestGetAsync($"timelines/{generator(1)}/posts");
}
}
{ // change visibility to private
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PatchAsJsonAsync(generator(1, null),
- new TimelinePatchRequest { Visibility = TimelineVisibility.Private });
- res.Should().HaveStatusCode(200);
- }
- {
- var res = await client.PatchAsJsonAsync(generator(0, null),
- new TimelinePatchRequest { Visibility = TimelineVisibility.Private });
- res.Should().HaveStatusCode(200);
- }
+ await client.PatchTimelineAsync(generator(1), new() { Visibility = TimelineVisibility.Private });
+ await client.PatchTimelineAsync(generator(0), new() { Visibility = TimelineVisibility.Private });
}
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync(userUrl);
- res.Should().HaveStatusCode(403);
+ await client.TestGetAssertForbiddenAsync($"timelines/{generator(1)}/posts");
}
{ // user can't read admin's
using var client = await CreateClientAsUser();
- var res = await client.GetAsync(adminUrl);
- res.Should().HaveStatusCode(403);
+ await client.TestGetAssertForbiddenAsync($"timelines/{generator(0)}/posts");
}
{ // admin can read user's
using var client = await CreateClientAsAdministrator();
- var res = await client.GetAsync(userUrl);
- res.Should().HaveStatusCode(200);
+ await client.TestGetAsync($"timelines/{generator(1)}/posts");
}
{ // add member
using var client = await CreateClientAsAdministrator();
- var res = await client.PutAsync(generator(0, "members/user1"), null);
- res.Should().HaveStatusCode(200);
+ await client.PutTimelineMemberAsync(generator(0), "user1");
}
{ // now user can read admin's
using var client = await CreateClientAsUser();
- var res = await client.GetAsync(adminUrl);
- res.Should().HaveStatusCode(200);
+ await client.TestGetAsync($"timelines/{generator(0)}/posts");
}
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Permission_Post_Create(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task CreatePostPermission_Should_Work(TimelineNameGenerator generator)
{
using (var client = await CreateClientAsUser())
{
- var res = await client.PutAsync(generator(1, "members/user2"), null);
- res.Should().HaveStatusCode(200);
+ await client.PutTimelineMemberAsync(generator(1), "user2");
}
using (var client = await CreateDefaultClient())
- {
- { // no auth should get 401
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(401);
- }
+ { // no auth should get 401
+ await client.TestPostAssertUnauthorizedAsync($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
}
using (var client = await CreateClientAsUser())
{
- { // post self's
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(200);
- }
- { // post other not as a member should get 403
- var res = await client.PostAsJsonAsync(generator(0, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(403);
- }
+ // post self's
+ await client.TestPostAsync($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
+ // post other not as a member should get 403
+ await client.TestPostAssertForbiddenAsync($"timelines/{generator(0)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
}
using (var client = await CreateClientAsAdministrator())
- {
- { // post as admin
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(200);
- }
+ { // post as admin
+ await client.TestPostAsync($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
}
using (var client = await CreateClientAs(2))
- {
- { // post as member
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- res.Should().HaveStatusCode(200);
- }
+ { // post as member
+ await client.TestPostAsync($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Permission_Post_Delete(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task DeletePostPermission_Should_Work(TimelineNameGenerator generator)
{
async Task<long> CreatePost(int userNumber)
{
using var client = await CreateClientAs(userNumber);
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- return res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>()
- .Which.Id;
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
+ return body.Id;
}
using (var client = await CreateClientAsUser())
{
- {
- var res = await client.PutAsync(generator(1, "members/user2"), null);
- res.Should().HaveStatusCode(200);
- }
- {
- var res = await client.PutAsync(generator(1, "members/user3"), null);
- res.Should().HaveStatusCode(200);
- }
+ await client.PutTimelineMemberAsync(generator(1), "user2");
+ await client.PutTimelineMemberAsync(generator(1), "user3");
}
{ // no auth should get 401
using var client = await CreateDefaultClient();
- var res = await client.DeleteAsync(generator(1, "posts/12"));
- res.Should().HaveStatusCode(401);
+ await client.TestDeleteAssertUnauthorizedAsync($"timelines/{generator(1)}/posts/12");
}
{ // self can delete self
var postId = await CreatePost(1);
using var client = await CreateClientAsUser();
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().HaveStatusCode(200);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}");
}
{ // admin can delete any
var postId = await CreatePost(1);
using var client = await CreateClientAsAdministrator();
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().HaveStatusCode(200);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}");
}
{ // owner can delete other
var postId = await CreatePost(2);
using var client = await CreateClientAsUser();
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().HaveStatusCode(200);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}");
}
{ // author can delete self
var postId = await CreatePost(2);
using var client = await CreateClientAs(2);
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().HaveStatusCode(200);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}");
}
{ // otherwise is forbidden
var postId = await CreatePost(2);
using var client = await CreateClientAs(3);
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().HaveStatusCode(403);
+ await client.TestDeleteAssertForbiddenAsync($"timelines/{generator(1)}/posts/{postId}");
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task TextPost_ShouldWork(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task TextPost_Should_Work(TimelineNameGenerator generator)
{
+ using var client = await CreateClientAsUser();
+
{
- using var client = await CreateClientAsUser();
- {
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Should().NotBeNull().And.BeEmpty();
- }
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest(null));
- res.Should().BeInvalidModel();
- }
- const string mockContent = "aaa";
- TimelinePostInfo createRes;
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest(mockContent));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>()
- .Which;
- body.Should().NotBeNull();
- body.Content.Should().BeEquivalentTo(TimelineHelper.TextPostContent(mockContent));
- body.Author.Should().BeEquivalentTo(UserInfos[1]);
- body.Deleted.Should().BeFalse();
- createRes = body;
- }
- {
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Should().NotBeNull().And.BeEquivalentTo(createRes);
- }
- const string mockContent2 = "bbb";
- var mockTime2 = DateTime.UtcNow.AddDays(-1);
- TimelinePostInfo createRes2;
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest(mockContent2, mockTime2));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>()
- .Which;
- body.Should().NotBeNull();
- body.Content.Should().BeEquivalentTo(TimelineHelper.TextPostContent(mockContent2));
- body.Author.Should().BeEquivalentTo(UserInfos[1]);
- body.Time.Should().BeCloseTo(mockTime2, 1000);
- body.Deleted.Should().BeFalse();
- createRes2 = body;
- }
- {
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Should().NotBeNull().And.BeEquivalentTo(createRes, createRes2);
- }
- {
- var res = await client.DeleteAsync(generator(1, $"posts/{createRes.Id}"));
- res.Should().BeDelete(true);
- }
- {
- var res = await client.DeleteAsync(generator(1, $"posts/{createRes.Id}"));
- res.Should().BeDelete(false);
- }
- {
- var res = await client.DeleteAsync(generator(1, "posts/30000"));
- res.Should().BeDelete(false);
- }
- {
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Should().NotBeNull().And.BeEquivalentTo(createRes2);
- }
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Should().BeEmpty();
+ }
+
+ const string mockContent = "aaa";
+ TimelinePostInfo createRes;
+ {
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest(mockContent));
+ body.Content.Should().BeEquivalentTo(TimelineHelper.TextPostContent(mockContent));
+ body.Author.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
+ body.Deleted.Should().BeFalse();
+ createRes = body;
+ }
+ {
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Should().BeEquivalentTo(createRes);
+ }
+ const string mockContent2 = "bbb";
+ var mockTime2 = DateTime.UtcNow.AddDays(-1);
+ TimelinePostInfo createRes2;
+ {
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest(mockContent2, mockTime2));
+ body.Should().NotBeNull();
+ body.Content.Should().BeEquivalentTo(TimelineHelper.TextPostContent(mockContent2));
+ body.Author.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
+ body.Time.Should().BeCloseTo(mockTime2, 1000);
+ body.Deleted.Should().BeFalse();
+ createRes2 = body;
+ }
+ {
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Should().BeEquivalentTo(createRes, createRes2);
+ }
+ {
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{createRes.Id}", true);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{createRes.Id}", false);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/30000", false);
+ }
+ {
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Should().BeEquivalentTo(createRes2);
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task GetPost_Should_Ordered(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task GetPost_Should_Ordered(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
async Task<long> CreatePost(DateTime time)
{
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa", time));
- return res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>()
- .Which.Id;
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa", time));
+ return body.Id;
}
var now = DateTime.UtcNow;
@@ -1015,60 +577,31 @@ namespace Timeline.Tests.IntegratedTests
var id2 = await CreatePost(now);
{
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Select(p => p.Id).Should().Equal(id1, id2, id0);
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Select(p => p.Id).Should().Equal(id1, id2, id0);
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task CreatePost_InvalidModel(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task CreatePost_InvalidModel(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
-
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = null });
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = null } });
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "hahaha" } });
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "text", Text = null } });
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = null } });
- res.Should().BeInvalidModel();
- }
-
- {
- // image not base64
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = "!!!" } });
- res.Should().BeInvalidModel();
- }
-
- {
- // image base64 not image
- var res = await client.PostAsJsonAsync(generator(1, "posts"), new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = Convert.ToBase64String(new byte[] { 0x01, 0x02, 0x03 }) } });
- res.Should().BeInvalidModel();
- }
+ var postUrl = $"timelines/{generator(1)}/posts";
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = null! });
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = null! } });
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "hahaha" } });
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "text", Text = null } });
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = null } });
+ // image not base64
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = "!!!" } });
+ // image base64 not image
+ await client.TestPostAssertInvalidModelAsync(postUrl, new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Type = "image", Data = Convert.ToBase64String(new byte[] { 0x01, 0x02, 0x03 }) } });
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task ImagePost_ShouldWork(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task ImagePost_ShouldWork(TimelineNameGenerator generator)
{
var imageData = ImageHelper.CreatePngWithSize(100, 200);
@@ -1078,14 +611,14 @@ namespace Timeline.Tests.IntegratedTests
void AssertPostContent(TimelinePostContentInfo content)
{
content.Type.Should().Be(TimelinePostContentTypes.Image);
- content.Url.Should().EndWith(generator(1, $"posts/{postId}/data"));
+ content.Url.Should().EndWith($"timelines/{generator(1)}/posts/{postId}/data");
content.Text.Should().Be(null);
}
using var client = await CreateClientAsUser();
{
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts",
new TimelinePostCreateRequest
{
Content = new TimelinePostCreateRequestContent
@@ -1094,26 +627,22 @@ namespace Timeline.Tests.IntegratedTests
Data = Convert.ToBase64String(imageData)
}
});
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>().Which;
postId = body.Id;
- postImageUrl = body.Content.Url;
+ postImageUrl = body.Content!.Url!;
AssertPostContent(body.Content);
}
{
- var res = await client.GetAsync(generator(1, "posts"));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>().Which;
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
body.Should().HaveCount(1);
var post = body[0];
post.Id.Should().Be(postId);
- AssertPostContent(post.Content);
+ AssertPostContent(post.Content!);
}
{
- var res = await client.GetAsync(generator(1, $"posts/{postId}/data"));
- res.Content.Headers.ContentType.MediaType.Should().Be("image/png");
+ var res = await client.GetAsync($"timelines/{generator(1)}/posts/{postId}/data");
+ res.Content.Headers.ContentType!.MediaType.Should().Be("image/png");
var data = await res.Content.ReadAsByteArrayAsync();
var image = Image.Load(data, out var format);
image.Width.Should().Be(100);
@@ -1121,25 +650,13 @@ namespace Timeline.Tests.IntegratedTests
format.Name.Should().Be(PngFormat.Instance.Name);
}
- {
- await CacheTestHelper.TestCache(client, generator(1, $"posts/{postId}/data"));
- }
-
- {
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().BeDelete(true);
- }
-
- {
- var res = await client.DeleteAsync(generator(1, $"posts/{postId}"));
- res.Should().BeDelete(false);
- }
+ await CacheTestHelper.TestCache(client, $"timelines/{generator(1)}/posts/{postId}/data");
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}", true);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{postId}", false);
{
- var res = await client.GetAsync(generator(1, "posts"));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo[]>()
- .Which.Should().BeEmpty();
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts");
+ body.Should().BeEmpty();
}
{
@@ -1151,83 +668,60 @@ namespace Timeline.Tests.IntegratedTests
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task ImagePost_400(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task ImagePost_400(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
- {
- var res = await client.GetAsync(generator(1, "posts/11234/data"));
- res.Should().HaveStatusCode(404)
- .And.HaveCommonBody(ErrorCodes.TimelineController.PostNotExist);
- }
+ await client.TestGetAssertNotFoundAsync($"timelines/{generator(1)}/posts/11234/data", errorCode: ErrorCodes.TimelineController.PostNotExist);
long postId;
{
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
- TimelineHelper.TextPostCreateRequest("aaa"));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>()
- .Which;
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", TimelineHelper.TextPostCreateRequest("aaa"));
postId = body.Id;
}
- {
- var res = await client.GetAsync(generator(1, $"posts/{postId}/data"));
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.TimelineController.PostNoData);
- }
+ await client.TestGetAssertErrorAsync($"timelines/{generator(1)}/posts/{postId}/data", errorCode: ErrorCodes.TimelineController.PostNoData);
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Timeline_LastModified(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Timeline_LastModified(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
DateTime lastModified;
{
- var res = await client.GetAsync(generator(1));
- lastModified = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.LastModified;
+ var body = await client.GetTimelineAsync(generator(1));
+ lastModified = body.LastModified;
}
await Task.Delay(1000);
{
- var res = await client.PatchAsJsonAsync(generator(1), new TimelinePatchRequest { Description = "123" });
- lastModified = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.LastModified.Should().BeAfter(lastModified).And.Subject.Value;
+ var body = await client.PatchTimelineAsync(generator(1), new() { Description = "123" });
+ lastModified = body.LastModified.Should().BeAfter(lastModified).And.Subject!.Value;
}
{
- var res = await client.GetAsync(generator(1));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.LastModified.Should().Be(lastModified);
+ var body = await client.GetTimelineAsync(generator(1));
+ body.LastModified.Should().Be(lastModified);
}
await Task.Delay(1000);
- {
- var res = await client.PutAsync(generator(1, "members/user2"), null);
- res.Should().HaveStatusCode(200);
- }
+ await client.PutTimelineMemberAsync(generator(1), "user2");
{
- var res = await client.GetAsync(generator(1));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.LastModified.Should().BeAfter(lastModified);
+ var body = await client.GetTimelineAsync(generator(1));
+ body.LastModified.Should().BeAfter(lastModified);
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Post_ModifiedSince(TimelineUrlGenerator generator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Post_ModifiedSince(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
@@ -1236,32 +730,24 @@ namespace Timeline.Tests.IntegratedTests
foreach (var content in postContentList)
{
- var res = await client.PostAsJsonAsync(generator(1, "posts"),
+ var post = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts",
new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Text = content, Type = TimelinePostContentTypes.Text } });
- var post = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>().Which;
posts.Add(post);
await Task.Delay(1000);
}
- {
- var res = await client.DeleteAsync(generator(1, $"posts/{posts[2].Id}"));
- res.Should().BeDelete(true);
- }
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{posts[2].Id}", true);
{
- var res = await client.GetAsync(generator(1, "posts",
- new Dictionary<string, string> { { "modifiedSince", posts[1].LastUpdated.ToString("s", CultureInfo.InvariantCulture) } }));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelinePostInfo>>()
- .Which.Should().HaveCount(2)
- .And.Subject.Select(p => p.Content.Text).Should().Equal("b", "d");
+ var body = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts?modifiedSince={posts[1].LastUpdated.ToString("s", CultureInfo.InvariantCulture) }");
+ body.Should().HaveCount(2)
+ .And.Subject.Select(p => p.Content!.Text).Should().Equal("b", "d");
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task PostList_IncludeDeleted(TimelineUrlGenerator urlGenerator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task PostList_IncludeDeleted(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
@@ -1270,23 +756,18 @@ namespace Timeline.Tests.IntegratedTests
foreach (var content in postContentList)
{
- var res = await client.PostAsJsonAsync(urlGenerator(1, "posts"),
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts",
new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Text = content, Type = TimelinePostContentTypes.Text } });
- posts.Add(res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>().Which);
+ posts.Add(body);
}
foreach (var id in new long[] { posts[0].Id, posts[2].Id })
{
- var res = await client.DeleteAsync(urlGenerator(1, $"posts/{id}"));
- res.Should().BeDelete(true);
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{id}", true);
}
{
- var res = await client.GetAsync(urlGenerator(1, "posts", new Dictionary<string, string> { ["includeDeleted"] = "true" }));
- posts = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelinePostInfo>>()
- .Which;
+ posts = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts?includeDeleted=true");
posts.Should().HaveCount(4);
posts.Select(p => p.Deleted).Should().Equal(true, false, true, false);
posts.Select(p => p.Content == null).Should().Equal(true, false, true, false);
@@ -1294,8 +775,8 @@ namespace Timeline.Tests.IntegratedTests
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Post_ModifiedSince_And_IncludeDeleted(TimelineUrlGenerator urlGenerator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Post_ModifiedSince_And_IncludeDeleted(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
@@ -1304,29 +785,17 @@ namespace Timeline.Tests.IntegratedTests
foreach (var (content, index) in postContentList.Select((v, i) => (v, i)))
{
- var res = await client.PostAsJsonAsync(urlGenerator(1, "posts"),
+ var post = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts",
new TimelinePostCreateRequest { Content = new TimelinePostCreateRequestContent { Text = content, Type = TimelinePostContentTypes.Text } });
- var post = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelinePostInfo>().Which;
posts.Add(post);
await Task.Delay(1000);
}
- {
- var res = await client.DeleteAsync(urlGenerator(1, $"posts/{posts[2].Id}"));
- res.Should().BeDelete(true);
- }
+ await client.TestDeleteAsync($"timelines/{generator(1)}/posts/{posts[2].Id}", true);
{
- var res = await client.GetAsync(urlGenerator(1, "posts",
- new Dictionary<string, string> {
- { "modifiedSince", posts[1].LastUpdated.ToString("s", CultureInfo.InvariantCulture) },
- { "includeDeleted", "true" }
- }));
- posts = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<List<TimelinePostInfo>>()
- .Which;
+ posts = await client.TestGetAsync<List<TimelinePostInfo>>($"timelines/{generator(1)}/posts?modifiedSince={posts[1].LastUpdated.ToString("s", CultureInfo.InvariantCulture)}&includeDeleted=true");
posts.Should().HaveCount(3);
posts.Select(p => p.Deleted).Should().Equal(false, true, false);
posts.Select(p => p.Content == null).Should().Equal(false, true, false);
@@ -1334,8 +803,8 @@ namespace Timeline.Tests.IntegratedTests
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Timeline_Get_IfModifiedSince_And_CheckUniqueId(TimelineUrlGenerator urlGenerator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Timeline_Get_IfModifiedSince_And_CheckUniqueId(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
@@ -1344,96 +813,70 @@ namespace Timeline.Tests.IntegratedTests
string uniqueId;
{
- var res = await client.GetAsync(urlGenerator(1));
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>().Which;
+ var body = await client.GetTimelineAsync(generator(1));
timeline = body;
lastModifiedTime = body.LastModified;
uniqueId = body.UniqueId;
}
{
- using var req = new HttpRequestMessage
- {
- RequestUri = new Uri(client.BaseAddress, urlGenerator(1)),
- Method = HttpMethod.Get,
- };
- req.Headers.IfModifiedSince = lastModifiedTime.AddSeconds(1);
- var res = await client.SendAsync(req);
- res.Should().HaveStatusCode(304);
+ await client.TestGetAsync($"timelines/{generator(1)}",
+ expectedStatusCode: HttpStatusCode.NotModified,
+ headerSetup: (headers, _) =>
+ {
+ headers.IfModifiedSince = lastModifiedTime.AddSeconds(1);
+ });
}
{
- using var req = new HttpRequestMessage
- {
- RequestUri = new Uri(client.BaseAddress, urlGenerator(1)),
- Method = HttpMethod.Get,
- };
- req.Headers.IfModifiedSince = lastModifiedTime.AddSeconds(-1);
- var res = await client.SendAsync(req);
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Should().BeEquivalentTo(timeline);
+
+ var body = await client.TestGetAsync<TimelineInfo>($"timelines/{generator(1)}",
+ headerSetup: (headers, _) =>
+ {
+ headers.IfModifiedSince = lastModifiedTime.AddSeconds(-1);
+ });
+ body.Should().BeEquivalentTo(timeline);
}
{
- var res = await client.GetAsync(urlGenerator(1, null,
- new Dictionary<string, string> { { "ifModifiedSince", lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) } }));
- res.Should().HaveStatusCode(304);
+ await client.TestGetAsync($"timelines/{generator(1)}?ifModifiedSince={lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) }", expectedStatusCode: HttpStatusCode.NotModified);
}
{
- var res = await client.GetAsync(urlGenerator(1, null,
- new Dictionary<string, string> { { "ifModifiedSince", lastModifiedTime.AddSeconds(-1).ToString("s", CultureInfo.InvariantCulture) } }));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Should().BeEquivalentTo(timeline);
+ var body = await client.TestGetAsync<TimelineInfo>($"timelines/{generator(1)}?ifModifiedSince={lastModifiedTime.AddSeconds(-1).ToString("s", CultureInfo.InvariantCulture) }");
+ body.Should().BeEquivalentTo(timeline);
}
{
- var res = await client.GetAsync(urlGenerator(1, null,
- new Dictionary<string, string> { { "ifModifiedSince", lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) },
- {"checkUniqueId", uniqueId } }));
- res.Should().HaveStatusCode(304);
+ await client.TestGetAsync($"timelines/{generator(1)}?ifModifiedSince={lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) }&checkUniqueId={uniqueId}", expectedStatusCode: HttpStatusCode.NotModified);
}
{
var testUniqueId = (uniqueId[0] == 'a' ? "b" : "a") + uniqueId[1..];
- var res = await client.GetAsync(urlGenerator(1, null,
- new Dictionary<string, string> { { "ifModifiedSince", lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) },
- {"checkUniqueId", testUniqueId } }));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Should().BeEquivalentTo(timeline);
+ var body = await client.TestGetAsync<TimelineInfo>($"timelines/{generator(1)}?ifModifiedSince={lastModifiedTime.AddSeconds(1).ToString("s", CultureInfo.InvariantCulture) }&checkUniqueId={testUniqueId}");
+ body.Should().BeEquivalentTo(timeline);
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task Title(TimelineUrlGenerator urlGenerator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task Title(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
{
- var res = await client.GetAsync(urlGenerator(1));
- var timeline = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which;
- timeline.Title.Should().Be(timeline.Name);
+ var body = await client.GetTimelineAsync(generator(1));
+ body.Title.Should().Be(body.Name);
}
{
- var res = await client.PatchAsJsonAsync(urlGenerator(1), new TimelinePatchRequest { Title = "atitle" });
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Title.Should().Be("atitle");
+ var body = await client.PatchTimelineAsync(generator(1), new TimelinePatchRequest { Title = "atitle" });
+ body.Title.Should().Be("atitle");
}
{
- var res = await client.GetAsync(urlGenerator(1));
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<TimelineInfo>()
- .Which.Title.Should().Be("atitle");
+ var body = await client.GetTimelineAsync(generator(1));
+ body.Title.Should().Be("atitle");
}
}
@@ -1442,53 +885,34 @@ namespace Timeline.Tests.IntegratedTests
{
{
using var client = await CreateDefaultClient();
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "tttttttt" });
- res.Should().HaveStatusCode(401);
+ await client.TestPostAssertUnauthorizedAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "tttttttt" });
}
{
using var client = await CreateClientAs(2);
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "tttttttt" });
- res.Should().HaveStatusCode(403);
+ await client.TestPostAssertForbiddenAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "tttttttt" });
}
using (var client = await CreateClientAsUser())
{
- {
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "!!!", NewName = "tttttttt" });
- res.Should().BeInvalidModel();
- }
+ await client.TestPostAssertInvalidModelAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "!!!", NewName = "tttttttt" });
+ await client.TestPostAssertInvalidModelAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "ttt", NewName = "!!!!" });
+ await client.TestPostAssertErrorAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "ttttt", NewName = "tttttttt" }, errorCode: ErrorCodes.TimelineController.NotExist);
- {
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "ttt", NewName = "!!!!" });
- res.Should().BeInvalidModel();
- }
-
- {
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "ttttt", NewName = "tttttttt" });
- res.Should().HaveStatusCode(400).And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.TimelineController.NotExist);
- }
+ await client.TestPostAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "newt" });
- {
- var res = await client.PostAsJsonAsync("timelineop/changename", new TimelineChangeNameRequest { OldName = "t1", NewName = "newt" });
- res.Should().HaveStatusCode(200).And.HaveJsonBody<TimelineInfo>().Which.Name.Should().Be("newt");
- }
-
- {
- var res = await client.GetAsync("timelines/t1");
- res.Should().HaveStatusCode(404);
- }
+ await client.TestGetAsync("timelines/t1", expectedStatusCode: HttpStatusCode.NotFound);
{
- var res = await client.GetAsync("timelines/newt");
- res.Should().HaveStatusCode(200).And.HaveJsonBody<TimelineInfo>().Which.Name.Should().Be("newt");
+ var body = await client.TestGetAsync<TimelineInfo>("timelines/newt");
+ body.Name.Should().Be("newt");
}
}
}
[Theory]
- [MemberData(nameof(TimelineUrlGeneratorData))]
- public async Task PostDataETag(TimelineUrlGenerator urlGenerator)
+ [MemberData(nameof(TimelineNameGeneratorTestData))]
+ public async Task PostDataETag(TimelineNameGenerator generator)
{
using var client = await CreateClientAsUser();
@@ -1496,7 +920,7 @@ namespace Timeline.Tests.IntegratedTests
string etag;
{
- var res = await client.PostAsJsonAsync(urlGenerator(1, "posts"), new TimelinePostCreateRequest
+ var body = await client.TestPostAsync<TimelinePostInfo>($"timelines/{generator(1)}/posts", new TimelinePostCreateRequest
{
Content = new TimelinePostCreateRequestContent
{
@@ -1504,19 +928,17 @@ namespace Timeline.Tests.IntegratedTests
Data = Convert.ToBase64String(ImageHelper.CreatePngWithSize(100, 50))
}
});
- res.Should().HaveStatusCode(200);
- var body = await res.ReadBodyAsJsonAsync<TimelinePostInfo>();
- body.Content.ETag.Should().NotBeNullOrEmpty();
+ body.Content!.ETag.Should().NotBeNullOrEmpty();
id = body.Id;
- etag = body.Content.ETag;
+ etag = body.Content.ETag!;
}
{
- var res = await client.GetAsync(urlGenerator(1, $"posts/{id}/data"));
- res.Should().HaveStatusCode(200);
+ var res = await client.GetAsync($"timelines/{generator(1)}/posts/{id}/data");
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.ETag.Should().NotBeNull();
- res.Headers.ETag.ToString().Should().Be(etag);
+ res.Headers.ETag!.ToString().Should().Be(etag);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs
index 9aac8188..a5208618 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/TokenTest.cs
@@ -5,7 +5,6 @@ using System.Net.Http;
using System.Threading.Tasks;
using Timeline.Models.Http;
using Timeline.Services;
-using Timeline.Tests.Helpers;
using Xunit;
namespace Timeline.Tests.IntegratedTests
@@ -17,12 +16,10 @@ namespace Timeline.Tests.IntegratedTests
private static async Task<CreateTokenResponse> CreateUserTokenAsync(HttpClient client, string username, string password, int? expireOffset = null)
{
- var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password, Expire = expireOffset });
- return response.Should().HaveStatusCode(200)
- .And.HaveJsonBody<CreateTokenResponse>().Which;
+ return await client.TestPostAsync<CreateTokenResponse>(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password, Expire = expireOffset });
}
- public static IEnumerable<object[]> CreateToken_InvalidModel_Data()
+ public static IEnumerable<object?[]> CreateToken_InvalidModel_Data()
{
yield return new[] { null, "p", null };
yield return new[] { "u", null, null };
@@ -35,12 +32,12 @@ namespace Timeline.Tests.IntegratedTests
public async Task CreateToken_InvalidModel(string username, string password, int expire)
{
using var client = await CreateDefaultClient();
- (await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest
+ await client.TestPostAssertInvalidModelAsync(CreateTokenUrl, new CreateTokenRequest
{
Username = username,
Password = password,
Expire = expire
- })).Should().BeInvalidModel();
+ });
}
public static IEnumerable<object[]> CreateToken_UserCredential_Data()
@@ -54,42 +51,35 @@ namespace Timeline.Tests.IntegratedTests
public async void CreateToken_UserCredential(string username, string password)
{
using var client = await CreateDefaultClient();
- var response = await client.PostAsJsonAsync(CreateTokenUrl,
- new CreateTokenRequest { Username = username, Password = password });
- response.Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.TokenController.Create_BadCredential);
+ await client.TestPostAssertErrorAsync(CreateTokenUrl,
+ new CreateTokenRequest { Username = username, Password = password },
+ errorCode: ErrorCodes.TokenController.Create_BadCredential);
}
[Fact]
public async Task CreateToken_Success()
{
using var client = await CreateDefaultClient();
- var response = await client.PostAsJsonAsync(CreateTokenUrl,
+ var body = await client.TestPostAsync<CreateTokenResponse>(CreateTokenUrl,
new CreateTokenRequest { Username = "user1", Password = "user1pw" });
- var body = response.Should().HaveStatusCode(200)
- .And.HaveJsonBody<CreateTokenResponse>().Which;
body.Token.Should().NotBeNullOrWhiteSpace();
- body.User.Should().BeEquivalentTo(UserInfos[1]);
+ body.User.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
}
[Fact]
public async Task VerifyToken_InvalidModel()
{
using var client = await CreateDefaultClient();
- (await client.PostAsJsonAsync(VerifyTokenUrl,
- new VerifyTokenRequest { Token = null })).Should().BeInvalidModel();
+ await client.TestPostAssertInvalidModelAsync(VerifyTokenUrl, new VerifyTokenRequest { Token = null! });
}
[Fact]
public async Task VerifyToken_BadFormat()
{
using var client = await CreateDefaultClient();
- var response = await client.PostAsJsonAsync(VerifyTokenUrl,
- new VerifyTokenRequest { Token = "bad token hahaha" });
- response.Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.TokenController.Verify_BadFormat);
+ await client.TestPostAssertErrorAsync(VerifyTokenUrl,
+ new VerifyTokenRequest { Token = "bad token hahaha" },
+ errorCode: ErrorCodes.TokenController.Verify_BadFormat);
}
[Fact]
@@ -106,11 +96,9 @@ namespace Timeline.Tests.IntegratedTests
await userService.ModifyUser(id, new ModifyUserParams { Password = "user1pw" });
}
- (await client.PostAsJsonAsync(VerifyTokenUrl,
- new VerifyTokenRequest { Token = token }))
- .Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.TokenController.Verify_OldVersion);
+ await client.TestPostAssertErrorAsync(VerifyTokenUrl,
+ new VerifyTokenRequest { Token = token },
+ errorCode: ErrorCodes.TokenController.Verify_OldVersion);
}
[Fact]
@@ -125,11 +113,9 @@ namespace Timeline.Tests.IntegratedTests
await userService.DeleteUser("user1");
}
- (await client.PostAsJsonAsync(VerifyTokenUrl,
- new VerifyTokenRequest { Token = token }))
- .Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.TokenController.Verify_UserNotExist);
+ await client.TestPostAssertErrorAsync(VerifyTokenUrl,
+ new VerifyTokenRequest { Token = token },
+ errorCode: ErrorCodes.TokenController.Verify_UserNotExist);
}
//[Fact]
@@ -155,11 +141,9 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateDefaultClient();
var createTokenResult = await CreateUserTokenAsync(client, "user1", "user1pw");
- var response = await client.PostAsJsonAsync(VerifyTokenUrl,
+ var body = await client.TestPostAsync<VerifyTokenResponse>(VerifyTokenUrl,
new VerifyTokenRequest { Token = createTokenResult.Token });
- response.Should().HaveStatusCode(200)
- .And.HaveJsonBody<VerifyTokenResponse>()
- .Which.User.Should().BeEquivalentTo(UserInfos[1]);
+ body.User.Should().BeEquivalentTo(await client.GetUserAsync("user1"));
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UnknownEndpointTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UnknownEndpointTest.cs
index 732232e2..4389c6b4 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UnknownEndpointTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UnknownEndpointTest.cs
@@ -1,7 +1,5 @@
-using FluentAssertions;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
using Timeline.Models.Http;
-using Timeline.Tests.Helpers;
using Xunit;
namespace Timeline.Tests.IntegratedTests
@@ -12,10 +10,7 @@ namespace Timeline.Tests.IntegratedTests
public async Task UnknownEndpoint()
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync("unknownEndpoint");
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.Common.UnknownEndpoint);
+ await client.TestGetAssertErrorAsync("unknownEndpoint", errorCode: ErrorCodes.Common.UnknownEndpoint);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserAvatarTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserAvatarTest.cs
index 854a4ee6..893a5d28 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UserAvatarTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UserAvatarTest.cs
@@ -31,117 +31,83 @@ namespace Timeline.Tests.IntegratedTests
using (var client = await CreateClientAsUser())
{
- {
- var res = await client.GetAsync("users/usernotexist/avatar");
- res.Should().HaveStatusCode(404)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
- }
+ await client.TestGetAssertNotFoundAsync("users/usernotexist/avatar", errorCode: ErrorCodes.UserCommon.NotExist);
var env = TestApp.Host.Services.GetRequiredService<IWebHostEnvironment>();
var defaultAvatarData = await File.ReadAllBytesAsync(Path.Combine(env.ContentRootPath, "default-avatar.png"));
- async Task GetReturnDefault(string username = "user1")
+ async Task TestAvatar(string username, byte[] data)
{
var res = await client.GetAsync($"users/{username}/avatar");
- res.Should().HaveStatusCode(200);
- res.Content.Headers.ContentType.MediaType.Should().Be("image/png");
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
+ var contentTypeHeader = res.Content.Headers.ContentType;
+ contentTypeHeader.Should().NotBeNull();
+ contentTypeHeader!.MediaType.Should().Be("image/png");
var body = await res.Content.ReadAsByteArrayAsync();
- body.Should().Equal(defaultAvatarData);
+ body.Should().Equal(data);
}
- {
- var res = await client.GetAsync("users/user1/avatar");
- res.Should().HaveStatusCode(200);
- res.Content.Headers.ContentType.MediaType.Should().Be("image/png");
- var body = await res.Content.ReadAsByteArrayAsync();
- body.Should().Equal(defaultAvatarData);
- }
+ await TestAvatar("user1", defaultAvatarData);
await CacheTestHelper.TestCache(client, "users/user1/avatar");
- await GetReturnDefault("admin");
+ await TestAvatar("admin", defaultAvatarData);
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = null;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().BeInvalidModel();
+ await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 1;
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().BeInvalidModel();
+ await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 0;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().BeInvalidModel();
+ await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
- var res = await client.PutByteArrayAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/notaccept");
- res.Should().HaveStatusCode(HttpStatusCode.UnsupportedMediaType);
+ await client.TestPutByteArrayAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/notaccept", expectedStatusCode: HttpStatusCode.UnsupportedMediaType);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 1000 * 1000 * 11;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.Common.Content.TooBig);
+ await client.TestSendAssertErrorAsync(HttpMethod.Put, "users/user1/avatar", content, errorCode: ErrorCodes.Common.Content.TooBig);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 2;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().BeInvalidModel();
+ await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00, (byte)0x01 });
content.Headers.ContentLength = 1;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
- var res = await client.PutAsync("users/user1/avatar", content);
- res.Should().BeInvalidModel();
- }
+ await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
- {
- var res = await client.PutByteArrayAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/png");
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.UserAvatar.BadFormat_CantDecode);
}
{
- var res = await client.PutByteArrayAsync("users/user1/avatar", mockAvatar.Data, "image/jpeg");
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.UserAvatar.BadFormat_UnmatchedFormat);
+ await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/png", errorCode: ErrorCodes.UserAvatar.BadFormat_CantDecode);
+ await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", mockAvatar.Data, "image/jpeg", errorCode: ErrorCodes.UserAvatar.BadFormat_UnmatchedFormat);
+ await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", ImageHelper.CreatePngWithSize(100, 200), "image/png", errorCode: ErrorCodes.UserAvatar.BadFormat_BadSize);
}
{
- var res = await client.PutByteArrayAsync("users/user1/avatar", ImageHelper.CreatePngWithSize(100, 200), "image/png");
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.UserAvatar.BadFormat_BadSize);
- }
-
- {
- var res = await client.PutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.Type);
- res.Should().HaveStatusCode(HttpStatusCode.OK);
-
- var res2 = await client.GetAsync("users/user1/avatar");
- res2.Should().HaveStatusCode(200);
- res2.Content.Headers.ContentType.MediaType.Should().Be(mockAvatar.Type);
- var body = await res2.Content.ReadAsByteArrayAsync();
- body.Should().Equal(mockAvatar.Data);
+ await client.TestPutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.Type);
+ await TestAvatar("user1", mockAvatar.Data);
}
IEnumerable<(string, IImageFormat)> formats = new (string, IImageFormat)[]
@@ -153,74 +119,36 @@ namespace Timeline.Tests.IntegratedTests
foreach ((var mimeType, var format) in formats)
{
- var res = await client.PutByteArrayAsync("users/user1/avatar", ImageHelper.CreateImageWithSize(100, 100, format), mimeType);
- res.Should().HaveStatusCode(HttpStatusCode.OK);
+ await client.TestPutByteArrayAsync("users/user1/avatar", ImageHelper.CreateImageWithSize(100, 100, format), mimeType);
}
- {
- var res = await client.PutByteArrayAsync("users/admin/avatar", new[] { (byte)0x00 }, "image/png");
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.Common.Forbid);
- }
+ await client.TestPutByteArrayAssertErrorAsync("users/admin/avatar", new[] { (byte)0x00 }, "image/png",
+ expectedStatusCode: HttpStatusCode.Forbidden, errorCode: ErrorCodes.Common.Forbid);
- {
- var res = await client.DeleteAsync("users/admin/avatar");
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.Common.Forbid);
- }
+ await client.TestDeleteAssertForbiddenAsync("users/admin/avatar", errorCode: ErrorCodes.Common.Forbid);
for (int i = 0; i < 2; i++) // double delete should work.
{
- var res = await client.DeleteAsync("users/user1/avatar");
- res.Should().HaveStatusCode(200);
- await GetReturnDefault();
+ await client.TestDeleteAsync("users/user1/avatar");
+ await TestAvatar("user1", defaultAvatarData);
}
}
// Authorization check.
using (var client = await CreateClientAsAdministrator())
{
- {
- var res = await client.PutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.Type);
- res.Should().HaveStatusCode(HttpStatusCode.OK);
- }
-
- {
- var res = await client.DeleteAsync("users/user1/avatar");
- res.Should().HaveStatusCode(HttpStatusCode.OK);
- }
-
- {
- var res = await client.PutByteArrayAsync("users/usernotexist/avatar", new[] { (byte)0x00 }, "image/png");
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
- }
-
- {
- var res = await client.DeleteAsync("users/usernotexist/avatar");
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody().Which.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
- }
+ await client.TestPutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.Type);
+ await client.TestDeleteAsync("users/user1/avatar");
+ await client.TestPutByteArrayAssertErrorAsync("users/usernotexist/avatar", new[] { (byte)0x00 }, "image/png", errorCode: ErrorCodes.UserCommon.NotExist);
+ await client.TestDeleteAssertErrorAsync("users/usernotexist/avatar", errorCode: ErrorCodes.UserCommon.NotExist);
}
// bad username check
using (var client = await CreateClientAsAdministrator())
{
- {
- 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();
- }
+ await client.TestGetAssertInvalidModelAsync("users/u!ser/avatar");
+ await client.TestPutByteArrayAssertInvalidModelAsync("users/u!ser/avatar", ImageHelper.CreatePngWithSize(100, 100), "image/png");
+ await client.TestDeleteAssertInvalidModelAsync("users/u!ser/avatar");
}
}
@@ -229,22 +157,21 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsUser();
- EntityTagHeaderValue etag;
+ EntityTagHeaderValue? etag;
{
var image = ImageHelper.CreatePngWithSize(100, 100);
- var res = await client.PutByteArrayAsync("users/user1/avatar", image, PngFormat.Instance.DefaultMimeType);
- res.Should().HaveStatusCode(200);
+ var res = await client.TestPutByteArrayAsync("users/user1/avatar", image, PngFormat.Instance.DefaultMimeType);
etag = res.Headers.ETag;
etag.Should().NotBeNull();
- etag.Tag.Should().NotBeNullOrEmpty();
+ etag!.Tag.Should().NotBeNullOrEmpty();
}
{
var res = await client.GetAsync("users/user1/avatar");
- res.Should().HaveStatusCode(200);
+ res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.ETag.Should().Be(etag);
- res.Headers.ETag.Tag.Should().Be(etag.Tag);
+ res.Headers.ETag!.Tag.Should().Be(etag.Tag);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
index cf27a6c6..77cae590 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UserPermissionTest.cs
@@ -2,8 +2,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Net;
-using System.Net.Http.Json;
using System.Threading.Tasks;
using Timeline.Models.Http;
using Timeline.Services;
@@ -19,9 +17,7 @@ namespace Timeline.Tests.IntegratedTests
public async Task RootUserShouldReturnAllPermissions()
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync("users/admin");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("admin");
body.Permissions.Should().BeEquivalentTo(Enum.GetNames<UserPermission>());
}
@@ -29,9 +25,7 @@ namespace Timeline.Tests.IntegratedTests
public async Task NonRootUserShouldReturnNonPermissions()
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEmpty();
}
@@ -46,27 +40,17 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.DeleteAsync($"users/admin/permissions/{permission}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/admin/permissions/{permission}");
{
- var res = await client.GetAsync("users/admin");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("admin");
body.Permissions.Should().BeEquivalentTo(Enum.GetNames<UserPermission>());
}
- {
- var res = await client.PutAsync($"users/admin/permissions/{permission}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/admin/permissions/{permission}");
{
- var res = await client.GetAsync("users/admin");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("admin");
body.Permissions.Should().BeEquivalentTo(Enum.GetNames<UserPermission>());
}
}
@@ -77,27 +61,17 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PutAsync($"users/user1/permissions/{permission}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{permission}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(permission.ToString());
}
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{permission}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{permission}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEmpty();
}
}
@@ -108,27 +82,17 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PutAsync($"users/user1/permissions/{permission}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{permission}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(permission.ToString());
}
- {
- var res = await client.PutAsync($"users/user1/permissions/{permission}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{permission}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(permission.ToString());
}
}
@@ -139,15 +103,10 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{permission}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{permission}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEmpty();
}
}
@@ -157,106 +116,66 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PutAsync($"users/user1/permissions/{UserPermission.AllTimelineManagement}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{UserPermission.AllTimelineManagement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(UserPermission.AllTimelineManagement.ToString());
}
- {
- var res = await client.PutAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(UserPermission.AllTimelineManagement.ToString(),
UserPermission.HighlightTimelineManangement.ToString());
}
- {
- var res = await client.PutAsync($"users/user1/permissions/{UserPermission.UserManagement}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{UserPermission.UserManagement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(
UserPermission.AllTimelineManagement.ToString(),
UserPermission.HighlightTimelineManangement.ToString(),
UserPermission.UserManagement.ToString());
}
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(
UserPermission.AllTimelineManagement.ToString(),
UserPermission.UserManagement.ToString());
}
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{UserPermission.AllTimelineManagement}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{UserPermission.AllTimelineManagement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(UserPermission.UserManagement.ToString());
}
- {
- var res = await client.PutAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}", null);
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestPutAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(
UserPermission.HighlightTimelineManangement.ToString(), UserPermission.UserManagement.ToString());
}
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{UserPermission.HighlightTimelineManangement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEquivalentTo(UserPermission.UserManagement.ToString());
}
- {
- var res = await client.DeleteAsync($"users/user1/permissions/{UserPermission.UserManagement}");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- }
+ await client.TestDeleteAsync($"users/user1/permissions/{UserPermission.UserManagement}");
{
- var res = await client.GetAsync("users/user1");
- res.StatusCode.Should().Be(HttpStatusCode.OK);
- var body = await res.Content.ReadFromJsonAsync<UserInfo>();
+ var body = await client.GetUserAsync("user1");
body.Permissions.Should().BeEmpty();
}
}
@@ -268,19 +187,8 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PutAsync(url, null);
- res.StatusCode.Should().Be(HttpStatusCode.BadRequest);
- var body = await res.Content.ReadFromJsonAsync<CommonResponse>();
- body.Code.Should().Be(ErrorCodes.Common.InvalidModel);
- }
-
- {
- var res = await client.DeleteAsync(url);
- res.StatusCode.Should().Be(HttpStatusCode.BadRequest);
- var body = await res.Content.ReadFromJsonAsync<CommonResponse>();
- body.Code.Should().Be(ErrorCodes.Common.InvalidModel);
- }
+ await client.TestPutAssertInvalidModelAsync(url);
+ await client.TestDeleteAssertInvalidModelAsync(url);
}
[Fact]
@@ -290,19 +198,8 @@ namespace Timeline.Tests.IntegratedTests
const string url = "users/user123/permissions/UserManagement";
- {
- var res = await client.PutAsync(url, null);
- res.StatusCode.Should().Be(HttpStatusCode.NotFound);
- var body = await res.Content.ReadFromJsonAsync<CommonResponse>();
- body.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
- }
-
- {
- var res = await client.DeleteAsync(url);
- res.StatusCode.Should().Be(HttpStatusCode.NotFound);
- var body = await res.Content.ReadFromJsonAsync<CommonResponse>();
- body.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
- }
+ await client.TestPutAssertNotFoundAsync(url, errorCode: ErrorCodes.UserCommon.NotExist);
+ await client.TestDeleteAssertNotFoundAsync(url, errorCode: ErrorCodes.UserCommon.NotExist);
}
}
}
diff --git a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
index 329e53f5..0c2e0b0d 100644
--- a/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
+++ b/BackEnd/Timeline.Tests/IntegratedTests/UserTest.cs
@@ -1,11 +1,7 @@
using FluentAssertions;
using System.Collections.Generic;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
using System.Threading.Tasks;
using Timeline.Models.Http;
-using Timeline.Tests.Helpers;
using Xunit;
namespace Timeline.Tests.IntegratedTests
@@ -13,89 +9,41 @@ namespace Timeline.Tests.IntegratedTests
public class UserTest : IntegratedTestBase
{
[Fact]
- public void UserListShouldHaveUniqueId()
+ public async Task UserListShouldHaveUniqueId()
{
- foreach (var user in UserInfos)
+ using var client = await CreateDefaultClient();
+ foreach (var user in await client.TestGetAsync<List<UserInfo>>("users"))
{
user.UniqueId.Should().NotBeNullOrWhiteSpace();
}
}
[Fact]
- public async Task GetList_NoAuth()
+ public async Task GetList()
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync("users");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo[]>()
- .Which.Should().BeEquivalentTo(UserInfos);
- }
-
- [Fact]
- public async Task GetList_User()
- {
- using var client = await CreateClientAsUser();
- var res = await client.GetAsync("users");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo[]>()
- .Which.Should().BeEquivalentTo(UserInfos);
- }
-
- [Fact]
- public async Task GetList_Admin()
- {
- using var client = await CreateClientAsAdministrator();
- var res = await client.GetAsync("users");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo[]>()
- .Which.Should().BeEquivalentTo(UserInfos);
+ await client.TestGetAsync<List<UserInfo>>("users");
}
[Fact]
- public async Task Get_NoAuth()
+ public async Task Get()
{
using var client = await CreateDefaultClient();
- var res = await client.GetAsync($"users/admin");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which.Should().BeEquivalentTo(UserInfos[0]);
- }
-
- [Fact]
- public async Task Get_User()
- {
- using var client = await CreateClientAsUser();
- var res = await client.GetAsync($"users/admin");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which.Should().BeEquivalentTo(UserInfos[0]);
- }
-
- [Fact]
- public async Task Get_Admin()
- {
- using var client = await CreateClientAsAdministrator();
- var res = await client.GetAsync($"users/user1");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which.Should().BeEquivalentTo(UserInfos[1]);
+ await client.TestGetAsync<UserInfo>($"users/admin");
}
[Fact]
public async Task Get_InvalidModel()
{
- using var client = await CreateClientAsUser();
- var res = await client.GetAsync("users/aaa!a");
- res.Should().BeInvalidModel();
+ using var client = await CreateDefaultClient();
+ await client.TestGetAssertInvalidModelAsync("users/aaa!a");
}
[Fact]
public async Task Get_404()
{
- using var client = await CreateClientAsUser();
- var res = await client.GetAsync("users/usernotexist");
- res.Should().HaveStatusCode(404)
- .And.HaveCommonBody(ErrorCodes.UserCommon.NotExist);
+ using var client = await CreateDefaultClient();
+ await client.TestGetAssertNotFoundAsync("users/usernotexist", errorCode: ErrorCodes.UserCommon.NotExist);
}
[Fact]
@@ -103,18 +51,14 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsUser();
{
- var res = await client.PatchAsJsonAsync("users/user1",
+ var body = await client.TestPatchAsync<UserInfo>("users/user1",
new UserPatchRequest { Nickname = "aaa" });
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which.Nickname.Should().Be("aaa");
+ body.Nickname.Should().Be("aaa");
}
{
- var res = await client.GetAsync("users/user1");
- res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which.Nickname.Should().Be("aaa");
+ var body = await client.GetUserAsync("user1");
+ body.Nickname.Should().Be("aaa");
}
}
@@ -125,32 +69,25 @@ namespace Timeline.Tests.IntegratedTests
using var userClient = await CreateClientAsUser();
{
- var res = await client.PatchAsJsonAsync("users/user1",
+ var body = await client.TestPatchAsync<UserInfo>("users/user1",
new UserPatchRequest
{
Username = "newuser",
Password = "newpw",
Nickname = "aaa"
});
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which;
body.Nickname.Should().Be("aaa");
}
{
- var res = await client.GetAsync("users/newuser");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>()
- .Which;
+ var body = await client.GetUserAsync("newuser");
body.Nickname.Should().Be("aaa");
}
{
- var token = userClient.DefaultRequestHeaders.Authorization.Parameter;
+ var token = userClient.DefaultRequestHeaders.Authorization!.Parameter!;
// Token should expire.
- var res = await userClient.PostAsJsonAsync<VerifyTokenRequest>("token/verify", new() { Token = token });
- res.Should().HaveStatusCode(HttpStatusCode.BadRequest);
+ await userClient.TestPostAssertErrorAsync("token/verify", new VerifyTokenRequest() { Token = token });
}
{
@@ -163,18 +100,14 @@ namespace Timeline.Tests.IntegratedTests
public async Task Patch_NotExist()
{
using var client = await CreateClientAsAdministrator();
- var res = await client.PatchAsJsonAsync("users/usernotexist", new UserPatchRequest { });
- res.Should().HaveStatusCode(404)
- .And.HaveCommonBody()
- .Which.Code.Should().Be(ErrorCodes.UserCommon.NotExist);
+ await client.TestPatchAssertNotFoundAsync("users/usernotexist", new UserPatchRequest { }, errorCode: ErrorCodes.UserCommon.NotExist);
}
[Fact]
public async Task Patch_InvalidModel()
{
using var client = await CreateClientAsAdministrator();
- var res = await client.PatchAsJsonAsync("users/aaa!a", new UserPatchRequest { });
- res.Should().BeInvalidModel();
+ await client.TestPatchAssertInvalidModelAsync("users/aaa!a", new UserPatchRequest { });
}
public static IEnumerable<object[]> Patch_InvalidModel_Body_Data()
@@ -189,96 +122,78 @@ namespace Timeline.Tests.IntegratedTests
public async Task Patch_InvalidModel_Body(UserPatchRequest body)
{
using var client = await CreateClientAsAdministrator();
- var res = await client.PatchAsJsonAsync("users/user1", body);
- res.Should().BeInvalidModel();
+ await client.TestPatchAssertInvalidModelAsync("users/user1", body);
}
[Fact]
public async Task Patch_UsernameConflict()
{
using var client = await CreateClientAsAdministrator();
- var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { Username = "admin" });
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.UserController.UsernameConflict);
+ await client.TestPatchAssertErrorAsync("users/user1", new UserPatchRequest { Username = "admin" }, errorCode: ErrorCodes.UserController.UsernameConflict);
}
[Fact]
public async Task Patch_NoAuth_Unauthorized()
{
using var client = await CreateDefaultClient();
- var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { Nickname = "aaa" });
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
+ await client.TestPatchAssertUnauthorizedAsync("users/user1", new UserPatchRequest { Nickname = "aaa" });
}
[Fact]
public async Task Patch_User_Forbid()
{
using var client = await CreateClientAsUser();
- var res = await client.PatchAsJsonAsync("users/admin", new UserPatchRequest { Nickname = "aaa" });
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
+ await client.TestPatchAssertForbiddenAsync("users/admin", new UserPatchRequest { Nickname = "aaa" });
}
[Fact]
public async Task Patch_Username_Forbid()
{
using var client = await CreateClientAsUser();
- var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { Username = "aaa" });
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
+ await client.TestPatchAssertForbiddenAsync("users/user1", new UserPatchRequest { Username = "aaa" });
}
[Fact]
public async Task Patch_Password_Forbid()
{
using var client = await CreateClientAsUser();
- var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { Password = "aaa" });
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
+ await client.TestPatchAssertForbiddenAsync("users/user1", new UserPatchRequest { Password = "aaa" });
}
[Fact]
public async Task Delete_Deleted()
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.DeleteAsync("users/user1");
- res.Should().BeDelete(true);
- }
-
- {
- var res = await client.GetAsync("users/user1");
- res.Should().HaveStatusCode(404);
- }
+ await client.TestDeleteAsync("users/user1", true);
+ await client.TestGetAssertNotFoundAsync("users/user1");
}
[Fact]
public async Task Delete_NotExist()
{
using var client = await CreateClientAsAdministrator();
- var res = await client.DeleteAsync("users/usernotexist");
- res.Should().BeDelete(false);
+ await client.TestDeleteAsync("users/usernotexist", false);
}
[Fact]
public async Task Delete_InvalidModel()
{
using var client = await CreateClientAsAdministrator();
- var res = await client.DeleteAsync("users/aaa!a");
- res.Should().BeInvalidModel();
+ await client.TestDeleteAssertInvalidModelAsync("users/aaa!a");
}
[Fact]
public async Task Delete_NoAuth_Unauthorized()
{
using var client = await CreateDefaultClient();
- var res = await client.DeleteAsync("users/aaa!a");
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
+ await client.TestDeleteAssertUnauthorizedAsync("users/aaa!a");
}
[Fact]
public async Task Delete_User_Forbid()
{
using var client = await CreateClientAsUser();
- var res = await client.DeleteAsync("users/aaa!a");
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
+ await client.TestDeleteAssertForbiddenAsync("users/aaa!a");
}
private const string createUserUrl = "userop/createuser";
@@ -288,19 +203,15 @@ namespace Timeline.Tests.IntegratedTests
{
using var client = await CreateClientAsAdministrator();
{
- var res = await client.PostAsJsonAsync(createUserUrl, new CreateUserRequest
+ var body = await client.TestPostAsync<UserInfo>(createUserUrl, new CreateUserRequest
{
Username = "aaa",
Password = "bbb",
});
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>().Which;
body.Username.Should().Be("aaa");
}
{
- var res = await client.GetAsync("users/aaa");
- var body = res.Should().HaveStatusCode(200)
- .And.HaveJsonBody<UserInfo>().Which;
+ var body = await client.GetUserAsync("aaa");
body.Username.Should().Be("aaa");
}
{
@@ -322,53 +233,40 @@ namespace Timeline.Tests.IntegratedTests
public async Task Op_CreateUser_InvalidModel(CreateUserRequest body)
{
using var client = await CreateClientAsAdministrator();
- {
- var res = await client.PostAsJsonAsync(createUserUrl, body);
- res.Should().BeInvalidModel();
- }
+ await client.TestPostAssertInvalidModelAsync(createUserUrl, body);
}
[Fact]
public async Task Op_CreateUser_UsernameConflict()
{
using var client = await CreateClientAsAdministrator();
+ await client.TestPostAssertErrorAsync(createUserUrl, new CreateUserRequest
{
- var res = await client.PostAsJsonAsync(createUserUrl, new CreateUserRequest
- {
- Username = "user1",
- Password = "bbb",
- });
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.UserController.UsernameConflict);
- }
+ Username = "user1",
+ Password = "bbb",
+ }, errorCode: ErrorCodes.UserController.UsernameConflict);
}
[Fact]
public async Task Op_CreateUser_NoAuth_Unauthorized()
{
using var client = await CreateDefaultClient();
+ await client.TestPostAssertUnauthorizedAsync(createUserUrl, new CreateUserRequest
{
- var res = await client.PostAsJsonAsync(createUserUrl, new CreateUserRequest
- {
- Username = "aaa",
- Password = "bbb",
- });
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
- }
+ Username = "aaa",
+ Password = "bbb",
+ });
}
[Fact]
public async Task Op_CreateUser_User_Forbid()
{
using var client = await CreateClientAsUser();
+ await client.TestPostAssertForbiddenAsync(createUserUrl, new CreateUserRequest
{
- var res = await client.PostAsJsonAsync(createUserUrl, new CreateUserRequest
- {
- Username = "aaa",
- Password = "bbb",
- });
- res.Should().HaveStatusCode(HttpStatusCode.Forbidden);
- }
+ Username = "aaa",
+ Password = "bbb",
+ });
}
private const string changePasswordUrl = "userop/changepassword";
@@ -377,21 +275,12 @@ namespace Timeline.Tests.IntegratedTests
public async Task Op_ChangePassword()
{
using var client = await CreateClientAsUser();
- {
- var res = await client.PostAsJsonAsync(changePasswordUrl,
- new ChangePasswordRequest { OldPassword = "user1pw", NewPassword = "newpw" });
- res.Should().HaveStatusCode(200);
- }
- {
- var res = await client.PatchAsJsonAsync("users/user1", new UserPatchRequest { });
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
- }
- {
- (await CreateClientWithCredential("user1", "newpw")).Dispose();
- }
+ await client.TestPostAsync(changePasswordUrl, new ChangePasswordRequest { OldPassword = "user1pw", NewPassword = "newpw" });
+ await client.TestPatchAssertUnauthorizedAsync("users/user1", new UserPatchRequest { });
+ (await CreateClientWithCredential("user1", "newpw")).Dispose();
}
- public static IEnumerable<object[]> Op_ChangePassword_InvalidModel_Data()
+ public static IEnumerable<object?[]> Op_ChangePassword_InvalidModel_Data()
{
yield return new[] { null, "ppp" };
yield return new[] { "ppp", null };
@@ -402,26 +291,22 @@ namespace Timeline.Tests.IntegratedTests
public async Task Op_ChangePassword_InvalidModel(string oldPassword, string newPassword)
{
using var client = await CreateClientAsUser();
- var res = await client.PostAsJsonAsync(changePasswordUrl,
+ await client.TestPostAssertInvalidModelAsync(changePasswordUrl,
new ChangePasswordRequest { OldPassword = oldPassword, NewPassword = newPassword });
- res.Should().BeInvalidModel();
}
[Fact]
public async Task Op_ChangePassword_BadOldPassword()
{
using var client = await CreateClientAsUser();
- var res = await client.PostAsJsonAsync(changePasswordUrl, new ChangePasswordRequest { OldPassword = "???", NewPassword = "???" });
- res.Should().HaveStatusCode(400)
- .And.HaveCommonBody(ErrorCodes.UserController.ChangePassword_BadOldPassword);
+ await client.TestPostAssertErrorAsync(changePasswordUrl, new ChangePasswordRequest { OldPassword = "???", NewPassword = "???" }, errorCode: ErrorCodes.UserController.ChangePassword_BadOldPassword);
}
[Fact]
public async Task Op_ChangePassword_NoAuth_Unauthorized()
{
using var client = await CreateDefaultClient();
- var res = await client.PostAsJsonAsync(changePasswordUrl, new ChangePasswordRequest { OldPassword = "???", NewPassword = "???" });
- res.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
+ await client.TestPostAssertUnauthorizedAsync(changePasswordUrl, new ChangePasswordRequest { OldPassword = "???", NewPassword = "???" });
}
}
}
diff --git a/BackEnd/Timeline.Tests/Services/DatabaseBasedTest.cs b/BackEnd/Timeline.Tests/Services/DatabaseBasedTest.cs
index 7c97158c..3bb6ebb5 100644
--- a/BackEnd/Timeline.Tests/Services/DatabaseBasedTest.cs
+++ b/BackEnd/Timeline.Tests/Services/DatabaseBasedTest.cs
@@ -8,7 +8,7 @@ namespace Timeline.Tests.Services
public abstract class DatabaseBasedTest : IAsyncLifetime
{
protected TestDatabase TestDatabase { get; }
- protected DatabaseContext Database { get; private set; }
+ protected DatabaseContext Database { get; private set; } = default!;
protected DatabaseBasedTest(bool databaseCreateUsers = true)
{
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/Services/UserPermissionServiceTest.cs b/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
index cea11b34..5a4e4954 100644
--- a/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
+++ b/BackEnd/Timeline.Tests/Services/UserPermissionServiceTest.cs
@@ -9,7 +9,7 @@ namespace Timeline.Tests.Services
{
public class UserPermissionServiceTest : DatabaseBasedTest
{
- private UserPermissionService _service;
+ private UserPermissionService _service = default!;
public UserPermissionServiceTest()
{
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.Tests/UsernameValidatorUnitTest.cs b/BackEnd/Timeline.Tests/UsernameValidatorUnitTest.cs
index 5b568adf..7022b311 100644
--- a/BackEnd/Timeline.Tests/UsernameValidatorUnitTest.cs
+++ b/BackEnd/Timeline.Tests/UsernameValidatorUnitTest.cs
@@ -1,6 +1,5 @@
using FluentAssertions;
using Timeline.Models.Validation;
-using Timeline.Tests.Helpers;
using Xunit;
namespace Timeline.Tests