public static AntiForgeryRequestTokens GetFromApplication(TestApplication app) { var homeResponseTask = app.Server.CreateRequest("/").GetAsync(); homeResponseTask.ConfigureAwait(false); homeResponseTask.Wait(); var homeRes = homeResponseTask.Result; if (!homeRes.Headers.TryGetValues(HeaderNames.SetCookie, out var cookies)) { cookies = Enumerable.Empty <string>(); } var antiForgeryCookie = SetCookieHeaderValue.ParseList(cookies.ToList()).FirstOrDefault(cookie => cookie.Name.ToString().StartsWith(".AspNetCore.Antiforgery")); if (antiForgeryCookie == null) { throw new InvalidOperationException("无法从服务器获取 AntiForgery Cookie"); } var htmlContent = homeRes.ReadAllContent(); const string tokenStart = "window.__RequestVerificationToken"; var tokenHtmlContent = htmlContent.Substring(htmlContent.LastIndexOf(tokenStart)); var tokenPattern = new Regex(@"^window\.__RequestVerificationToken[^']+'(?<token>[^']+)';"); var token = tokenPattern.Match(tokenHtmlContent).Groups["token"].Value; var reqCookie = new Cookie(antiForgeryCookie.Name.ToString(), antiForgeryCookie.Value.ToString()); return(new AntiForgeryRequestTokens { VerificationToken = token, Cookie = reqCookie }); }
public static T CreateController <T>(this TestApplication app) where T : ControllerBase { var httpContext = app.GetService <IHttpContextFactory>().Create(new DefaultHttpContext().Features); httpContext.User = app.User; var routeData = new RouteData(); routeData.Routers.Add(new FakeRoute(app.GetService <IInlineConstraintResolver>())); var actionContext = new ActionContext( httpContext, routeData, new ControllerActionDescriptor { ControllerTypeInfo = typeof(T).GetTypeInfo() }); var actionContextAccessor = app.GetService <IActionContextAccessor>(); if (actionContextAccessor != null) { actionContextAccessor.ActionContext = actionContext; } return(app.GetService <IControllerFactory>().CreateController(new ControllerContext(actionContext)) as T); }
//public static AdminUser MockAdminUser(this TestApplication app) //{ // var adminUserRepo = app.GetService<IRepository<AdminUser>>(); // var adminUserService = app.GetService<IAdminUserService>(); // var adminUser = new AdminUser // { // CreatedAtUtc = DateTime.UtcNow.AddDays(-1), // Username = "******", // HashedPassword = adminUserService.HashPassword("11111A") // }; // adminUserRepo.Save(adminUser); // var token = adminUserService.IssueJwtToken(adminUser); // var options = app.GetService<IOptionsMonitor<JwtBearerOptions>>().Get("Bearer"); // var identity = options.SecurityTokenValidators // .First() // .ValidateToken(token.TokenString, options.TokenValidationParameters, out _); // app.User = identity; // return adminUser; //} public static ModelStateDictionary ValidateModel(this TestApplication app, object model) { var validator = app.GetService <IObjectModelValidator>(); var actionContext = new ActionContext(); validator.Validate(actionContext, null, string.Empty, model); return(actionContext.ModelState); }
public static TestApplication BuildTestApplication <TStartup>(TestApplication testApp, string environmentName = "Production", Action <IWebHostBuilder> configureHost = null) where TStartup : class { testApp.LoggerProvider = new StubLoggerProvider(); testApp.User = new ClaimsPrincipal(new ClaimsIdentity()); var hostBuilder = new WebHostBuilder(); configureHost?.Invoke(hostBuilder); hostBuilder.ConfigureServices(services => { services.AddTransient <HttpContextFactory>(); services.AddTransient <IHttpContextFactory>((sp) => { var defaultContextFactory = sp.GetService <HttpContextFactory>(); var httpContextFactory = new WrappedHttpContextFactory(defaultContextFactory); httpContextFactory.ConfigureFeatureWithContext((features, httpCtx) => { features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature { User = testApp.User }); features.Set <IServiceProvidersFeature>(new RequestServicesFeature(httpCtx, testApp.ApplicationServices.GetService <IServiceScopeFactory>())); }); return(httpContextFactory); }); }); Environment.SetEnvironmentVariable("SGConnectionString", "Data Source=.;Initial Catalog=siegrain.blog;Integrated Security=True"); WebHostConfiguration.Configure(hostBuilder); hostBuilder.ConfigureLogging(loggingBuilder => { loggingBuilder.SetMinimumLevel(LogLevel.Trace); loggingBuilder.AddProvider(testApp.LoggerProvider); }); hostBuilder .UseContentRoot(TestEnv.WebProjectPath()) .UseEnvironment(environmentName) .UseStartup <TStartup>(); testApp.Server = new TestServer(hostBuilder); testApp.ApplicationServices = testApp.Server.Host.Services; testApp._spOverrider = new ServiceProviderOverrider(testApp.ApplicationServices); return(testApp); }
public static RequestBuilder RequestAntiForgeryForm(this TestApplication app, string path, Dictionary <string, string> obj = null) { var tokens = app.GetAntiForgeryTokens(); var request = app.Server.CreateRequest(path); return(request.And(req => { if (obj == null) { obj = new Dictionary <string, string>(); } obj["__RequestVerificationToken"] = tokens.VerificationToken; req.Content = new FormUrlEncodedContent(obj); }) .WithCookie(tokens.Cookie)); }
//public async static Task<Users> MockUser(this TestApplication app) //{ // var controller = CreateController<UsersController>(app); // dynamic user = await controller.SignIn(new AuthUserParameter // { // LoginName = "admin", // Password = "******" // 123456 // }); // return user.Data.User; //} public static Users NoUser(this TestApplication app) { app.ResetUser(); return(null); }
public static T GetService <T>(this TestApplication app) where T : class { return(app.ApplicationServices.GetService <T>()); }
public static IEnumerable <StubLoggerProvider.LogItem> GetLogs(this TestApplication app) { var loggerProvider = app.ApplicationServices.GetRequiredService <ILoggerProvider>() as StubLoggerProvider; return(loggerProvider?.LogItems); }
public static TestHttpRequestBuilder Path(this TestApplication app, string path) { return(new TestHttpRequestBuilder(app, path)); }
public TestHttpRequestBuilder(TestApplication app, string path) { _app = app; _path = path; }