aboutsummaryrefslogtreecommitdiff
path: root/Timeline.Tests
diff options
context:
space:
mode:
Diffstat (limited to 'Timeline.Tests')
-rw-r--r--Timeline.Tests/AuthorizationUnitTest.cs14
-rw-r--r--Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs (renamed from Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs)17
-rw-r--r--Timeline.Tests/Helpers/TestUsers.cs40
-rw-r--r--Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs22
-rw-r--r--Timeline.Tests/JwtTokenUnitTest.cs6
-rw-r--r--Timeline.Tests/QCloudCosServiceUnitTest.cs104
-rw-r--r--Timeline.Tests/Timeline.Tests.csproj2
-rw-r--r--Timeline.Tests/UserUnitTest.cs36
8 files changed, 204 insertions, 37 deletions
diff --git a/Timeline.Tests/AuthorizationUnitTest.cs b/Timeline.Tests/AuthorizationUnitTest.cs
index e450af06..28715ada 100644
--- a/Timeline.Tests/AuthorizationUnitTest.cs
+++ b/Timeline.Tests/AuthorizationUnitTest.cs
@@ -26,7 +26,7 @@ namespace Timeline.Tests
{
using (var client = _factory.CreateDefaultClient())
{
- var response = await client.GetAsync(NeedAuthorizeUrl);
+ var response = await client.GetAsync(NeedAuthorizeUrl);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
@@ -34,10 +34,9 @@ namespace Timeline.Tests
[Fact]
public async Task AuthenticationTest()
{
- using (var client = _factory.CreateDefaultClient())
+ using (var client = await _factory.CreateClientWithUser("user", "user"))
{
- var token = (await client.CreateUserTokenAsync("user", "user")).Token;
- var response = await client.SendWithAuthenticationAsync(token, NeedAuthorizeUrl);
+ var response = await client.GetAsync(NeedAuthorizeUrl);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
@@ -58,12 +57,11 @@ namespace Timeline.Tests
[Fact]
public async Task AdminAuthorizationTest()
{
- using (var client = _factory.CreateDefaultClient())
+ using (var client = await _factory.CreateClientWithUser("admin", "admin"))
{
- var token = (await client.CreateUserTokenAsync("admin", "admin")).Token;
- var response1 = await client.SendWithAuthenticationAsync(token, BothUserAndAdminUrl);
+ var response1 = await client.GetAsync(BothUserAndAdminUrl);
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
- var response2 = await client.SendWithAuthenticationAsync(token, OnlyAdminUrl);
+ var response2 = await client.GetAsync(OnlyAdminUrl);
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
}
}
diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs
index c0051c53..cda9fe99 100644
--- a/Timeline.Tests/Helpers/Authentication/AuthenticationHttpClientExtensions.cs
+++ b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs
@@ -1,16 +1,17 @@
-using Newtonsoft.Json;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
-using Timeline.Entities;
+using Timeline.Entities.Http;
using Xunit;
namespace Timeline.Tests.Helpers.Authentication
{
- public static class AuthenticationHttpClientExtensions
+ public static class AuthenticationExtensions
{
- private const string CreateTokenUrl = "/User/CreateToken";
+ private const string CreateTokenUrl = "/token/create";
public static async Task<CreateTokenResponse> CreateUserTokenAsync(this HttpClient client, string username, string password, bool assertSuccess = true)
{
@@ -24,6 +25,14 @@ namespace Timeline.Tests.Helpers.Authentication
return result;
}
+ public static async Task<HttpClient> CreateClientWithUser<T>(this WebApplicationFactory<T> factory, string username, string password) where T : class
+ {
+ var client = factory.CreateDefaultClient();
+ var token = (await client.CreateUserTokenAsync(username, password)).Token;
+ client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
+ return client;
+ }
+
public static async Task<HttpResponseMessage> SendWithAuthenticationAsync(this HttpClient client, string token, string path, Action<HttpRequestMessage> requestBuilder = null)
{
var request = new HttpRequestMessage
diff --git a/Timeline.Tests/Helpers/TestUsers.cs b/Timeline.Tests/Helpers/TestUsers.cs
new file mode 100644
index 00000000..89ddf218
--- /dev/null
+++ b/Timeline.Tests/Helpers/TestUsers.cs
@@ -0,0 +1,40 @@
+using System.Collections.Generic;
+using System.Linq;
+using Timeline.Entities;
+using Timeline.Models;
+using Timeline.Services;
+
+namespace Timeline.Tests.Helpers
+{
+ public static class TestMockUsers
+ {
+ static TestMockUsers()
+ {
+ var mockUsers = new List<User>();
+ var passwordService = new PasswordService(null);
+
+ mockUsers.Add(new User
+ {
+ Name = "user",
+ EncryptedPassword = passwordService.HashPassword("user"),
+ RoleString = "user"
+ });
+ mockUsers.Add(new User
+ {
+ Name = "admin",
+ EncryptedPassword = passwordService.HashPassword("admin"),
+ RoleString = "user,admin"
+ });
+
+ MockUsers = mockUsers;
+
+ var mockUserInfos = mockUsers.Select(u => UserInfo.Create(u)).ToList();
+ mockUserInfos.Sort(UserInfo.Comparer);
+ MockUserInfos = mockUserInfos;
+ }
+
+ public static List<User> MockUsers { get; }
+
+ public static IReadOnlyList<UserInfo> MockUserInfos { get; }
+ }
+}
diff --git a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs b/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs
index 4a7f87fb..a7616b41 100644
--- a/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs
+++ b/Timeline.Tests/Helpers/WebApplicationFactoryExtensions.cs
@@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Timeline.Models;
-using Timeline.Services;
using Xunit.Abstractions;
namespace Timeline.Tests.Helpers
@@ -16,7 +15,6 @@ namespace Timeline.Tests.Helpers
return factory.WithWebHostBuilder(builder =>
{
builder
- .UseEnvironment(EnvironmentConstants.TestEnvironmentName)
.ConfigureLogging(logging =>
{
logging.AddXunit(outputHelper);
@@ -42,28 +40,10 @@ namespace Timeline.Tests.Helpers
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<DatabaseContext>();
- var passwordService = new PasswordService(null);
-
// Ensure the database is created.
db.Database.EnsureCreated();
- db.Users.AddRange(new User[] {
- new User
- {
- Id = 0,
- Name = "user",
- EncryptedPassword = passwordService.HashPassword("user"),
- RoleString = "user"
- },
- new User
- {
- Id = 0,
- Name = "admin",
- EncryptedPassword = passwordService.HashPassword("admin"),
- RoleString = "user,admin"
- }
- });
-
+ db.Users.AddRange(TestMockUsers.MockUsers);
db.SaveChanges();
}
});
diff --git a/Timeline.Tests/JwtTokenUnitTest.cs b/Timeline.Tests/JwtTokenUnitTest.cs
index fa9c7628..8a503bd7 100644
--- a/Timeline.Tests/JwtTokenUnitTest.cs
+++ b/Timeline.Tests/JwtTokenUnitTest.cs
@@ -2,7 +2,7 @@
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
-using Timeline.Entities;
+using Timeline.Entities.Http;
using Timeline.Tests.Helpers;
using Timeline.Tests.Helpers.Authentication;
using Xunit;
@@ -12,8 +12,8 @@ namespace Timeline.Tests
{
public class JwtTokenUnitTest : IClassFixture<WebApplicationFactory<Startup>>
{
- private const string CreateTokenUrl = "User/CreateToken";
- private const string VerifyTokenUrl = "User/VerifyToken";
+ private const string CreateTokenUrl = "token/create";
+ private const string VerifyTokenUrl = "token/verify";
private readonly WebApplicationFactory<Startup> _factory;
diff --git a/Timeline.Tests/QCloudCosServiceUnitTest.cs b/Timeline.Tests/QCloudCosServiceUnitTest.cs
new file mode 100644
index 00000000..0940c70d
--- /dev/null
+++ b/Timeline.Tests/QCloudCosServiceUnitTest.cs
@@ -0,0 +1,104 @@
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+using Timeline.Services;
+using Timeline.Tests.Helpers;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Timeline.Tests
+{
+ public class QCloudCosServiceUnitTest : IClassFixture<WebApplicationFactory<Startup>>
+ {
+ private readonly WebApplicationFactory<Startup> _factory;
+
+ public QCloudCosServiceUnitTest(WebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper)
+ {
+ _factory = factory.WithTestConfig(outputHelper);
+ _factory.CreateDefaultClient().Dispose(); // Ensure test server is created.
+ }
+
+ [Fact]
+ public void ValidateBucketNameTest()
+ {
+ Assert.True(QCloudCosService.ValidateBucketName("hello"));
+ Assert.True(QCloudCosService.ValidateBucketName("hello0123"));
+ Assert.True(QCloudCosService.ValidateBucketName("hello0123-hello"));
+ Assert.False(QCloudCosService.ValidateBucketName("-hello"));
+ Assert.False(QCloudCosService.ValidateBucketName("hello-"));
+ Assert.False(QCloudCosService.ValidateBucketName("helloU"));
+ Assert.False(QCloudCosService.ValidateBucketName("hello!"));
+ }
+
+ [Fact]
+ public void GenerateSignatureTest()
+ {
+ var credential = new QCloudCosService.QCloudCredentials
+ {
+ SecretId = "AKIDQjz3ltompVjBni5LitkWHFlFpwkn9U5q",
+ SecretKey = "BQYIM75p8x0iWVFSIgqEKwFprpRSVHlz"
+ };
+
+ var request = new QCloudCosService.RequestInfo
+ {
+ Method = "put",
+ Uri = "/exampleobject",
+ Parameters = new Dictionary<string, string>(),
+ Headers = new Dictionary<string, string>
+ {
+ ["Host"] = "examplebucket-1250000000.cos.ap-beijing.myqcloud.com",
+ ["x-cos-storage-class"] = "standard",
+ ["x-cos-content-sha1"] = "b502c3a1f48c8609ae212cdfb639dee39673f5e"
+ }
+ };
+
+ var signValidTime = new QCloudCosService.TimeDuration
+ {
+ Start = DateTimeOffset.FromUnixTimeSeconds(1417773892),
+ End = DateTimeOffset.FromUnixTimeSeconds(1417853898)
+ };
+
+ Assert.Equal("q-sign-algorithm=sha1&q-ak=AKIDQjz3ltompVjBni5LitkWHFlFpwkn9U5q&q-sign-time=1417773892;1417853898&q-key-time=1417773892;1417853898&q-header-list=host;x-cos-content-sha1;x-cos-storage-class&q-url-param-list=&q-signature=0ab12f43e74cbe148d705cd9fae8adc9a6d39cc1", QCloudCosService.GenerateSign(credential, request, signValidTime));
+ }
+
+/*
+// Tests in this part need secret configs in cos.
+#region SecretTests
+ [Fact]
+ public async Task ObjectExistsTest()
+ {
+ using (var serviceScope = _factory.Server.Host.Services.CreateScope())
+ {
+ var services = serviceScope.ServiceProvider;
+ var service = services.GetRequiredService<IQCloudCosService>();
+ Assert.True(await service.IsObjectExists("avatar", "__default"));
+ Assert.False(await service.IsObjectExists("avatar", "haha"));
+ Assert.False(await service.IsObjectExists("haha", "haha"));
+ }
+ }
+
+ [Fact]
+ public async Task GenerateObjectGetUrlTest()
+ {
+ using (var serviceScope = _factory.Server.Host.Services.CreateScope())
+ {
+ var services = serviceScope.ServiceProvider;
+ var service = services.GetRequiredService<IQCloudCosService>();
+ var url = service.GenerateObjectGetUrl("avatar", "__default");
+ // never use the following line! Because client created by factory can't access Internet.
+ //using (var client = _factory.CreateClient())
+ using (var client = services.GetRequiredService<IHttpClientFactory>().CreateClient())
+ {
+ var res = await client.GetAsync(url);
+ Assert.Equal(HttpStatusCode.OK, res.StatusCode);
+ }
+ }
+ }
+#endregion
+*/
+ }
+}
diff --git a/Timeline.Tests/Timeline.Tests.csproj b/Timeline.Tests/Timeline.Tests.csproj
index 57e04fc0..820737cc 100644
--- a/Timeline.Tests/Timeline.Tests.csproj
+++ b/Timeline.Tests/Timeline.Tests.csproj
@@ -8,7 +8,7 @@
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Testing" Version="2.2.0-rtm-35646" />
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<PrivateAssets>all</PrivateAssets>
diff --git a/Timeline.Tests/UserUnitTest.cs b/Timeline.Tests/UserUnitTest.cs
new file mode 100644
index 00000000..7d8cc824
--- /dev/null
+++ b/Timeline.Tests/UserUnitTest.cs
@@ -0,0 +1,36 @@
+using Microsoft.AspNetCore.Mvc.Testing;
+using Newtonsoft.Json;
+using System.Linq;
+using System.Net;
+using System.Threading.Tasks;
+using Timeline.Entities;
+using Timeline.Tests.Helpers;
+using Timeline.Tests.Helpers.Authentication;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Timeline.Tests
+{
+ public class UserUnitTest : IClassFixture<WebApplicationFactory<Startup>>
+ {
+ private readonly WebApplicationFactory<Startup> _factory;
+
+ public UserUnitTest(WebApplicationFactory<Startup> factory, ITestOutputHelper outputHelper)
+ {
+ _factory = factory.WithTestConfig(outputHelper);
+ }
+
+ [Fact]
+ public async Task UserTest()
+ {
+ using (var client = await _factory.CreateClientWithUser("admin", "admin"))
+ {
+ var res1 = await client.GetAsync("users");
+ Assert.Equal(HttpStatusCode.OK, res1.StatusCode);
+ var users = JsonConvert.DeserializeObject<UserInfo[]>(await res1.Content.ReadAsStringAsync()).ToList();
+ users.Sort(UserInfo.Comparer);
+ Assert.Equal(TestMockUsers.MockUserInfos, users, UserInfo.EqualityComparer);
+ }
+ }
+ }
+}