public void Can_override_service_creation_with_custom_implementation()
        {
            using (var appHost = new BasicAppHost(typeof(BasicService).Assembly).Init())
            {
                var container = appHost.Container;
                var serviceController = appHost.ServiceController;

                container.Register<IFoo>(c => new Foo());
                container.Register<IBar>(c => new Bar());

                var request = new AutoWire();

                var response = serviceController.Execute(request) as AutoWireResponse;

                Assert.That(response, Is.Not.Null);
                Assert.That(response.Foo as Foo, Is.Not.Null);
                Assert.That(response.Bar as Bar, Is.Not.Null);

                container.Register(c => new AutoWireService(new Foo2())
                {
                    Bar = new Bar2()
                });

                response = serviceController.Execute(request) as AutoWireResponse;

                Assert.That(response, Is.Not.Null);
                Assert.That(response.Foo as Foo2, Is.Not.Null);
                Assert.That(response.Bar as Bar2, Is.Not.Null);
            }
        }
Пример #2
0
		public void GetUsers_Test()
		{
            using (var appHost = new BasicAppHost(typeof(GetUsersService).Assembly).Init())
		    {
                var request = new GetUsers
                {
                    UserIds = new ArrayOfLong(1, 2),
                    UserNames = new ArrayOfString("User3", "User4")
                };

                var factory = new OrmLiteConnectionFactory(
                    InMemoryDb, SqliteDialect.Provider);

                using (var db = factory.Open())
                {
                    db.DropAndCreateTable<User>();
                    db.Insert(new User { Id = 1, UserName = "******" });
                    db.Insert(new User { Id = 2, UserName = "******" });
                    db.Insert(new User { Id = 3, UserName = "******" });
                    db.Insert(new User { Id = 4, UserName = "******" });

                    var handler = appHost.Resolve<GetUsersService>();

                    var response = handler.Any(request);

                    Assert.That(response.Users.Count, Is.EqualTo(4));
                }
            }
		}
        public void WithAnEmbeddedResource_ShouldBeAbleToFindItInVirtualDirectoryWalk()
        {
            var appHost = new BasicAppHost(GetType().Assembly);
            var directory = new ResourceVirtualDirectory(new InMemoryVirtualPathProvider(appHost), null, GetType().Assembly, GetType().Assembly.GetName().Name);

            var resourceFiles = WalkForFiles(directory).ToList();
            Assert.IsNotEmpty(resourceFiles);
            Assert.Contains("/ResourceFile.txt", resourceFiles);
        }
        public void TestInit()
        {
            LogManager.LogFactory = new ConsoleLogFactory();

            _appHost = new BasicAppHost();
            _appHost.Init();

            var container = _appHost.Container;

            container.RegisterAutoWired<HelloService>();
        }
        public void Generic_Service_should_not_get_registered_with_generic_parameter()
        {
            using (var appHost = new BasicAppHost(typeof(GenericService<>).Assembly).Init())
            {
                // We should definately *not* be able to call the generic service with a "T" request object :)
                var requestType = typeof(GenericService<>).GetGenericArguments()[0];
                var exception = Assert.Throws<NotImplementedException>(() => appHost.ServiceController.GetService(requestType));

                Assert.That(exception.Message, Does.Contain("Unable to resolve service"));
            }
        }
Пример #6
0
        public void Can_use_nested_classes_as_Request_DTOs()
        {
            using (var appHost = new BasicAppHost(typeof(NestedService).Assembly){}.Init())
            {
                var root = (Root)appHost.ExecuteService(new Root { Id = 1 });
                Assert.That(root.Id, Is.EqualTo(1));

                var nested = (Root.Nested)appHost.ExecuteService(new Root.Nested { Id = 2 });
                Assert.That(nested.Id, Is.EqualTo(2));
            }
        }
 static IAppHost GetAppHost()
 {
     if (_appHost == null)
     {
         _appHost = new BasicAppHost();
         var authService = new AuthenticateService();
         authService.SetResolver(_appHost);
         _appHost.Container.Register(authService);
         _appHost.Container.Register<IAuthSession>(authUserSession);
     }
     return _appHost;
 }
        public void By_default_assigned_roles_are_saved_in_UserAuth_table()
        {
            using (var appHost = new BasicAppHost
            {
                ConfigureContainer = container =>
                {

                    container.Register<IDbConnectionFactory>(c =>
                        new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

                    container.Register<IAuthRepository>(c =>
                        new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

                    container.Resolve<IAuthRepository>().InitSchema();
                }
            }.Init())
            {
                using (var db = appHost.Container.Resolve<IDbConnectionFactory>().Open())
                {
                    var register = CreateNewUserRegistration();
                    var req = new BasicRequest(register);
                    req.QueryString["authSecret"] = appHost.Config.AdminAuthSecret = "allow";

                    var response = (RegisterResponse)appHost.ExecuteService(register, req);
                    var userAuth = db.SingleById<UserAuth>(response.UserId);

                    var assignResponse = (AssignRolesResponse)appHost.ExecuteService(new AssignRoles
                    {
                        UserName = userAuth.UserName,
                        Roles = { "TestRole" },
                        Permissions = { "TestPermission" },
                    }, req);
                    Assert.That(assignResponse.AllRoles[0], Is.EqualTo("TestRole"));
                    Assert.That(assignResponse.AllPermissions[0], Is.EqualTo("TestPermission"));

                    userAuth = db.SingleById<UserAuth>(response.UserId);
                    Assert.That(userAuth.Roles[0], Is.EqualTo("TestRole"));
                    Assert.That(userAuth.Permissions[0], Is.EqualTo("TestPermission"));

                    appHost.ExecuteService(new UnAssignRoles
                    {
                        UserName = userAuth.UserName,
                        Roles = { "TestRole" },
                        Permissions = { "TestPermission" },
                    }, req);

                    userAuth = db.SingleById<UserAuth>(response.UserId);
                    Assert.That(userAuth.Roles.Count, Is.EqualTo(0));
                    Assert.That(userAuth.Permissions.Count, Is.EqualTo(0));
                }
            }
        }
        public void Can_inject_RequestContext_for_IRequiresRequestContext_services()
        {
            using (var appHost = new BasicAppHost(typeof(RequiresService).Assembly).Init())
            {
                var serviceController = appHost.ServiceController;

                var request = new RequiresContext();
                var response = serviceController.Execute(request, new BasicRequest(request))
                    as RequiresContextResponse;

                Assert.That(response, Is.Not.Null);
            }
        }
        public void TestInit()
        {
            if (_appHost == null)
            {
                LogManager.LogFactory = new ConsoleLogFactory();

                _appHost = new BasicAppHost();
                _appHost.Init();

                var store = NewDocumentStore();
                DataInitializer.InitializerWithDefaultValuesIfEmpty(store);

                _appHost.Container.RegisterAutoWired<ConfigurationService>();
            }
        }
        public void Can_register_all_services_in_an_assembly()
        {
            using (var appHost = new BasicAppHost(typeof(BasicService).Assembly).Init())
            {
                var container = appHost.Container;
                var serviceController = appHost.ServiceController;

                container.Register<IFoo>(c => new Foo());
                container.Register<IBar>(c => new Bar());

                var request = new AutoWire();
                var response = serviceController.Execute(request) as AutoWireResponse;

                Assert.That(response, Is.Not.Null);
            }
        }
        private static void CanOptimizeResult(string contentType, IPlugin pluginFormat)
        {
            using (var appHost = new BasicAppHost().Init())
            {
                var dto = new TestDto { Name = "test" };

                var httpReq = new MockHttpRequest();
                httpReq.Headers.Add(HttpHeaders.AcceptEncoding, "gzip,deflate,sdch");
                httpReq.ResponseContentType = contentType;

                if (pluginFormat != null) pluginFormat.Register(appHost);

                object result = httpReq.ToOptimizedResult(dto);
                Assert.IsNotNull(result);
                Assert.IsTrue(result is CompressedResult);
            }
        }
Пример #13
0
        public void Prefer_user_defined_routes_first()
        {
            using (var appHost = new BasicAppHost
            {
                ConfigureAppHost = host =>
                {
                    host.Routes.AddFromAssembly(typeof(RoutePriorityTests).GetAssembly());
                },
            }.Init())
            {
                var emptyUrl = new RoutePriority().ToGetUrl();
                Assert.That(emptyUrl, Is.EqualTo("/category/priority"));

                var autoRouteWithIdUrl = new RoutePriority { Id = "foo" }.ToGetUrl();
                Assert.That(autoRouteWithIdUrl, Is.EqualTo("/RoutePriority/foo"));
            }
        }
        public void Can_register_routes_dynamically()
        {
            typeof(NewApiRequestDto)
                .AddAttributes(new RouteAttribute("/custom/NewApiRequestDto"))
                .AddAttributes(new RouteAttribute("/custom/NewApiRequestDto/get-only", "GET"));
            
            using (var appHost = new BasicAppHost(typeof(NewApiRestServiceWithAllVerbsImplemented).Assembly).Init())
            {
                var allVerbs = appHost.RestPaths.First(x => x.Path == "/custom/NewApiRequestDto");
                Assert.That(allVerbs.AllowsAllVerbs);
                Assert.That(allVerbs.AllowedVerbs, Is.Null);

                var getOnlyVerb = appHost.RestPaths.First(x => x.Path == "/custom/NewApiRequestDto/get-only");
                Assert.That(getOnlyVerb.AllowedVerbs.Contains("GET"));
                Assert.That(!getOnlyVerb.AllowedVerbs.Contains("POST"));
            }
        }
 public ServicesTestsWithTearDown()
 {
     if (ServiceStackHost.Instance != null) { return; }
     try
     {
         AppHost = new BasicAppHost(typeof(PeopleServices).Assembly)
         {
             ConfigureContainer = container => ConfigureContainer(container)
         }.Init();
     }
     catch (Exception)
     {
         // It's already set, use existing
         AppHost = ServiceStackHost.Instance;
         //AppHost.Configure(container);
     }
 }
Пример #16
0
		public void Xsd_output_does_not_contain_xml_declaration()
		{
		    using (var appHost = new BasicAppHost().Init())
		    {
		        var xsd = new XsdGenerator
		        {
		            OperationTypes = new[]
		            {
		                typeof (GetCustomer), typeof (GetCustomerResponse), typeof (GetCustomers),
		                typeof (GetCustomersResponse), typeof (StoreCustomer)
		            },
		            OptimizeForFlash = false,
		        }.ToString();

		        Assert.That(!xsd.StartsWith("<?"));
		    }
		}
Пример #17
0
        public void Wsdl_state_is_correct()
        {
            using (var appHost = new BasicAppHost().Init())
            {

                var dummyServiceType = GetType();
                appHost.Metadata.Add(dummyServiceType, typeof(GetCustomer), typeof(GetCustomerResponse));
                appHost.Metadata.Add(dummyServiceType, typeof(GetCustomers), typeof(GetCustomersResponse));
                appHost.Metadata.Add(dummyServiceType, typeof(StoreCustomer), null);

                var wsdlGenerator = new Soap11WsdlMetadataHandler();
                var xsdMetadata = new XsdMetadata(appHost.Metadata);
                var wsdlTemplate = wsdlGenerator.GetWsdlTemplate(xsdMetadata, "http://w3c.org/types", false, "http://w3c.org/types", "Service Name");

                Assert.That(wsdlTemplate.ReplyOperationNames, Is.EquivalentTo(xsdMetadata.GetReplyOperationNames(Format.Soap12)));
                Assert.That(wsdlTemplate.OneWayOperationNames, Is.EquivalentTo(xsdMetadata.GetOneWayOperationNames(Format.Soap12)));
            }
        }
Пример #18
0
        public void CreateInstance_throws_on_missing_dependency()
        {
            using (var appHost = new BasicAppHost().Init())
            {
                var services = appHost.Container;
                services.AddTransient<IFoo, Foo>();

                var typeFactory = new ContainerResolveCache(appHost.Container);

                var foo = typeFactory.CreateInstance(services, typeof(IFoo), tryResolve: true);
                Assert.That(foo, Is.Not.Null);

                var bar = typeFactory.CreateInstance(services, typeof(IBar), tryResolve: true);
                Assert.That(bar, Is.Null);

                Assert.Throws<ResolutionException>(() =>
                    typeFactory.CreateInstance(services, typeof(IBar), tryResolve: false));
            }
        }
Пример #19
0
        public void Can_use_NetCore_APIs_to_register_dependencies()
        {
            using (var appHost = new BasicAppHost().Init())
            {
                var services = appHost.Container;

                services.AddTransient<IFoo, Foo>();
                services.AddSingleton<IBar>(c => new Bar { Name = "bar" });

                var bar = (Bar)services.GetService(typeof(IBar));
                Assert.That(bar.Name, Is.EqualTo("bar"));

                var foo = (Foo)services.GetService(typeof(IFoo));
                Assert.That(foo.Id, Is.EqualTo(0));
                Assert.That(ReferenceEquals(foo.Bar, bar));

                foo = (Foo)services.GetService(typeof(IFoo));
                Assert.That(foo.Id, Is.EqualTo(1));
                Assert.That(ReferenceEquals(foo.Bar, bar));
            }
        }
Пример #20
0
        public void Does_process_messages_in_BasicAppHost()
        {
            using (var appHost = new BasicAppHost(typeof(HelloService).Assembly)
            {
                ConfigureAppHost = host =>
                {
                    host.Container.Register(c => CreateMqServer());

                    var mqServer = host.Container.Resolve<IMessageService>();

                    mqServer.RegisterHandler<HelloIntro>(host.ServiceController.ExecuteMessage);
                    mqServer.Start();
                }
            }.Init())
            {
                using (var mqClient = appHost.Resolve<IMessageService>().CreateMessageQueueClient())
                {
                    mqClient.Publish(new HelloIntro { Name = "World" });

                    IMessage<HelloIntroResponse> responseMsg = mqClient.Get<HelloIntroResponse>(QueueNames<HelloIntroResponse>.In);
                    mqClient.Ack(responseMsg);
                    Assert.That(responseMsg.GetBody().Result, Is.EqualTo("Hello, World!"));
                }
            }
        }
        public void Generic_service_with_recursive_ceneric_type_should_not_get_registered()
        {
            using (var appHost = new BasicAppHost
            {
                UseServiceController = x =>
                    new ServiceController(x, () => new[] {
                        typeof(GenericService<>).MakeGenericType(new[] { typeof(Generic3<>) })
                    })
            }.Init())
            {
                // Tell manager to register GenericService<Generic3<>>, which should not be possible since Generic3<> is an open type
                var exception = Assert.Throws<System.NotImplementedException>(() =>
                    appHost.ServiceController.GetService(typeof(Generic3<>)));

                Assert.That(exception.Message, Does.Contain("Unable to resolve service"));
            }
        }
Пример #22
0
 public void TestFixtureSetUp()
 {
     loadAppHost = new BasicAppHost().Init();
 }
		public static RegisterService GetRegistrationService(
			IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
			MockRequestContext requestContext = null)
		{
			if (requestContext == null)
				requestContext = new MockRequestContext();
			if (oAuthUserSession == null)
				oAuthUserSession = requestContext.ReloadSession();

			var httpReq = requestContext.Get<IHttpRequest>();
			var httpRes = requestContext.Get<IHttpResponse>();
			oAuthUserSession.Id = httpRes.CreateSessionId(httpReq);
			httpReq.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost {
				Container = requestContext.Container
			};

			requestContext.Container.Register(userAuthRepository);

		    var authService = new AuthenticateService {
                RequestContext = requestContext,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				UserAuthRepo = userAuthRepository,
				RequestContext = requestContext,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
Пример #24
0
        public void Can_assign_roles_that_persist_to_UserAuthRole_table_in_DynamoDb()
        {
            using (var appHost = new BasicAppHost
            {
                ConfigureContainer = container =>
                {
                    container.Register<IPocoDynamo>(c => new PocoDynamo(DynamoConfig.CreateDynamoDBClient()));
                    //DynamoMetadata.Reset();
                    container.Resolve<IPocoDynamo>().DeleteAllTables(TimeSpan.FromMinutes(1));

                    container.Register<IAuthRepository>(c => new DynamoDbAuthRepository(c.Resolve<IPocoDynamo>()));
                    container.Resolve<IAuthRepository>().InitSchema();
                }
            }.Init())
            {
                var db = appHost.Container.Resolve<IPocoDynamo>();

                var register = CreateNewUserRegistration();
                var req = new BasicRequest(register);
                req.QueryString["authSecret"] = appHost.Config.AdminAuthSecret = "allow";

                var response = (RegisterResponse)appHost.ExecuteService(register, req);
                var userAuth = db.GetItem<UserAuth>(response.UserId);

                var assignResponse = (AssignRolesResponse)appHost.ExecuteService(new AssignRoles
                {
                    UserName = userAuth.UserName,
                    Roles = { "TestRole" },
                    Permissions = { "TestPermission" },
                }, req);
                Assert.That(assignResponse.AllRoles[0], Is.EqualTo("TestRole"));
                Assert.That(assignResponse.AllPermissions[0], Is.EqualTo("TestPermission"));

                Assert.That(userAuth.Roles.Count, Is.EqualTo(0));
                Assert.That(userAuth.Permissions.Count, Is.EqualTo(0));

                var manageRoles = (IManageRoles)appHost.Container.Resolve<IAuthRepository>();
                Assert.That(manageRoles.HasRole(userAuth.Id.ToString(), "TestRole"));
                Assert.That(manageRoles.HasPermission(userAuth.Id.ToString(), "TestPermission"));

                appHost.ExecuteService(new UnAssignRoles
                {
                    UserName = userAuth.UserName,
                    Roles = { "TestRole" },
                    Permissions = { "TestPermission" },
                }, req);

                Assert.That(!manageRoles.HasRole(userAuth.Id.ToString(), "TestRole"));
                Assert.That(!manageRoles.HasPermission(userAuth.Id.ToString(), "TestPermission"));
            }
        }
        public void Generic_service_can_be_registered_with_closed_types()
        {
            using (var appHost = new BasicAppHost
            {
                UseServiceController = x => new ServiceController(x, () => new[]
                {
                    typeof (GenericService<Generic1>),
                    typeof (GenericService<>).MakeGenericType(new[] {typeof (Generic2)}),
                    // GenericService<Generic2> created through reflection
                    typeof (GenericService<Generic3<string>>),
                    typeof (GenericService<Generic3<int>>),
                    typeof (GenericService<>).MakeGenericType(new[]
                        {typeof (Generic3<>).MakeGenericType(new[] {typeof (double)})}),
                    // GenericService<Generic3<double>> created through reflection
                })
            }.Init())
            {
                var serviceController = appHost.ServiceController;

                Assert.AreEqual(typeof(Generic1).FullName, ((Generic1Response)serviceController.Execute(new Generic1())).Data);
                Assert.AreEqual(typeof(Generic2).FullName, ((Generic1Response)serviceController.Execute(new Generic2())).Data);
                Assert.AreEqual(typeof(Generic3<string>).FullName, ((Generic1Response)serviceController.Execute(new Generic3<string>())).Data);
                Assert.AreEqual(typeof(Generic3<int>).FullName, ((Generic1Response)serviceController.Execute(new Generic3<int>())).Data);
                Assert.AreEqual(typeof(Generic3<double>).FullName, ((Generic1Response)serviceController.Execute(new Generic3<double>())).Data);
            }
        }
        public void GetPhysicalPath_Honours_WebHostPhysicalPath()
        {
            using (var appHost = new BasicAppHost {
                ConfigFilter = c => {
                    c.WebHostPhysicalPath = "c:/Windows/Temp";
                }
            }.Init())
            {
                var mock = new HttpRequestMock();

                string originalPath = appHost.Config.WebHostPhysicalPath;
                string path = mock.GetPhysicalPath();

                var normalizePaths = (Func<string, string>)(p => p == null ? null : p.Replace('\\', '/'));

                Assert.That(normalizePaths(path), Is.EqualTo(normalizePaths("{0}/{1}".Fmt(originalPath, mock.PathInfo))));
            }
        }
        public void CheckRoleAssignmentInUserRoleTableUsingIAuthRepository()
        {
            using (var appHost = new BasicAppHost
            {
                ConfigureContainer = container =>
                {
                    container.Register<IUnitOfWork>(c => UnitOfWork);
                    container.Register<IAuthRepository>(c =>
                        new LightSpeedUserAuthRepository(c.Resolve<IUnitOfWork>())
                        {
                            UseDistinctRoleTables = true
                        });
                }
            }.Init())
            {
                // Arrange
                LightSpeed.UserAuth userAuth;
                AssignRolesResponse assignRolesResponse;
                var newRegistration = CreateNewUserRegistration();
                var request = new BasicRequest(newRegistration);
                var response = (RegisterResponse)appHost.ExecuteService(newRegistration, request);
                var authRepo = appHost.Resolve<IAuthRepository>();

                // Test #1: Check role and permission assignment
                // ---------------------------------------------
                // Act
                userAuth = UnitOfWork.FindById<LightSpeed.UserAuth>(response.UserId); // Hydrate userAuth

                var assignRoleRequest =
                    new AssignRoles
                    {
                        UserName = userAuth.UserName,
                        Roles = { TestRoleName },
                        Permissions = { TestPermissionName },
                    };

                userAuth = (LightSpeed.UserAuth)authRepo.GetUserAuthByUserName(assignRoleRequest.UserName);
                authRepo.AssignRoles(userAuth, assignRoleRequest.Roles, assignRoleRequest.Permissions);

                // Assert #1.1: 
                // Check UserAuth to contain roles and permissions
                Assert.That(authRepo.GetRoles(userAuth).FirstOrDefault(), Is.EqualTo(TestRoleName));
                Assert.That(authRepo.GetPermissions(userAuth).FirstOrDefault(), Is.EqualTo(TestPermissionName));

                // Assert #1.2: 
                // Check that roles and permissions are not persisted to UserAuth table
                Assert.That(userAuth.Roles.Count, Is.EqualTo(0));
                Assert.That(userAuth.Permissions.Count, Is.EqualTo(0));

                // Assert #1.3:
                // Check UserRoles table to contain roles and permissions
                var manageRoles = (IManageRoles)appHost.Container.Resolve<IAuthRepository>();
                Assert.That(manageRoles.HasRole(userAuth.Id.ToString(), TestRoleName));
                Assert.That(manageRoles.HasPermission(userAuth.Id.ToString(), TestPermissionName));

                // Test #2: Check role and permission un-assignment
                // ------------------------------------------------
                // Act
                userAuth = UnitOfWork.FindById<LightSpeed.UserAuth>(response.UserId); // Hydrate userAuth

                var unassignRolesRequest =
                    new UnAssignRoles
                    {
                        UserName = userAuth.UserName,
                        Roles = { TestRoleName },
                        Permissions = { TestPermissionName },
                    };

                userAuth = (LightSpeed.UserAuth)authRepo.GetUserAuthByUserName(assignRoleRequest.UserName);
                authRepo.UnAssignRoles(userAuth, unassignRolesRequest.Roles, unassignRolesRequest.Permissions);

                // Assert #2.1:
                // Check UserAuth to contain roles and permissions
                Assert.That(authRepo.GetRoles(userAuth).FirstOrDefault(), Is.Null);
                Assert.That(authRepo.GetPermissions(userAuth).FirstOrDefault(), Is.Null);

                // Assert #2.2:
                // Check UserRole table not to contain roles and permissions above
                Assert.That(!manageRoles.HasRole(userAuth.Id.ToString(), TestRoleName));
                Assert.That(!manageRoles.HasPermission(userAuth.Id.ToString(), TestPermissionName));
            }
        }
		public static RegisterService GetRegistrationService(
            IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
            BasicRequest request = null)
		{
			if (request == null)
                request = new BasicRequest();
			if (oAuthUserSession == null)
				oAuthUserSession = request.ReloadSession();

            oAuthUserSession.Id = request.Response.CreateSessionId(request);
            request.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost();

            mockAppHost.Container.Register<IAuthRepository>(userAuthRepository);

		    var authService = new AuthenticateService {
                Request = request,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				AuthRepo = userAuthRepository,
				Request = request,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
Пример #29
0
        public void Does_dispose_request_scope_dependency_in_PostMessageHandler()
        {
            var disposeCount = 0;
            using (var appHost = new BasicAppHost(typeof(HelloWithDepService).Assembly)
            {
                ConfigureAppHost = host =>
                {
                    RequestContext.UseThreadStatic = true;
                    host.Container.Register<IDisposableDependency>(c => new DisposableDependency(() =>
                    {
                        disposeCount++;
                    }))
                        .ReusedWithin(ReuseScope.Request);
                    host.Container.Register(c => CreateMqServer(host));

                    var mqServer = host.Container.Resolve<IMessageService>();

                    mqServer.RegisterHandler<HelloIntroWithDep>(host.ServiceController.ExecuteMessage);
                    mqServer.Start();
                }
            }.Init())
            {
                using (var mqClient = appHost.Resolve<IMessageService>().CreateMessageQueueClient())
                {
                    mqClient.Publish(new HelloIntroWithDep { Name = "World" });

                    IMessage<HelloIntroResponse> responseMsg = mqClient.Get<HelloIntroResponse>(QueueNames<HelloIntroResponse>.In);
                    mqClient.Ack(responseMsg);

                    Assert.That(disposeCount, Is.EqualTo(1));
                }
            }
        }
        public void CheckRoleAssignmentInUserAuthTableUsingSecretKey()
        {
            using (var appHost = new BasicAppHost
            {
                ConfigureAppHost = host =>
                {
                    host.Config.AdminAuthSecret = AdminAuthSecret;
                },
                ConfigureContainer = container =>
                {
                    container.Register<IUnitOfWork>(c => UnitOfWork);
                    container.Register<IAuthRepository>(c =>
                        new LightSpeedUserAuthRepository(c.Resolve<IUnitOfWork>()));
                }
            }.Init())
            {
                // Arrange
                LightSpeed.UserAuth userAuth;
                AssignRolesResponse assignRolesResponse;
                var newRegistration = CreateNewUserRegistration();
                var request = new BasicRequest(newRegistration);
                request.QueryString["authSecret"] = AdminAuthSecret;
                var response = (RegisterResponse)appHost.ExecuteService(newRegistration, request);
                
                // Test #1: Check role and permission assignment
                // ---------------------------------------------
                // Act
                userAuth = UnitOfWork.FindById<LightSpeed.UserAuth>(response.UserId); // Hydrate userAuth

                var assignRoleRequest = 
                    new AssignRoles
                    {
                        UserName = userAuth.UserName,
                        Roles = { TestRoleName },
                        Permissions = { TestPermissionName },
                    };
                
                // Assert #1.1: 
                // Check AssignRoles response to contain roles and permissions
                assignRolesResponse = (AssignRolesResponse)appHost.ExecuteService(assignRoleRequest, request);
                Assert.That(assignRolesResponse.AllRoles[0], Is.EqualTo(TestRoleName));
                Assert.That(assignRolesResponse.AllPermissions[0], Is.EqualTo(TestPermissionName));
                
                // Assert #1.2: 
                // Check UserAuth to contain roles and permissions
                userAuth = UnitOfWork.FindById<LightSpeed.UserAuth>(response.UserId);
                Assert.That(userAuth.Roles[0], Is.EqualTo(TestRoleName));
                Assert.That(userAuth.Permissions[0], Is.EqualTo(TestPermissionName));

                // Test #2: Check role and permission un-assignment
                // ------------------------------------------------
                // Act
                var unassignRolesRequest =
                    new UnAssignRoles
                        {
                            UserName = userAuth.UserName,
                            Roles = { TestRoleName },
                            Permissions = { TestPermissionName },
                        };
                appHost.ExecuteService(unassignRolesRequest, request);

                // Assert #2.1:
                // Check UserAuth not to contain roles and permissions above
                userAuth = UnitOfWork.FindById<LightSpeed.UserAuth>(response.UserId);
                Assert.That(userAuth.Roles.Count, Is.EqualTo(0));
                Assert.That(userAuth.Permissions.Count, Is.EqualTo(0));
            }
        }