Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
KerlyJiang1 committed Sep 16, 2019
2 parents e81384f + bbc49f1 commit 4a8e820
Show file tree
Hide file tree
Showing 62 changed files with 1,993 additions and 1,619 deletions.
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
// <copyright file="AuthenticationServiceTests.cs" company="Shuai Zhang">
// Copyright Shuai Zhang. All rights reserved.
// Licensed under the GPLv3 license. See LICENSE file in the project root for full license information.
// </copyright>

using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
// <copyright file="AuthenticationServiceTests.cs" company="Shuai Zhang">
// Copyright Shuai Zhang. All rights reserved.
// Licensed under the GPLv3 license. See LICENSE file in the project root for full license information.
// </copyright>

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using GeothermalResearchInstitute.ServerConsole.GrpcService;
using GeothermalResearchInstitute.ServerConsole.Model;
using GeothermalResearchInstitute.v1;
using Grpc.Core;
using Grpc.Core.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.MSTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GeothermalResearchInstitute.ServerConsole.UnitTest
{
[TestClass]
public class AuthenticationServiceTests
{
private IHost Host { get; set; }
private static IHost Host { get; set; }

[ClassInitialize]
public void Init()
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Required by MSTest Framework.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"样式", "IDE0060:删除未使用的参数", Justification = "Required by MSTest Framework.")]
public static void Init(TestContext testContext)
{
this.Host = new HostBuilder()
Host = new HostBuilder()
.ConfigureHostConfiguration(builder =>
{
builder.AddInMemoryCollection(new Dictionary<string, string>
Expand All @@ -28,25 +43,183 @@ public void Init()
})
.ConfigureAppConfiguration(builder =>
{

builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "credentials:0:nickname", "测试用户0" },
{ "credentials:0:username", "user0_username" },
{ "credentials:0:password", "user0_password" },
{ "credentials:0:role", "User" },
{ "credentials:1:nickname", "测试用户1" },
{ "credentials:1:username", "user1_username" },
{ "credentials:1:password", "user1_password" },
{ "credentials:1:role", "Administrator" },
});
})
.ConfigureLogging(builder =>
.ConfigureLogging((context, builder) =>
{
builder.AddProvider(new MsTestLoggerProvider());
})
.ConfigureServices((context, builder) =>
{
IConfiguration config = context.Configuration;

// Configuration options.
builder.Configure<AuthenticationOptions>(context.Configuration);

// Grpc services.
builder.AddSingleton(serviceProvider =>
{
return new GrpcLoggerAdapater.GrpcLoggerAdapter(
serviceProvider.GetRequiredService<ILoggerFactory>(),
serviceProvider.GetRequiredService<ILogger<Server>>());
});
builder.AddTransient<AuthenticationServiceImpl>();
builder.AddSingleton(serviceProvider =>
{
GrpcEnvironment.SetLogger(serviceProvider.GetRequiredService<GrpcLoggerAdapater.GrpcLoggerAdapter>());
return new Server
{
Services =
{
AuthenticationService.BindService(serviceProvider.GetRequiredService<AuthenticationServiceImpl>()),
},
Ports =
{
new ServerPort(
"0.0.0.0",
config.GetValue<int>("core.port"),
ServerCredentials.Insecure),
},
};
});

builder.AddHostedService<GrpcHostedService>();
})
.Build();
}

[ClassCleanup]
public void Cleanup()
public static void Cleanup()
{
Host.Dispose();
Host = null;
}

[TestMethod]
public async Task LoginUser0Success()
{
this.Host.StopAsync().GetAwaiter().GetResult();
this.Host.Dispose();
this.Host = null;
var service = Host.Services.GetRequiredService<AuthenticationServiceImpl>();
var fakeServerCallContext = TestServerCallContext.Create(
nameof(service.Authenticate),
null,
DateTime.UtcNow.AddHours(1),
new Metadata(),
CancellationToken.None,
"127.0.0.1",
null,
null,
(metadata) => Task.CompletedTask,
() => new WriteOptions(),
(writeOptions) => { });

var response = await service.Authenticate(
new AuthenticateRequest
{
Username = "user0_username",
Password = "user0_password",
},
fakeServerCallContext).ConfigureAwait(false);
Assert.AreEqual(
new AuthenticateResponse
{
Nickname = "测试用户0",
Role = UserRole.User,
},
response);
}

[TestMethod]
public async Task LoginUser1Success()
{
var service = Host.Services.GetRequiredService<AuthenticationServiceImpl>();
var fakeServerCallContext = TestServerCallContext.Create(
nameof(service.Authenticate),
null,
DateTime.UtcNow.AddHours(1),
new Metadata(),
CancellationToken.None,
"127.0.0.1",
null,
null,
(metadata) => Task.CompletedTask,
() => new WriteOptions(),
(writeOptions) => { });

var response = await service.Authenticate(
new AuthenticateRequest
{
Username = "user1_username",
Password = "user1_password",
},
fakeServerCallContext).ConfigureAwait(false);
Assert.AreEqual(
new AuthenticateResponse
{
Nickname = "测试用户1",
Role = UserRole.Administrator,
},
response);
}

[TestMethod]
public void TestMethod1()
public async Task LoginUser1Failed()
{
var service = Host.Services.GetRequiredService<AuthenticationServiceImpl>();
var fakeServerCallContext = TestServerCallContext.Create(
nameof(service.Authenticate),
null,
DateTime.UtcNow.AddHours(1),
new Metadata(),
CancellationToken.None,
"127.0.0.1",
null,
null,
(metadata) => Task.CompletedTask,
() => new WriteOptions(),
(writeOptions) => { });

var rpcException = await Assert.ThrowsExceptionAsync<RpcException>(() => service.Authenticate(
new AuthenticateRequest
{
Username = "user1_username",
},
fakeServerCallContext)).ConfigureAwait(false);
Assert.AreEqual(StatusCode.Unauthenticated, rpcException.StatusCode);
}

[TestMethod]
public async Task LoginFailed()
{
var service = Host.Services.GetRequiredService<AuthenticationServiceImpl>();
var fakeServerCallContext = TestServerCallContext.Create(
nameof(service.Authenticate),
null,
DateTime.UtcNow.AddHours(1),
new Metadata(),
CancellationToken.None,
"127.0.0.1",
null,
null,
(metadata) => Task.CompletedTask,
() => new WriteOptions(),
(writeOptions) => { });

var rpcException = await Assert.ThrowsExceptionAsync<RpcException>(() => service.Authenticate(
new AuthenticateRequest
{
},
fakeServerCallContext)).ConfigureAwait(false);
Assert.AreEqual(StatusCode.Unauthenticated, rpcException.StatusCode);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(NetcoreCurrentTargetFramework)</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\GeothermalResearchInstitute.ServerConsole\GeothermalResearchInstitute.ServerConsole.csproj" />
</ItemGroup>

</Project>
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(NetcoreCurrentTargetFramework)</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Grpc.Core.Testing" Version="2.23.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\MicrosoftExtensions\Logging\MSTest\MicrosoftExtensions.Logging.MSTest\MicrosoftExtensions.Logging.MSTest.csproj" />
<ProjectReference Include="..\GeothermalResearchInstitute.ServerConsole\GeothermalResearchInstitute.ServerConsole.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@
<None Update="appsettings.Development.ini">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="bjdire.sqlite">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<None Update="bjdire.sqlite">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace GeothermalResearchInstitute.ServerConsole
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Performance", "CA1812", Justification = "Instantiated with reflection.")]
internal class GrpcHostedService : IHostedService
public class GrpcHostedService : IHostedService
{
private readonly ILogger<GrpcHostedService> logger;
private readonly Server server;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ namespace GeothermalResearchInstitute.ServerConsole.GrpcService
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Performance", "CA1812", Justification = "Instantiated with reflection.")]
internal class AuthenticationServiceImpl
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Design", "CA1062:验证公共方法的参数", Justification = "由Grpc框架保证.")]
public class AuthenticationServiceImpl
: AuthenticationService.AuthenticationServiceBase
{
private readonly ILogger<AuthenticationServiceImpl> logger;
Expand All @@ -27,8 +29,8 @@ public AuthenticationServiceImpl(
ILogger<AuthenticationServiceImpl> logger,
IServiceProvider serviceProvider)
{
this.logger = logger;
this.serviceProvider = serviceProvider;
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));

if (this.logger.IsEnabled(LogLevel.Debug))
{
Expand All @@ -44,7 +46,9 @@ public override Task<AuthenticateResponse> Authenticate(
AuthenticateRequest request, ServerCallContext context)
{
var authenticationOptions = this.serviceProvider.GetRequiredService<IOptionsSnapshot<AuthenticationOptions>>();
var credential = authenticationOptions.Value.Credentials.SingleOrDefault(c => c.Username == request.Username && c.Password == request.Password);
var credential = authenticationOptions.Value.Credentials.SingleOrDefault(
c => string.Equals(c.Username, request.Username, StringComparison.Ordinal) &&
string.Equals(c.Password, request.Password, StringComparison.Ordinal));
if (credential == null)
{
throw new RpcException(new Status(StatusCode.Unauthenticated, "Invalid username or password."));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ namespace GeothermalResearchInstitute.ServerConsole.GrpcService
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Performance", "CA1812", Justification = "Instantiated with reflection.")]
internal class DeviceServiceImpl : DeviceService.DeviceServiceBase
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Design", "CA1062:验证公共方法的参数", Justification = "由Grpc框架保证.")]
public class DeviceServiceImpl : DeviceService.DeviceServiceBase
{
private readonly ILogger<DeviceServiceImpl> logger;
private readonly BjdireContext bjdireContext;
Expand All @@ -33,9 +35,9 @@ public DeviceServiceImpl(
BjdireContext bjdireContext,
IServiceProvider serviceProvider)
{
this.logger = logger;
this.bjdireContext = bjdireContext;
this.serviceProvider = serviceProvider;
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.bjdireContext = bjdireContext ?? throw new ArgumentNullException(nameof(bjdireContext));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.metricsMap = new ConcurrentDictionary<ByteString, DeviceMetrics>();

if (this.logger.IsEnabled(LogLevel.Debug))
Expand Down
Loading

0 comments on commit 4a8e820

Please sign in to comment.