Merge branch 'dev'

This commit is contained in:
Argo Zhang 2019-10-09 22:47:11 +08:00
commit 1447d52072
No known key found for this signature in database
GPG Key ID: 152E398953DDF19F
20 changed files with 188 additions and 39 deletions

View File

@ -38,7 +38,7 @@
function runUnitTest() {
write-host "dotnet test test\UnitTest" -ForegroundColor Cyan
dotnet test test\UnitTest --filter "FullyQualifiedName!~MySql" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Include="[Bootstrap*]*" /p:ExcludeByFile="..\..\src\admin\Bootstrap.Admin\Program.cs%2c..\..\src\admin\Bootstrap.Admin\Startup.cs%2c..\..\src\admin\Bootstrap.Admin\HttpHeaderOperation.cs" /p:CoverletOutput=..\..\
dotnet test test\UnitTest --filter="FullyQualifiedName!~MySql" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Include="[Bootstrap.Admin*]*%2c[Bootstrap.DataAccess*]*" /p:Exclude="[*]*Program%2c[*]*Startup%2c[Bootstrap.DataAccess]*AutoDB%2c[Bootstrap.DataAccess]*WeChatHelper%2c[Bootstrap.DataAccess]*DbLogTask" /p:ExcludeByFile="**/SMSExtensions.cs%2c**/Helper/OAuthHelper.cs" /p:CoverletOutput=..\..\
}
function coverallUnitTest() {

View File

@ -24,7 +24,11 @@ services:
- mongodb
install:
- ps: >-
#copy my.ini into mysql folder
dotnet --version
#xcopy "$($env:appveyor_build_folder)\db\MySQL\my.ini" "C:\Program Files\MySQL\MySQL Server 5.7" /y
build_script:
- ps: >-
.\appveyor.build.ps1

View File

@ -1,7 +1,9 @@
[client]
[client]
default-character-set=utf8
[mysqld]
charcater_set_client=utf8
character_set_connection=utf8
character_set_results=utf8
character_set_results=utf8
character_set_server=utf8
character_set_database=utf8

View File

@ -16,7 +16,7 @@
<PackageReference Include="Longbow.Configuration" Version="2.2.7" />
<PackageReference Include="Longbow.Logging" Version="3.0.0" />
<PackageReference Include="Longbow.Tasks" Version="3.0.0-beta1" />
<PackageReference Include="Longbow.Web" Version="3.0.0-beta1" />
<PackageReference Include="Longbow.Web" Version="3.0.0-beta2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Sentry.AspNetCore" Version="2.0.0-beta4" />

View File

@ -52,11 +52,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="phone"></param>
/// <returns></returns>
[HttpPut]
public async Task<bool> Put([FromServices]ISMSProvider provider, [FromQuery]string phone)
{
if (string.IsNullOrEmpty(phone)) return false;
return await provider.SendCodeAsync(phone);
}
public async Task<bool> Put([FromServices]ISMSProvider provider, [FromQuery]string phone) => string.IsNullOrEmpty(phone) ? false : await provider.SendCodeAsync(phone);
/// <summary>
/// 跨域握手协议

View File

@ -17,8 +17,6 @@ namespace Bootstrap.Admin
/// <param name="context"></param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null) operation.Parameters = new List<OpenApiParameter>();
if (context.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Length == 0)
{
operation.Parameters.Add(new OpenApiParameter()

View File

@ -1,6 +1,5 @@
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -241,7 +240,7 @@ namespace Microsoft.Extensions.DependencyInjection
/// <summary>
/// 获得/设置 默认授权 App
/// </summary>
public string App { get; set; }
public string App { get; set; } = "0";
/// <summary>
/// 获得/设置 短信下发网关地址

View File

@ -16,7 +16,7 @@
<PackageReference Include="Longbow.PetaPoco" Version="1.0.2" />
<PackageReference Include="Longbow.Security.Cryptography" Version="1.3.0" />
<PackageReference Include="Longbow.Tasks" Version="2.2.24" />
<PackageReference Include="Longbow.Web" Version="3.0.0-beta1" />
<PackageReference Include="Longbow.Web" Version="3.0.0-beta2" />
<PackageReference Include="Longbow.WeChatAuth" Version="2.2.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="3.0.0" />
<PackageReference Include="PetaPoco.Extensions" Version="1.0.9" />

View File

@ -18,7 +18,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="connectionName"></param>
/// <param name="keepAlive"></param>
/// <param name="log">是否记录日志</param>
/// <param name="enableLog">是否记录日志</param>
/// <returns></returns>
public static IDatabase Create(string connectionName = null, bool keepAlive = false, bool enableLog = true)
{

View File

@ -81,7 +81,7 @@ namespace Bootstrap.DataAccess
while (_messageQueue.TryTake(out var log))
{
logs.Add(log);
};
}
if (logs.Any())
{
using (var db = DbManager.Create(enableLog: false))

View File

@ -74,7 +74,7 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 插入 Gitee 授权用户到数据库中
/// </summary>
/// <param name="userName"></param>
/// <param name="context"></param>
/// <returns></returns>
private static User ParseUser(OAuthCreatingTicketContext context)
{

View File

@ -4,6 +4,9 @@ using Longbow.WeChatAuth;
using Microsoft.AspNetCore.Authentication.OAuth;
using System;
using System.Linq;
#if NETCOREAPP3_0
using System.Text.Json;
#endif
namespace Bootstrap.DataAccess
{
@ -35,7 +38,7 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 插入 Gitee 授权用户到数据库中
/// </summary>
/// <param name="userName"></param>
/// <param name="context"></param>
/// <returns></returns>
private static User ParseUser(OAuthCreatingTicketContext context)
{
@ -53,7 +56,7 @@ namespace Bootstrap.DataAccess
}
#if NETCOREAPP3_0
private static T ToObject<T>(this System.Text.Json.JsonElement element) where T : WeChatUser
private static T ToObject<T>(this JsonElement element) where T : WeChatUser
{
var user = new WeChatUser();
var target = element.EnumerateObject();
@ -70,7 +73,7 @@ namespace Bootstrap.DataAccess
return user as T;
}
private static string TryGetValue(this System.Text.Json.JsonElement.ObjectEnumerator target, string propertyName)
private static string TryGetValue(this JsonElement.ObjectEnumerator target, string propertyName)
{
var ret = string.Empty;
var property = target.FirstOrDefault(t => t.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));

View File

@ -10,6 +10,8 @@ using System.Net;
using System.Net.Http;
using UnitTest;
using Xunit;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
namespace Bootstrap.Admin
{
@ -119,6 +121,39 @@ namespace Bootstrap.Admin
builder.ConfigureAppConfiguration(app => app.AddJsonFile(TestHelper.RetrievePath($"UnitTest{Path.DirectorySeparatorChar}appsettings.appveyor.json"), false, true));
}
TestHelper.ConfigureWebHost(builder);
// 替换 SMS 服务
builder.ConfigureServices(services =>
{
services.AddTransient<ISMSProvider, DefaultSMSProvider>();
});
}
/// <summary>
/// 手机号登陆帮助类
/// </summary>
class DefaultSMSProvider : ISMSProvider
{
/// <summary>
/// 获得 短信配置信息
/// </summary>
public SMSOptions Option { get; protected set; } = new SMSOptions();
/// <summary>
/// 下发验证码方法
/// </summary>
/// <param name="phoneNumber"></param>
/// <returns></returns>
public Task<bool> SendCodeAsync(string phoneNumber) => Task.FromResult(true);
/// <summary>
/// 验证验证码方法
/// </summary>
/// <param name="phone">手机号</param>
/// <param name="code">验证码</param>
/// <returns></returns>
public bool Validate(string phone, string code) => code == "1234";
}
}
}

View File

@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Xunit;
namespace Bootstrap.Admin.Api
{
public class HttpHeaderOperationTest
{
[Fact]
public void Apply_Ok()
{
var oper = new HttpHeaderOperation();
var api = new OpenApiOperation();
var desc = new ApiDescription();
var mi = typeof(HttpHeaderOperationTest).GetMethod("Apply_Ok");
var context = new OperationFilterContext(desc, null, null, mi);
oper.Apply(api, context);
}
}
}

View File

@ -39,10 +39,9 @@ namespace Bootstrap.Admin.Api.SqlServer
var _token = await resq.Content.ReadAsStringAsync();
Assert.Equal("false", _token);
// UNDONE: 重构短信登陆后完善
//resq = await Client.PutAsync("?phone=", new StringContent(""));
//_token = await resq.Content.ReadAsStringAsync();
//Assert.Equal("true", _token);
resq = await Client.PutAsync("?phone=18910001000", new StringContent(""));
_token = await resq.Content.ReadAsStringAsync();
Assert.Equal("true", _token);
}
[Fact]

View File

@ -1,10 +1,8 @@
using Bootstrap.DataAccess;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using Xunit;
namespace Bootstrap.Admin.Controllers.SqlServer
@ -123,22 +121,54 @@ namespace Bootstrap.Admin.Controllers.SqlServer
}
[Fact]
public void Mobile_Ok()
public async void Mobile_Ok()
{
// UNDONE: Mobile 单元测试未完成
using (var db = DbManager.Create()) db.Execute("delete from Users where UserName = @0", "18910001000");
var client = Host.CreateClient();
var r = await client.GetAsync("/Account/Login");
var view = await r.Content.ReadAsStringAsync();
var tokenTag = "<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"";
var index = view.IndexOf(tokenTag);
view = view.Substring(index + tokenTag.Length);
index = view.IndexOf("\" /></form>");
var antiToken = view.Substring(0, index);
// 反射设置 SMSHelper 内部验证码保证 Validate 方法返回真
var validateCodeInstance = Activator.CreateInstance(Type.GetType("Bootstrap.DataAccess.SMSHelper+AutoExpireValidateCode, Bootstrap.DataAccess"), new object[] { "18910001000", "1234", TimeSpan.FromSeconds(10)});
var _poolInstance = typeof(SMSHelper).GetField("_pool", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
//_pool.AddOrUpdate(option.Phone, key => new AutoExpireValidateCode(option.Phone, result.Data, option.Expires), (key, v) => v.Reset(result.Data));
//var addMethod = _poolInstance.GetType().GetMethod("AddOrUpdate");
//addMethod.Invoke(_poolInstance, new object[] { "18910001000", validateCodeInstance, null });
var content = new MultipartFormDataContent
{
{ new StringContent("18910001000"), "phone" },
{ new StringContent("1234"), "code" },
{ new StringContent(antiToken), "__RequestVerificationToken" }
};
var m = await client.PostAsync("/Account/Mobile", content);
Assert.True(m.IsSuccessStatusCode);
var payload = await r.Content.ReadAsStringAsync();
Assert.Contains("登 录", payload);
}
//var client = Host.CreateClient();
//var r = await client.GetAsync($"/Account/Mobile?phone=18910001000&code=1234");
//Assert.True(r.IsSuccessStatusCode);
//var content = await r.Content.ReadAsStringAsync();
//Assert.Contains("登 录", content);
[Fact]
public async void Mobile_Fail()
{
using (var db = DbManager.Create()) db.Execute("delete from Users where UserName = @0", "18910001000");
var client = Host.CreateClient();
var r = await client.GetAsync("/Account/Login");
var view = await r.Content.ReadAsStringAsync();
var tokenTag = "<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"";
var index = view.IndexOf(tokenTag);
view = view.Substring(index + tokenTag.Length);
index = view.IndexOf("\" /></form>");
var antiToken = view.Substring(0, index);
var content = new MultipartFormDataContent
{
{ new StringContent("18910001000"), "phone" },
{ new StringContent("1000"), "code" },
{ new StringContent(antiToken), "__RequestVerificationToken" }
};
var m = await client.PostAsync("/Account/Mobile?AppId=0", content);
Assert.True(m.IsSuccessStatusCode);
var payload = await r.Content.ReadAsStringAsync();
Assert.Contains("登 录", payload);
}
}
}

View File

@ -0,0 +1,14 @@
using Xunit;
namespace Bootstrap.DataAccess.MongoDB
{
[Collection("MongoContext")]
public class DBLogTest : SqlServer.DBLogTest
{
[Fact]
public override void Save_Ok()
{
Assert.True(new DBLog().Save(null));
}
}
}

View File

@ -0,0 +1,10 @@
using Xunit;
namespace Bootstrap.DataAccess.MySql
{
[Collection("MySqlContext")]
public class DBLogTest : SqlServer.DBLogTest
{
}
}

View File

@ -0,0 +1,28 @@
using System;
using Xunit;
namespace Bootstrap.DataAccess.SqlServer
{
[Collection("SQLServerContext")]
public class DBLogTest
{
[Fact]
public virtual void Save_Ok()
{
var log = new DBLog()
{
Id = "",
LogTime = DateTime.Now,
SQL = "UnitTest",
UserName = "UniTest"
};
Assert.True(log.Save(log));
}
[Fact]
public void Save_Exception()
{
Assert.Throws<ArgumentNullException>(() => new DBLog().Save(null));
}
}
}

View File

@ -0,0 +1,10 @@
using Xunit;
namespace Bootstrap.DataAccess.SQLite
{
[Collection("SQLiteContext")]
public class DBLogTest : SqlServer.DBLogTest
{
}
}