public void Create_CreatesInstancesOfTypes(Type type)
        {
            // Arrange
            var activator = new DefaultControllerActivator(new TypeActivatorCache());
            var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);

            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider.Object
            };

            var context = new ControllerContext(
                new ActionContext(
                    httpContext,
                    new RouteData(),
                    new ControllerActionDescriptor
                    {
                        ControllerTypeInfo = type.GetTypeInfo()
                    }));

            // Act
            var instance = activator.Create(context);

            // Assert
            Assert.IsType(type, instance);
        }
        public void Create_TypeActivatesTypesWithServices()
        {
            // Arrange
            var activator = new DefaultControllerActivator(new TypeActivatorCache());
            var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);
            var testService = new TestService();
            serviceProvider.Setup(s => s.GetService(typeof(TestService)))
                           .Returns(testService)
                           .Verifiable();

            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider.Object
            };

            var context = new ControllerContext(
                new ActionContext(
                    httpContext,
                    new RouteData(),
                    new ControllerActionDescriptor
                    {
                        ControllerTypeInfo = typeof(TypeDerivingFromControllerWithServices).GetTypeInfo()
                    }));

            // Act
            var instance = activator.Create(context);

            // Assert
            var controller = Assert.IsType<TypeDerivingFromControllerWithServices>(instance);
            Assert.Same(testService, controller.TestService);
            serviceProvider.Verify();
        }
        public void Create_ThrowsIfControllerIsNotRegisteredInServiceProvider()
        {
            // Arrange
            var expected = "No service for type '" + typeof(DIController) + "' has been registered.";
            var controller = new DIController();

            var httpContext = new DefaultHttpContext
            {
                RequestServices = Mock.Of<IServiceProvider>()
            };

            var activator = new ServiceBasedControllerActivator();
            var context = new ControllerContext(
                new ActionContext(
                httpContext,
                new RouteData(),
                new ControllerActionDescriptor
                {
                    ControllerTypeInfo = typeof(DIController).GetTypeInfo()
                }));

            // Act and Assert
            var ex = Assert.Throws<InvalidOperationException>(
                () => activator.Create(context));

            Assert.Equal(expected, ex.Message);
        }
        public async Task InvalidModelStateResult_WritesHttpError()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = CreateServices();

            var stream = new MemoryStream();
            httpContext.Response.Body = stream;

            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var modelState = new ModelStateDictionary();
            modelState.AddModelError("product.Name", "Name is required.");

            var expected =
                "{\"Message\":\"The request is invalid.\"," +
                "\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";

            var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content);
            }
        }
        public void CreateResponse_DoingConneg_OnlyContent_RetrievesContentNegotiatorFromServices()
        {
            // Arrange
            var context = new DefaultHttpContext();

            var services = new Mock<IServiceProvider>();
            services
                .Setup(s => s.GetService(typeof(IContentNegotiator)))
                .Returns(Mock.Of<IContentNegotiator>())
                .Verifiable();

            var options = new WebApiCompatShimOptions();
            options.Formatters.AddRange(new MediaTypeFormatterCollection());

            var optionsAccessor = new Mock<IOptions<WebApiCompatShimOptions>>();
            optionsAccessor.SetupGet(o => o.Value).Returns(options);

            services
                .Setup(s => s.GetService(typeof(IOptions<WebApiCompatShimOptions>)))
                .Returns(optionsAccessor.Object);

            context.RequestServices = services.Object;

            var request = CreateRequest(context);

            // Act
            request.CreateResponse(CreateValue());

            // Assert
            services.Verify();
        }
        public void SelectResponseCharacterEncoding_SelectsEncoding(
            string acceptCharsetHeaders,
            string[] supportedEncodings,
            string expectedEncoding)
        {
            // Arrange
            var httpContext = new Mock<HttpContext>();
            var httpRequest = new DefaultHttpContext().Request;
            httpRequest.Headers[HeaderNames.AcceptCharset] = acceptCharsetHeaders;
            httpRequest.Headers[HeaderNames.Accept] = "application/acceptCharset";
            httpContext.SetupGet(o => o.Request).Returns(httpRequest);

            var formatter = new TestOutputFormatter();
            foreach (string supportedEncoding in supportedEncodings)
            {
                formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding));
            }

            var context = new OutputFormatterWriteContext(
                httpContext.Object,
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                typeof(string),
                "someValue")
            {
                ContentType = new StringSegment(httpRequest.Headers[HeaderNames.Accept]),
            };

            // Act
            var actualEncoding = formatter.SelectCharacterEncoding(context);

            // Assert
            Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding);
        }
Example #7
0
        public void CopyConstructor_CopiesExpectedProperties()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalContext = new ViewContext(
                new ActionContext(httpContext, new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider()),
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var view = Mock.Of<IView>();
            var viewData = new ViewDataDictionary(originalContext.ViewData);
            var writer = new StringWriter();

            // Act
            var context = new ViewContext(originalContext, view, viewData, writer);

            // Assert
            Assert.Same(originalContext.ActionDescriptor, context.ActionDescriptor);
            Assert.Equal(originalContext.ClientValidationEnabled, context.ClientValidationEnabled);
            Assert.Same(originalContext.ExecutingFilePath, context.ExecutingFilePath);
            Assert.Same(originalContext.FormContext, context.FormContext);
            Assert.Equal(originalContext.Html5DateRenderingMode, context.Html5DateRenderingMode);
            Assert.Same(originalContext.HttpContext, context.HttpContext);
            Assert.Same(originalContext.ModelState, context.ModelState);
            Assert.Same(originalContext.RouteData, context.RouteData);
            Assert.Same(originalContext.TempData, context.TempData);
            Assert.Same(originalContext.ValidationMessageElement, context.ValidationMessageElement);
            Assert.Same(originalContext.ValidationSummaryMessageElement, context.ValidationSummaryMessageElement);

            Assert.Same(view, context.View);
            Assert.Same(viewData, context.ViewData);
            Assert.Same(writer, context.Writer);
        }
        public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddSingleton<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddSingleton<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddSingleton<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
Example #9
0
        public async void Invoke_LogsCorrectValues_WhenNotHandled()
        {
            // Arrange
            var expectedMessage = "Request did not match any routes.";
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Example #10
0
        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var context = new ViewContext(
                new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: originalViewData,
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
        public void GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
        {
            // Arrange
            var cookieToken = new AntiforgeryToken()
            {
                IsCookieToken = true
            };

            var httpContext = new DefaultHttpContext();
            httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername());

            var options = new AntiforgeryOptions();
            var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;

            var tokenProvider = new DefaultAntiforgeryTokenGenerator(
                claimUidExtractor: claimUidExtractor,
                additionalDataProvider: null);

            // Act & assert
            var exception = Assert.Throws<InvalidOperationException>(
                    () => tokenProvider.GenerateRequestToken(httpContext, cookieToken));
            Assert.Equal(
                "The provided identity of type " +
                $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " +
                "is marked IsAuthenticated = true but does not have a value for Name. " +
                "By default, the antiforgery system requires that all authenticated identities have a unique Name. " +
                "If it is not possible to provide a unique Name for this identity, " +
                "consider extending IAntiforgeryAdditionalDataProvider by overriding the " +
                "DefaultAntiforgeryAdditionalDataProvider " +
                "or a custom type that can provide some form of unique identifier for the current user.",
                exception.Message);
        }
Example #12
0
        public async void Invoke_DoesNotLog_WhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = new ServiceProvider();

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Empty(sink.Writes);
        }
        public void OnActionExecuted_HandlesExceptionAndReturnsObjectResult()
        {
            // Arrange
            var filter = new HttpResponseExceptionActionFilter();
            var httpContext = new DefaultHttpContext();
            httpContext.Request.Method = "GET";

            var actionContext = new ActionContext(
                                httpContext,
                                new RouteData(),
                                Mock.Of<ActionDescriptor>());

            var context = new ActionExecutedContext(
                actionContext,
                filters: new List<IFilterMetadata>(),
                controller: new object());

            context.Exception = new HttpResponseException(HttpStatusCode.BadRequest);

            // Act
            filter.OnActionExecuted(context);

            // Assert
            Assert.True(context.ExceptionHandled);
            var result = Assert.IsType<ObjectResult>(context.Result);
            Assert.Equal(typeof(HttpResponseMessage), result.DeclaredType);
            var response = Assert.IsType<HttpResponseMessage>(result.Value);
            Assert.NotNull(response.RequestMessage);
            Assert.Equal(context.HttpContext.GetHttpRequestMessage(), response.RequestMessage);
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public void Create_GetsServicesFromServiceProvider()
        {
            // Arrange
            var controller = new DIController();
            var serviceProvider = new Mock<IServiceProvider>(MockBehavior.Strict);
            serviceProvider.Setup(s => s.GetService(typeof(DIController)))
                           .Returns(controller)
                           .Verifiable();
            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider.Object
            };
            var activator = new ServiceBasedControllerActivator();
            var context = new ControllerContext(new ActionContext(
                httpContext,
                new RouteData(),
                new ControllerActionDescriptor
                {
                    ControllerTypeInfo = typeof(DIController).GetTypeInfo()
                }));

            // Act
            var instance = activator.Create(context);

            // Assert
            Assert.Same(controller, instance);
            serviceProvider.Verify();
        }
        private static ViewComponentContext GetViewComponentContext(IView view, Stream stream)
        {
            var httpContext = new DefaultHttpContext();
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext = new ViewContext(
                actionContext,
                view,
                viewData,
                new TempDataDictionary(httpContext, new SessionStateTempDataProvider()),
                TextWriter.Null,
                new HtmlHelperOptions());

            var writer = new StreamWriter(stream) { AutoFlush = true };

            var viewComponentDescriptor = new ViewComponentDescriptor()
            {
                TypeInfo = typeof(object).GetTypeInfo(),
            };

            var viewComponentContext = new ViewComponentContext(
                viewComponentDescriptor,
                new Dictionary<string, object>(),
                new HtmlTestEncoder(),
                viewContext,
                writer);

            return viewComponentContext;
        }
Example #16
0
    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
 private static HttpContext GetHttpContext()
 {
     var httpContext = new DefaultHttpContext();
     httpContext.Request.PathBase = new PathString("");
     httpContext.Response.Body = new MemoryStream();
     httpContext.RequestServices = CreateServices();
     return httpContext;
 }
        public async void EmptyContext()
        {
            var context = new DefaultHttpContext();

            var secret = await _parser.ParseAsync(context);

            secret.Should().BeNull();
        }
        public void WithHttpContextShouldPopulateCustomHttpContextForPocoController()
        {
            MyApplication
                .StartsFrom<TestStartup>()
                .WithServices(services =>
                {
                    services.AddMemoryCache();
                    services.AddDistributedMemoryCache();
                    services.AddSession();
                    services.AddHttpContextAccessor();
                });

            var httpContext = new DefaultHttpContext();
            httpContext.Request.Scheme = "Custom";
            httpContext.Response.StatusCode = 404;
            httpContext.Response.ContentType = ContentType.ApplicationJson;
            httpContext.Response.ContentLength = 100;

            MyController<MvcController>
                .Instance()
                .WithHttpContext(httpContext)
                .ShouldPassForThe<HttpContext>(setHttpContext =>
                {
                    Assert.Equal("Custom", setHttpContext.Request.Scheme);
                    Assert.IsAssignableFrom<HttpResponseMock>(setHttpContext.Response);
                    Assert.Same(httpContext.Response.Body, setHttpContext.Response.Body);
                    Assert.Equal(httpContext.Response.ContentLength, setHttpContext.Response.ContentLength);
                    Assert.Equal(httpContext.Response.ContentType, setHttpContext.Response.ContentType);
                    Assert.Equal(httpContext.Response.StatusCode, setHttpContext.Response.StatusCode);
                    Assert.Same(httpContext.Items, setHttpContext.Items);
                    Assert.Same(httpContext.Features, setHttpContext.Features);
                    Assert.Same(httpContext.RequestServices, setHttpContext.RequestServices);
                    Assert.Same(httpContext.Session, setHttpContext.Session);
                    Assert.Same(httpContext.TraceIdentifier, setHttpContext.TraceIdentifier);
                    Assert.Same(httpContext.User, setHttpContext.User);
                });

            MyController<PocoController>
                .Instance()
                .WithHttpContext(httpContext)
                .ShouldPassForThe<PocoController>(controller =>
                {
                    Assert.Equal("Custom", controller.CustomHttpContext.Request.Scheme);
                    Assert.IsAssignableFrom<HttpResponseMock>(controller.CustomHttpContext.Response);
                    Assert.Same(httpContext.Response.Body, controller.CustomHttpContext.Response.Body);
                    Assert.Equal(httpContext.Response.ContentLength, controller.CustomHttpContext.Response.ContentLength);
                    Assert.Equal(httpContext.Response.ContentType, controller.CustomHttpContext.Response.ContentType);
                    Assert.Equal(httpContext.Response.StatusCode, controller.CustomHttpContext.Response.StatusCode);
                    Assert.Same(httpContext.Items, controller.CustomHttpContext.Items);
                    Assert.Same(httpContext.Features, controller.CustomHttpContext.Features);
                    Assert.Same(httpContext.RequestServices, controller.CustomHttpContext.RequestServices);
                    Assert.Same(httpContext.Session, controller.CustomHttpContext.Session);
                    Assert.Same(httpContext.TraceIdentifier, controller.CustomHttpContext.TraceIdentifier);
                    Assert.Same(httpContext.User, controller.CustomHttpContext.User);
                });

            MyApplication.StartsFrom<DefaultStartup>();
        }
        public async void EmptyOwinEnvironment()
        {
            var context = new DefaultHttpContext();
            context.Request.Body = new MemoryStream();

            var secret = await _parser.ParseAsync(context);

            secret.Should().BeNull();
        }
Example #21
0
        private static HttpContext GetHttpContext()
        {
            var services = CreateServices();

            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = services.BuildServiceProvider();

            return httpContext;
        }
        public void Can_get_tenant_instance()
        {
            HttpContext httpContext = new DefaultHttpContext();

            var tenant = new TestTenant { Id = "1" };
            httpContext.SetTenantContext(new TenantContext<TestTenant>(tenant));

            Assert.Same(tenant, httpContext.GetTenant<TestTenant>());
        }
        public void Can_get_and_set_tenant_context()
        {
            HttpContext httpContext = new DefaultHttpContext();

            var tenantContext = new TenantContext<TestTenant>(new TestTenant());
            httpContext.SetTenantContext(tenantContext);

            Assert.Same(tenantContext, httpContext.GetTenantContext<TestTenant>());
        }
        public async Task No_Header_no_Body_Post()
        {
            var ctx = new DefaultHttpContext();
            ctx.Request.Method = "POST";

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
Example #25
0
        public void AppendLargeCookie_Appended()
        {
            HttpContext context = new DefaultHttpContext();

            string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            new ChunkingCookieManager() { ChunkSize = null }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
            var values = context.Response.Headers["Set-Cookie"];
            Assert.Equal(1, values.Count);
            Assert.Equal("TestCookie=" + testString + "; path=/", values[0]);
        }
        public async void BasicAuthentication_Request_With_Empty_Basic_Header()
        {
            var context = new DefaultHttpContext();

            context.Request.Headers.Add("Authorization", new StringValues(""));
                
            var secret = await _parser.ParseAsync(context);

            secret.Should().BeNull();
        }
        public async Task TestSdkVersionIsPopulatedByMiddleware()
        {
            var context = new DefaultHttpContext();
            context.Request.Scheme = HttpRequestScheme;
            context.Request.Host = this.httpRequestHost;

            await middleware.Invoke(context, new RequestTelemetry());

            Assert.NotEmpty(this.sentTelemetry.Context.GetInternalContext().SdkVersion);
            Assert.Contains(SdkVersionTestUtils.VersionPrefix, this.sentTelemetry.Context.GetInternalContext().SdkVersion);
        }
        public async Task Whitespaces_Bearer_Scheme_Header()
        {
            var ctx = new DefaultHttpContext();
            ctx.Request.Method = "GET";
            ctx.Request.Headers.Add("Authorization", new string[] { "Bearer           " });

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeFalse();
        }
        public void WithHttpContextSessionShouldThrowExceptionIfSessionIsNotRegistered()
        {
            var httpContext = new DefaultHttpContext();

            MyViewComponent<NormalComponent>
                .Instance()
                .WithHttpContext(httpContext)
                .ShouldPassForThe<HttpContext>(context =>
                {
                    Assert.Throws<InvalidOperationException>(() => context.Session);
                });
        }
        public void ApiKeyHandler_AuthenticatedEvent()
        {
            var context = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            var handler = CreateHandler(context);

            handler.Options.Events.OnAuthenticatedAsync = (ctx) =>
            {
                ctx.Identity.AddClaim(new System.Security.Claims.Claim("Foo", "Bar"));

                return(System.Threading.Tasks.Task.CompletedTask);
            };

            context.Request.Headers.Add("Authorization", "ApiKey TestName:TestKey");

            var authResult = handler.AuthenticateAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            Assert.IsTrue(authResult.Principal.HasClaim(x => x.Type == "Foo"));
        }
        public void ApiKeyHandler_OnRequestEvent()
        {
            var context = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            var handler = CreateHandler(context);

            handler.Options.Events.OnRequestAsync = (ctx) =>
            {
                ctx.AuthenticationType = "ApiKey";
                ctx.ClientID           = "TestName";
                ctx.Token = "TestKey";

                return(System.Threading.Tasks.Task.CompletedTask);
            };

            var authResult = handler.AuthenticateAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            Assert.AreEqual(true, authResult.Succeeded);
            Assert.AreEqual(true, authResult.Principal.Identity.IsAuthenticated);
            Assert.AreEqual("TestName", authResult.Principal.Identity.Name);
        }
Example #32
0
        public void ApiKeyHandler_HandleRequestWithCustomTokenProvider()
        {
            var context = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            var handler = CreateHandler(context);

            handler.Options.Events.OnRequestAsync = async(ctx) =>
            {
                ctx.Key = new ApiKey()
                {
                    ClientID = "TestName",
                    Secret   = "TestKey"
                };
            };

            var authResult = handler.AuthenticateAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            Assert.AreEqual(true, authResult.Succeeded);
            Assert.AreEqual(true, authResult.Principal.Identity.IsAuthenticated);
            Assert.AreEqual("TestName", authResult.Principal.Identity.Name);
        }
Example #33
0
        public void UpdateFeatures_ClearsCachedFeatures()
        {
            var features = new FeatureCollection();

            features.Set <IHttpRequestFeature>(new HttpRequestFeature());
            features.Set <IHttpResponseFeature>(new HttpResponseFeature());
            features.Set <IHttpWebSocketFeature>(new TestHttpWebSocketFeature());

            // featurecollection is set. all cached interfaces are null.
            var context = new DefaultHttpContext(features);

            TestAllCachedFeaturesAreNull(context, features);
            Assert.Equal(3, features.Count());

            // getting feature properties populates feature collection with defaults
            TestAllCachedFeaturesAreSet(context, features);
            Assert.NotEqual(3, features.Count());

            // featurecollection is null. and all cached interfaces are null.
            // only top level is tested because child objects are inaccessible.
            context.Uninitialize();
            TestCachedFeaturesAreNull(context, null);


            var newFeatures = new FeatureCollection();

            newFeatures.Set <IHttpRequestFeature>(new HttpRequestFeature());
            newFeatures.Set <IHttpResponseFeature>(new HttpResponseFeature());
            newFeatures.Set <IHttpWebSocketFeature>(new TestHttpWebSocketFeature());

            // featurecollection is set to newFeatures. all cached interfaces are null.
            context.Initialize(newFeatures);
            TestAllCachedFeaturesAreNull(context, newFeatures);
            Assert.Equal(3, newFeatures.Count());

            // getting feature properties populates new feature collection with defaults
            TestAllCachedFeaturesAreSet(context, newFeatures);
            Assert.NotEqual(3, newFeatures.Count());
        }
Example #34
0
        public async Task UseMiddlewareWithIMiddlewareWorks()
        {
            var mockServiceProvider = new DummyServiceProvider();
            var builder             = new ApplicationBuilder(mockServiceProvider);

            builder.UseMiddleware(typeof(Middleware));
            var app               = builder.Build();
            var context           = new DefaultHttpContext();
            var sp                = new DummyServiceProvider();
            var middlewareFactory = new BasicMiddlewareFactory();

            sp.AddService(typeof(IMiddlewareFactory), middlewareFactory);
            context.RequestServices = sp;
            await app(context);

            Assert.True(Assert.IsType <bool>(context.Items["before"]));
            Assert.True(Assert.IsType <bool>(context.Items["after"]));
            Assert.NotNull(middlewareFactory.Created);
            Assert.NotNull(middlewareFactory.Released);
            Assert.IsType <Middleware>(middlewareFactory.Created);
            Assert.IsType <Middleware>(middlewareFactory.Released);
            Assert.Same(middlewareFactory.Created, middlewareFactory.Released);
        }
        public void ReplacingResponseBody_DoesNotCreateOnCompletedRegistration()
        {
            var features = new FeatureCollection();

            var originalStream    = new FlushAsyncCheckStream();
            var replacementStream = new FlushAsyncCheckStream();

            var responseBodyMock = new Mock <IHttpResponseBodyFeature>();

            responseBodyMock.Setup(o => o.Stream).Returns(originalStream);
            features.Set(responseBodyMock.Object);

            var responseMock = new Mock <IHttpResponseFeature>();

            features.Set(responseMock.Object);

            var context = new DefaultHttpContext(features);

            Assert.Same(originalStream, context.Response.Body);
            Assert.Same(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

            context.Response.Body = replacementStream;

            Assert.Same(replacementStream, context.Response.Body);
            Assert.NotSame(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

            context.Response.Body = originalStream;

            Assert.Same(originalStream, context.Response.Body);
            Assert.Same(responseBodyMock.Object, context.Features.Get <IHttpResponseBodyFeature>());

            // The real issue was not that an OnCompleted registration existed, but that it would previously flush
            // the original response body in the OnCompleted callback after the response body was disposed.
            // However, since now there's no longer an OnCompleted registration at all, it's easier to verify that.
            // https://github.com/dotnet/aspnetcore/issues/25342
            responseMock.Verify(m => m.OnCompleted(It.IsAny <Func <object, Task> >(), It.IsAny <object>()), Times.Never);
        }
        public void Cookies_GetAndSet()
        {
            var request       = new DefaultHttpContext().Request;
            var cookieHeaders = request.Headers["Cookie"];

            Assert.Empty(cookieHeaders);
            var cookies0 = request.Cookies;

            Assert.Empty(cookies0);
            Assert.Null(cookies0["key0"]);
            Assert.False(cookies0.ContainsKey("key0"));

            var newCookies = new[] { "name0=value0%2C", "%5Ename1=value1" };

            request.Headers["Cookie"] = newCookies;

            cookies0 = RequestCookieCollection.Parse(newCookies);
            var cookies1 = request.Cookies;

            Assert.Equal(cookies0, cookies1);
            Assert.Equal(2, cookies1.Count);
            Assert.Equal("value0,", cookies1["name0"]);
            Assert.Equal("value1", cookies1["^name1"]);
            Assert.Equal(newCookies, request.Headers["Cookie"]);

            var cookies2 = new RequestCookieCollection(new Dictionary <string, string>()
            {
                { "name2", "value2" }
            });

            request.Cookies = cookies2;
            Assert.Equal(cookies2, request.Cookies);
            Assert.Equal("value2", request.Cookies["name2"]);
            cookieHeaders = request.Headers["Cookie"];
            Assert.Equal(new[] { "name2=value2" }, cookieHeaders);
        }
Example #37
0
 public DefaultHttpRequest(DefaultHttpContext context)
 {
     _context = context;
     _features.Initalize(context.Features);
 }
Example #38
0
        private HttpContext CreateContext()
        {
            var context = new DefaultHttpContext();

            return(context);
        }
Example #39
0
        public InversionRecuperadasController_Details_test()
        {
            _contextOptions = CreateNewContextOptions();
            context         = new ApplicationDbContext(_contextOptions);

            //Insertar datos semilla en la base de datos usando una instancia de contexto
            var rating = new Rating {
                Nombre = "A"
            };

            context.Rating.Add(rating);
            var area = new Areas {
                Nombre = "Sanidad"
            };

            context.Areas.Add(area);
            var tipo = new TiposInversiones {
                Nombre = "Crownfunding"
            };

            context.TiposInversiones.Add(tipo);



            Proyecto proyecto1 = new Proyecto
            {
                ProyectoId      = 1,
                FechaExpiracion = new DateTime(2020, 1, 1),
                Importe         = 12,
                Interes         = 50,
                MinInversion    = 5,
                Nombre          = "Pruebas en sanidad",
                NumInversores   = 0,
                Plazo           = 12,
                Progreso        = 34,
                Rating          = rating
            };

            context.Proyecto.Add(proyecto1);

            context.ProyectoAreas.Add(new ProyectoAreas {
                Proyecto = proyecto1, Areas = area
            });


            Monedero monedero1 = new Monedero
            {
                MonederoId = 1,
                Dinero     = 500
            };

            context.Monedero.Add(monedero1);

            Inversor inversor1 = new Inversor
            {
                Id               = "1",
                Nombre           = "*****@*****.**",
                Email            = "*****@*****.**",
                Apellido1        = "Girón",
                Apellido2        = "López",
                Domicilio        = "C/Cuenca",
                Municipio        = "Albacete",
                NIF              = "48259596",
                Nacionalidad     = "Española",
                PaisDeResidencia = "España",
                Provincia        = "Albacete",
                PasswordHash     = "hola",
                UserName         = "******",
                Monedero         = monedero1
            };

            context.Users.Add(inversor1);


            Inversion inversion1 = new Inversion
            {
                InversionId        = 1,
                Cuota              = 150,
                EstadosInversiones = "En_Curso",
                Intereses          = 50,
                Inversor           = inversor1,
                Proyecto           = proyecto1,
                TipoInversionesId  = 1,
                Total              = 200
            };

            context.Inversion.Add(inversion1);

            Inversion inversion2 = new Inversion
            {
                InversionId        = 2,
                Cuota              = 150,
                EstadosInversiones = "Finalizado",
                Intereses          = 50,
                Inversor           = inversor1,
                Proyecto           = proyecto1,
                TipoInversionesId  = 1,
                Total              = 200
            };

            context.Inversion.Add(inversion2);


            InversionRecuperada invRec1 = new InversionRecuperada
            {
                InversionRecuperadaId = 1,
                CantidadRecuperada    = 5,
                Inversion             = inversion1,
                Comentario            = "OK 1",
                FechaRecuperacion     = DateTime.Now,
            };

            InversionRecuperada invRec2 = new InversionRecuperada
            {
                InversionRecuperadaId = 2,
                CantidadRecuperada    = 10,
                Inversion             = inversion1,
                Comentario            = "OK 2",
                FechaRecuperacion     = DateTime.Now,
            };

            context.InversionRecuperada.Add(invRec1);
            context.InversionRecuperada.Add(invRec2);

            context.SaveChanges();

            //Para simular la conexión:
            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            inversionRecuperadaContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            inversionRecuperadaContext.User = identity;
        }
        public ManageControllerTest()
        {
            var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();

            var services = new ServiceCollection();
            services.AddOptions();
            services
                .AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>();

            services.AddLogging();
            services.AddOptions();

            // IHttpContextAccessor is required for SignInManager, and UserManager
            var context = new DefaultHttpContext();
            context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
            services.AddSingleton<IHttpContextAccessor>(
                new HttpContextAccessor()
                    {
                        HttpContext = context,
                    });

            _serviceProvider = services.BuildServiceProvider();
        }