Test and misc cleanup

This commit is contained in:
Hao Kung 2015-05-05 14:35:10 -07:00
parent ab43154577
commit 288cb6c58f
16 changed files with 98 additions and 240 deletions

View File

@ -5,8 +5,6 @@ namespace Microsoft.AspNet.Identity
{
public class IdentityErrorDescriber
{
public static IdentityErrorDescriber Default = new IdentityErrorDescriber();
public virtual IdentityError DefaultError()
{
return new IdentityError

View File

@ -37,7 +37,7 @@ namespace Microsoft.AspNet.Identity
IEnumerable<IRoleValidator<TRole>> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILoggerFactory logger,
ILogger<RoleManager<TRole>> logger,
IHttpContextAccessor contextAccessor)
{
if (store == null)
@ -48,6 +48,7 @@ namespace Microsoft.AspNet.Identity
KeyNormalizer = keyNormalizer ?? new UpperInvariantLookupNormalizer();
ErrorDescriber = errors ?? new IdentityErrorDescriber();
_context = contextAccessor?.HttpContext;
Logger = logger;
if (roleValidators != null)
{
@ -56,8 +57,6 @@ namespace Microsoft.AspNet.Identity
RoleValidators.Add(v);
}
}
Logger = logger?.CreateLogger<RoleManager<TRole>>();
}
/// <summary>

View File

@ -26,7 +26,7 @@ namespace Microsoft.AspNet.Identity
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<TUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILoggerFactory logger)
ILogger<SignInManager<TUser>> logger)
{
if (userManager == null)
{
@ -45,7 +45,7 @@ namespace Microsoft.AspNet.Identity
Context = contextAccessor.HttpContext;
ClaimsFactory = claimsFactory;
Options = optionsAccessor?.Options ?? new IdentityOptions();
Logger = logger?.CreateLogger<SignInManager<TUser>>();
Logger = logger;
}
protected internal virtual ILogger Logger { get; set; }

View File

@ -52,7 +52,7 @@ namespace Microsoft.AspNet.Identity
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
IEnumerable<IUserTokenProvider<TUser>> tokenProviders,
ILoggerFactory logger,
ILogger<UserManager<TUser>> logger,
IHttpContextAccessor contextAccessor)
{
if (store == null)
@ -65,6 +65,7 @@ namespace Microsoft.AspNet.Identity
PasswordHasher = passwordHasher;
KeyNormalizer = keyNormalizer;
ErrorDescriber = errors;
Logger = logger;
if (userValidators != null)
{
@ -81,8 +82,6 @@ namespace Microsoft.AspNet.Identity
}
}
Logger = logger?.CreateLogger<UserManager<TUser>>();
if (tokenProviders != null)
{
foreach (var tokenProvider in tokenProviders)

View File

@ -6,7 +6,6 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test

View File

@ -41,16 +41,27 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
DropDb();
}
private IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddLogging();
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
return services.BuildServiceProvider();
}
private ApplicationBuilder CreateBuilder()
{
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
builder.ApplicationServices = ConfigureServices();
return builder;
}
[Fact]
public async Task EnsureStartupUsageWorks()
{
var context = CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var builder = CreateBuilder();
var userStore = builder.ApplicationServices.GetRequiredService<IUserStore<IdentityUser>>();
var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
@ -70,12 +81,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
{
// Arrange
CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var builder = CreateBuilder();
var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();
@ -102,12 +108,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
{
// Arrange
CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var builder = CreateBuilder();
var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();
@ -134,12 +135,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
{
// Arrange
CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var builder = CreateBuilder();
var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
var roleManager = builder.ApplicationServices.GetRequiredService<RoleManager<IdentityRole>>();
@ -180,12 +176,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
{
// Arrange
CreateContext(true);
var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
var services = new ServiceCollection();
DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
builder.ApplicationServices = services.BuildServiceProvider();
var builder = CreateBuilder();
var roleManager = builder.ApplicationServices.GetRequiredService<RoleManager<IdentityRole>>();
var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();

View File

@ -3,15 +3,12 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity.Test;
using Microsoft.AspNet.TestHost;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime.Infrastructure;
using Xunit;
using System.Linq.Expressions;
namespace Microsoft.AspNet.Identity.EntityFramework.Test
{
@ -108,73 +105,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
CreateContext();
}
// https://github.com/aspnet/Identity/issues/411
//[Fact]
//public async Task EnsureStartupUsageWorks()
//{
// EnsureDatabase();
// var server = TestServer.Create(
// app =>
// {
// app.UseIdentity<ApplicationUser, IdentityRole>();
// app.Run(async context =>
// {
// var userStore = builder.ApplicationServices.GetRequiredService<IUserStore<TUser>>();
// var userManager = builder.ApplicationServices.GetRequiredService<UserManager<TUser>>();
// Assert.NotNull(userStore);
// Assert.NotNull(userManager);
// const string password = "1qaz@WSX";
// var user = CreateTestUser();
// user.UserName = "admin1111";
// IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
// IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
// });
// },
// services =>
// {
// DbUtil.ConfigureDbServices<TestDbContext>(ConnectionString, services);
// services.AddIdentity<TUser, TRole>().AddEntityFrameworkStores<TestDbContext, TKey>();
// });
//}
//[Fact]
//public async Task EnsureStartupOptionsChangeWorks()
//{
// EnsureDatabase();
// var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
// builder.UseServices(services =>
// {
// DbUtil.ConfigureDbServices<TestDbContext>(ConnectionString, services);
// services.AddIdentity<TUser, TRole>(options =>
// {
// options.Password.RequiredLength = 1;
// options.Password.RequireLowercase = false;
// options.Password.RequireNonLetterOrDigit = false;
// options.Password.RequireUppercase = false;
// options.Password.RequireDigit = false;
// options.User.UserNameValidationRegex = null;
// }).AddEntityFrameworkStores<TestDbContext, TKey>();
// });
// var userStore = builder.ApplicationServices.GetRequiredService<IUserStore<TUser>>();
// var userManager = builder.ApplicationServices.GetRequiredService<UserManager<TUser>>();
// Assert.NotNull(userStore);
// Assert.NotNull(userManager);
// const string userName = "admin";
// const string password = "a";
// var user = CreateTestUser(userName);
// IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
// IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
//}
[Fact]
public void CanCreateUserUsingEF()
{

View File

@ -2,8 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq.Expressions;
using Microsoft.AspNet.Identity.Test;
using Microsoft.Framework.DependencyInjection;
using Xunit;

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq.Expressions;
using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq.Expressions;
using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test

View File

@ -5,13 +5,8 @@ using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity.Test;
using Microsoft.AspNet.TestHost;
using Microsoft.Data.Entity;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime.Infrastructure;
using Xunit;
namespace Microsoft.AspNet.Identity.EntityFramework.Test
@ -43,73 +38,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
db.Database.EnsureDeleted();
}
//https://github.com/aspnet/Identity/issues/411
//[Fact]
//public async Task EnsureStartupUsageWorks()
//{
// EnsureDatabase();
// var server = TestServer.Create(
// app =>
// {
// app.UseIdentity<ApplicationUser, IdentityRole>();
// app.Run(async context =>
// {
// var userStore = context.RequestServices.GetRequiredService<IUserStore<ApplicationUser>>();
// var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
// Assert.NotNull(userStore);
// Assert.NotNull(userManager);
// const string userName = "admin";
// const string password = "1qaz@WSX";
// var user = new ApplicationUser { UserName = userName };
// IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
// IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
// });
// },
// services =>
// {
// DbUtil.ConfigureDbServices<ApplicationDbContext>(ConnectionString, services);
// services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
// });
//}
//[Fact]
//public async Task EnsureStartupOptionsChangeWorks()
//{
// EnsureDatabase();
// var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
// builder.UseServices(services =>
// {
// services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// services.AddEntityFramework()
// .AddSqlServer()
// .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(ConnectionString));
// services.AddIdentity<ApplicationUser, IdentityRole>(options =>
// {
// options.Password.RequiredLength = 1;
// options.Password.RequireLowercase = false;
// options.Password.RequireNonLetterOrDigit = false;
// options.Password.RequireUppercase = false;
// options.Password.RequireDigit = false;
// }).AddEntityFrameworkStores<ApplicationDbContext>();
// });
// var userStore = builder.ApplicationServices.GetRequiredService<IUserStore<ApplicationUser>>();
// var userManager = builder.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>();
// Assert.NotNull(userStore);
// Assert.NotNull(userManager);
// const string userName = "admin";
// const string password = "a";
// var user = new ApplicationUser { UserName = userName };
// IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
// IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user));
//}
[Fact]
public void CanCreateUserUsingEF()
{
@ -302,7 +230,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
user1.UserName = Guid.NewGuid().ToString();
user2.UserName = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(user1));
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(user2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(user2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -326,7 +254,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
user.UserName = Guid.NewGuid().ToString();
user2.UserName = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(user));
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(user2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(user2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -351,7 +279,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
Assert.NotSame(user1, user2);
user1.UserName = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(user1));
IdentityResultAssert.IsFailure(await manager2.DeleteAsync(user2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.DeleteAsync(user2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -377,7 +305,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
role1.Name = Guid.NewGuid().ToString();
role2.Name = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(role1));
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(role2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(role2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -402,7 +330,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
role.Name = Guid.NewGuid().ToString();
role2.Name = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(role));
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(role2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.UpdateAsync(role2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -427,7 +355,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
Assert.NotSame(role1, role2);
role1.Name = Guid.NewGuid().ToString();
IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(role1));
IdentityResultAssert.IsFailure(await manager2.DeleteAsync(role2), IdentityErrorDescriber.Default.ConcurrencyFailure());
IdentityResultAssert.IsFailure(await manager2.DeleteAsync(role2), new IdentityErrorDescriber().ConcurrencyFailure());
}
}
@ -464,8 +392,5 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
protected override Expression<Func<IdentityUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
}
public class ApplicationUser : IdentityUser
{
}
public class ApplicationUser : IdentityUser { }
}

View File

@ -27,16 +27,32 @@ namespace Microsoft.AspNet.Identity.InMemory
{
const string TestPassword = "1qaz!QAZ";
[Fact]
public async Task CanChangePasswordOptions()
{
var clock = new TestClock();
var server = CreateServer(services => services.ConfigureIdentity(options =>
{
options.Password.RequireUppercase = false;
options.Password.RequireNonLetterOrDigit = false;
options.Password.RequireDigit = false;
}));
var transaction1 = await SendAsync(server, "http://example.com/createSimple");
transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
Assert.Null(transaction1.SetCookie);
}
[Fact]
public async Task CanCreateMeLoginAndCookieStopsWorkingAfterExpiration()
{
var clock = new TestClock();
var server = CreateServer(appCookieOptions =>
var server = CreateServer(services => services.ConfigureIdentityApplicationCookie(appCookieOptions =>
{
appCookieOptions.SystemClock = clock;
appCookieOptions.ExpireTimeSpan = TimeSpan.FromMinutes(10);
appCookieOptions.SlidingExpiration = false;
});
}));
var transaction1 = await SendAsync(server, "http://example.com/createMe");
transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
@ -70,10 +86,10 @@ namespace Microsoft.AspNet.Identity.InMemory
public async Task CanCreateMeLoginAndSecurityStampExtendsExpiration(bool rememberMe)
{
var clock = new TestClock();
var server = CreateServer(appCookieOptions =>
var server = CreateServer(services => services.ConfigureIdentityApplicationCookie(appCookieOptions =>
{
appCookieOptions.SystemClock = clock;
});
}));
var transaction1 = await SendAsync(server, "http://example.com/createMe");
transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
@ -116,7 +132,7 @@ namespace Microsoft.AspNet.Identity.InMemory
[Fact]
public async Task TwoFactorRememberCookieVerification()
{
var server = CreateServer(appCookieOptions => { });
var server = CreateServer();
var transaction1 = await SendAsync(server, "http://example.com/createMe");
transaction1.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
@ -135,7 +151,7 @@ namespace Microsoft.AspNet.Identity.InMemory
private static string FindClaimValue(Transaction transaction, string claimType)
{
XElement claim = transaction.ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
var claim = transaction.ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
if (claim == null)
{
return null;
@ -154,7 +170,7 @@ namespace Microsoft.AspNet.Identity.InMemory
return me;
}
private static TestServer CreateServer(Action<CookieAuthenticationOptions> configureAppCookie, Func<HttpContext, Task> testpath = null, Uri baseAddress = null)
private static TestServer CreateServer(Action<IServiceCollection> configureServices = null, Func<HttpContext, Task> testpath = null, Uri baseAddress = null)
{
var server = TestServer.Create(app =>
{
@ -175,6 +191,11 @@ namespace Microsoft.AspNet.Identity.InMemory
var result = await userManager.CreateAsync(new TestUser("hao"), TestPassword);
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/createSimple"))
{
var result = await userManager.CreateAsync(new TestUser("simple"), "aaaaaa");
res.StatusCode = result.Succeeded ? 200 : 500;
}
else if (req.Path == new PathString("/protected"))
{
res.StatusCode = 401;
@ -224,7 +245,10 @@ namespace Microsoft.AspNet.Identity.InMemory
services.AddIdentity<TestUser, TestRole>();
services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
services.ConfigureIdentityApplicationCookie(configureAppCookie);
if (configureServices != null)
{
configureServices(services);
}
});
server.BaseAddress = baseAddress;
return server;

View File

@ -36,7 +36,7 @@ namespace Microsoft.AspNet.Identity.Test
var result = await validator.ValidateAsync(manager, user);
// Assert
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.InvalidRoleName(input));
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidRoleName(input));
}
}
}

View File

@ -279,7 +279,7 @@ namespace Microsoft.AspNet.Identity.Test
var result = await userManager.AddToRolesAsync(user, roles);
// Assert
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.UserAlreadyInRole("B"));
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().UserAlreadyInRole("B"));
store.VerifyAll();
}
@ -341,7 +341,7 @@ namespace Microsoft.AspNet.Identity.Test
var result = await userManager.RemoveFromRolesAsync(user, roles);
// Assert
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.UserNotInRole("B"));
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().UserNotInRole("B"));
store.VerifyAll();
}

View File

@ -36,7 +36,7 @@ namespace Microsoft.AspNet.Identity.Test
var result = await validator.ValidateAsync(manager, user);
// Assert
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.InvalidUserName(input));
IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidUserName(input));
}
[Theory]

View File

@ -26,12 +26,8 @@ namespace Microsoft.AspNet.Identity.Test
where TRole : class
where TKey : IEquatable<TKey>
{
protected TestLoggerFactory loggerFactory;
public UserManagerTestBase()
{
loggerFactory = new TestLoggerFactory();
}
private readonly IdentityErrorDescriber _errorDescriber = new IdentityErrorDescriber();
protected TestLoggerFactory LoggerFactory { get; } = new TestLoggerFactory();
protected virtual void SetupIdentityServices(IServiceCollection services, object context = null)
{
@ -39,7 +35,8 @@ namespace Microsoft.AspNet.Identity.Test
services.AddIdentity<TUser, TRole>().AddDefaultTokenProviders();
AddUserStore(services, context);
AddRoleStore(services, context);
services.AddInstance<ILoggerFactory>(loggerFactory);
services.AddInstance<ILoggerFactory>(LoggerFactory);
services.AddLogging();
services.ConfigureIdentity(options =>
{
options.Password.RequireDigit = false;
@ -143,8 +140,8 @@ namespace Microsoft.AspNet.Identity.Test
var newUser = CreateTestUser(username, useNamePrefixAsUserName: true);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(newUser));
IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, ""), IdentityErrorDescriber.Default.InvalidUserName(""));
IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, newUsername), IdentityErrorDescriber.Default.DuplicateUserName(newUsername));
IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, ""), _errorDescriber.InvalidUserName(""));
IdentityResultAssert.IsFailure(await manager.SetUserNameAsync(newUser, newUsername), _errorDescriber.DuplicateUserName(newUsername));
}
[Fact]
@ -176,8 +173,8 @@ namespace Microsoft.AspNet.Identity.Test
var newUser = CreateTestUser(email: email);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(newUser));
IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, newEmail), IdentityErrorDescriber.Default.DuplicateEmail(newEmail));
IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, ""), IdentityErrorDescriber.Default.InvalidEmail(""));
IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, newEmail), _errorDescriber.DuplicateEmail(newEmail));
IdentityResultAssert.IsFailure(await manager.SetEmailAsync(newUser, ""), _errorDescriber.InvalidEmail(""));
}
[Fact]
@ -250,7 +247,7 @@ namespace Microsoft.AspNet.Identity.Test
var manager = CreateManager();
var user = CreateTestUser();
manager.Options.User.RequireUniqueEmail = true;
IdentityResultAssert.IsFailure(await manager.CreateAsync(user), IdentityErrorDescriber.Default.InvalidEmail(email));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user), _errorDescriber.InvalidEmail(email));
}
#if DNX451
@ -262,7 +259,7 @@ namespace Microsoft.AspNet.Identity.Test
var manager = CreateManager();
var user = CreateTestUser("UpdateBlocked", email);
manager.Options.User.RequireUniqueEmail = true;
IdentityResultAssert.IsFailure(await manager.CreateAsync(user), IdentityErrorDescriber.Default.InvalidEmail(email));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user), _errorDescriber.InvalidEmail(email));
}
#endif
@ -378,7 +375,7 @@ namespace Microsoft.AspNet.Identity.Test
Assert.True(await manager.HasPasswordAsync(user));
IdentityResultAssert.IsFailure(await manager.AddPasswordAsync(user, "password"),
"User already has a password set.");
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "AddPasswordAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.UserAlreadyHasPassword());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "AddPasswordAsync", await manager.GetUserIdAsync(user), _errorDescriber.UserAlreadyHasPassword());
}
[Fact]
@ -556,7 +553,7 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user, "password"));
var result = await manager.ChangePasswordAsync(user, "bogus", "newpassword");
IdentityResultAssert.IsFailure(result, "Incorrect password.");
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangePasswordAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.PasswordMismatch());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangePasswordAsync", await manager.GetUserIdAsync(user), _errorDescriber.PasswordMismatch());
}
[Fact]
@ -567,7 +564,7 @@ namespace Microsoft.AspNet.Identity.Test
var user = CreateTestUser(username, useNamePrefixAsUserName: true);
var user2 = CreateTestUser(username, useNamePrefixAsUserName: true);
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), IdentityErrorDescriber.Default.DuplicateUserName(username));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), _errorDescriber.DuplicateUserName(username));
}
[Fact]
@ -589,7 +586,7 @@ namespace Microsoft.AspNet.Identity.Test
var user = CreateTestUser(email: "FooUser@yup.com");
var user2 = CreateTestUser(email: "FooUser@yup.com");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), IdentityErrorDescriber.Default.DuplicateEmail("FooUser@yup.com"));
IdentityResultAssert.IsFailure(await manager.CreateAsync(user2), _errorDescriber.DuplicateEmail("FooUser@yup.com"));
}
[Fact]
@ -615,8 +612,8 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, login));
var result = await manager.AddLoginAsync(user, login);
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.LoginAlreadyAssociated());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "AddLoginAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.LoginAlreadyAssociated());
IdentityResultAssert.IsFailure(result, _errorDescriber.LoginAlreadyAssociated());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "AddLoginAsync", await manager.GetUserIdAsync(user), _errorDescriber.LoginAlreadyAssociated());
}
// Email tests
@ -744,7 +741,7 @@ namespace Microsoft.AspNet.Identity.Test
var stamp = await manager.GetSecurityStampAsync(user);
Assert.NotNull(stamp);
IdentityResultAssert.IsFailure(await manager.ResetPasswordAsync(user, "bogus", newPassword), "Invalid token.");
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ResetPasswordAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ResetPasswordAsync", await manager.GetUserIdAsync(user), _errorDescriber.InvalidToken());
Assert.True(await manager.CheckPasswordAsync(user, password));
Assert.Equal(stamp, await manager.GetSecurityStampAsync(user));
}
@ -767,7 +764,7 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.VerifyUserManagerSuccessLog(manager.Logger, "VerifyUserTokenAsync", userId);
Assert.False(await manager.VerifyUserTokenAsync(user, "Static", "test2", token));
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyUserTokenAsync", userId, IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyUserTokenAsync", userId, _errorDescriber.InvalidToken());
Assert.False(await manager.VerifyUserTokenAsync(user, "Static", "test", token + "a"));
Assert.False(await manager.VerifyUserTokenAsync(user2, "Static", "test", token));
@ -804,7 +801,7 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsFailure(await manager.ConfirmEmailAsync(user, "bogus"), "Invalid token.");
Assert.False(await manager.IsEmailConfirmedAsync(user));
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ConfirmEmailAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ConfirmEmailAsync", await manager.GetUserIdAsync(user), _errorDescriber.InvalidToken());
}
[Fact]
@ -1322,8 +1319,8 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user));
IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
var result = await userMgr.RemoveFromRoleAsync(user, roleName);
IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.UserNotInRole(roleName));
IdentityResultAssert.VerifyUserManagerFailureLog(userMgr.Logger, "RemoveFromRoleAsync", await userMgr.GetUserIdAsync(user), IdentityErrorDescriber.Default.UserNotInRole(roleName));
IdentityResultAssert.IsFailure(result, _errorDescriber.UserNotInRole(roleName));
IdentityResultAssert.VerifyUserManagerFailureLog(userMgr.Logger, "RemoveFromRoleAsync", await userMgr.GetUserIdAsync(user), _errorDescriber.UserNotInRole(roleName));
}
[Fact]
@ -1339,8 +1336,8 @@ namespace Microsoft.AspNet.Identity.Test
IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, roleName));
Assert.True(await userMgr.IsInRoleAsync(user, roleName));
IdentityResultAssert.IsFailure(await userMgr.AddToRoleAsync(user, roleName), IdentityErrorDescriber.Default.UserAlreadyInRole(roleName));
IdentityResultAssert.VerifyUserManagerFailureLog(userMgr.Logger, "AddToRoleAsync", await userMgr.GetUserIdAsync(user), IdentityErrorDescriber.Default.UserAlreadyInRole(roleName));
IdentityResultAssert.IsFailure(await userMgr.AddToRoleAsync(user, roleName), _errorDescriber.UserAlreadyInRole(roleName));
IdentityResultAssert.VerifyUserManagerFailureLog(userMgr.Logger, "AddToRoleAsync", await userMgr.GetUserIdAsync(user), _errorDescriber.UserAlreadyInRole(roleName));
}
[Fact]
@ -1402,7 +1399,7 @@ namespace Microsoft.AspNet.Identity.Test
var stamp = await manager.GetSecurityStampAsync(user);
IdentityResultAssert.IsFailure(await manager.ChangePhoneNumberAsync(user, "111-111-1111", "bogus"),
"Invalid token.");
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangePhoneNumberAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangePhoneNumberAsync", await manager.GetUserIdAsync(user), _errorDescriber.InvalidToken());
Assert.False(await manager.IsPhoneNumberConfirmedAsync(user));
Assert.Equal(await manager.GetPhoneNumberAsync(user), "123-456-7890");
Assert.Equal(stamp, await manager.GetSecurityStampAsync(user));
@ -1443,7 +1440,7 @@ namespace Microsoft.AspNet.Identity.Test
Assert.True(await manager.VerifyChangePhoneNumberTokenAsync(user, token2, num2));
Assert.False(await manager.VerifyChangePhoneNumberTokenAsync(user, token2, num1));
Assert.False(await manager.VerifyChangePhoneNumberTokenAsync(user, token1, num2));
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyChangePhoneNumberTokenAsync", userId, IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyChangePhoneNumberTokenAsync", userId, _errorDescriber.InvalidToken());
}
[Fact]
@ -1478,7 +1475,7 @@ namespace Microsoft.AspNet.Identity.Test
var stamp = await manager.GetSecurityStampAsync(user);
IdentityResultAssert.IsFailure(await manager.ChangeEmailAsync(user, "whatevah@foo.barf", "bogus"),
"Invalid token.");
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangeEmailAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "ChangeEmailAsync", await manager.GetUserIdAsync(user), _errorDescriber.InvalidToken());
Assert.False(await manager.IsEmailConfirmedAsync(user));
Assert.Equal(await manager.GetEmailAsync(user), oldEmail);
Assert.Equal(stamp, await manager.GetSecurityStampAsync(user));
@ -1628,7 +1625,7 @@ namespace Microsoft.AspNet.Identity.Test
var user = CreateTestUser(phoneNumber: "4251234567");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
Assert.False(await manager.VerifyTwoFactorTokenAsync(user, "Phone", "bogus"));
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyTwoFactorTokenAsync", await manager.GetUserIdAsync(user), IdentityErrorDescriber.Default.InvalidToken());
IdentityResultAssert.VerifyUserManagerFailureLog(manager.Logger, "VerifyTwoFactorTokenAsync", await manager.GetUserIdAsync(user), _errorDescriber.InvalidToken());
}
[Fact]