예제 #1
0
        void CreateUser_returns_400_when_username_exist()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <UsersController>();
            var context    = scope.Resolve <DiscussionContext>();

            var user = new User
            {
                Id       = Guid.NewGuid(),
                Username = "******",
                Password = "******",
                Nickname = "cccchr"
            };

            context.Users.Add(user);
            context.SaveChanges();

            // Act
            var result = controller.CreateUser(new UsersController.CreateUserModel
            {
                Username = "******",
                Password = "******",
                Nickname = "realchr"
            });

            // Assert
            var badResult = Assert.IsType <BadRequestObjectResult>(result);

            Assert.Equal("UsernameExist", badResult.Value);
        }
예제 #2
0
        void CreateUser_returns_ok_when_everything_ok()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <UsersController>();
            var context    = scope.Resolve <DiscussionContext>();

            // Act

            var model = new UsersController.CreateUserModel
            {
                Username = "******",
                Password = "******",
                Nickname = "realchr"
            };

            var result = controller.CreateUser(model);

            // Assert
            Assert.IsType <OkResult>(result);

            var userInDatabase = context.Users.Where(p => p.Username == model.Username).FirstOrDefault();

            Assert.NotNull(userInDatabase);
            Assert.Equal(model.Username, userInDatabase.Username);
            Assert.Equal(model.Password, userInDatabase.Password);
            Assert.Equal(model.Nickname, userInDatabase.Nickname);
        }
예제 #3
0
        void CreateArticle_returns_ok_when_ok_with_id_and_saves_article()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller  = scope.Resolve <ArticlesController>();
            var loginStatus = scope.Resolve <FakeLoginStatus>();

            loginStatus.RealUserId = Guid.NewGuid();

            // Act
            var model = new ArticlesController.CreateArticleModel
            {
                Title = "title23213",
                Text  = "asdasdasdasdasd"
            };
            var result = controller.CreateArticle(model);

            // Assert
            var okResult  = Assert.IsType <OkObjectResult>(result);
            var articleId = Assert.IsType <Guid>(okResult.Value);

            var article = controller.Context.Articles.Where(p => p.Id == articleId).FirstOrDefault();

            Assert.NotNull(article);
            Assert.Equal(articleId, article.Id);
            Assert.Equal(model.Title, article.Title);
            Assert.Equal(model.Text, article.Text);
            Assert.Equal(loginStatus.UserId, article.UserId);
        }
예제 #4
0
        void RemoveArticle_returns_forbidden_when_article_not_belong_to_current_user()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller  = scope.Resolve <ArticlesController>();
            var loginStatus = scope.Resolve <FakeLoginStatus>();

            // Set userId of login status
            loginStatus.RealUserId = Guid.NewGuid();

            // add an article which not belongs to current user
            var article = new Article
            {
                Id         = Guid.NewGuid(),
                Text       = "asdasdasdas",
                ThumbCount = 0,
                Title      = "asdasdasdad",
                UserId     = Guid.NewGuid()            // a random
            };

            controller.Context.Articles.Add(article);
            controller.Context.SaveChanges();

            // Act
            var result = controller.RemoveArticle(article.Id);

            // Assert
            Assert.IsType <ForbidResult>(result);
        }
        public void AddNullToContainerExpectedException()
        {
            DataCreator <int, Matrix <Position <IPoint <int> > > > dataCreator = new ContainerCreator <int, Matrix <Position <IPoint <int> > > >();
            var container = dataCreator.Create();

            container.Add(null);
        }
예제 #6
0
        static void Main()
        {
            var container = ContainerCreator.Create();

            container = container.RegisterBootstrapper <Bootstrapper>();
            var serviceConfigurator = (ServiceConfigurator)container.Resolve(typeof(IServiceConfigurator), null);

            serviceConfigurator.ConfigureAndRun();
        }
예제 #7
0
        static void Main(string[] args)
        {
            ContainerCreator containerCreator = new ContainerCreator();              //建立Creator

            containerCreator.CreateBuilder();                                        //建立Builder
            containerCreator.LoadLibrary();                                          //載入dll=>class,interface
            var assemblyInfoList = new List <JBService.IOC.AssemblyImplementInfo>(); //設定要註冊的interface及其對應實作

            assemblyInfoList.Add(new AssemblyImplementInfo
            {
                ImplementClassInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.SERVICE.AbsentService", Path = @"JBHRIS.HRM.ABSENT.SERVICE.dll"
                },
                InterfaceInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.IAbsentService", Path = @"JBHRIS.HRM.ABSENT.dll"
                },
            });
            assemblyInfoList.Add(new AssemblyImplementInfo
            {
                ImplementClassInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.DAL.AbsentServiceRepository", Path = @"JBHRIS.HRM.ABSENT.DAL.dll"
                },
                InterfaceInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.SERVICE.IAbsentServiceRepository", Path = @"JBHRIS.HRM.ABSENT.SERVICE.dll"
                },
            });
            assemblyInfoList.Add(new AssemblyImplementInfo
            {
                ImplementClassInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.DAL.TestAbsentServiceBll", Path = @"JBHRIS.HRM.ABSENT.DAL.dll"
                },
                InterfaceInfo = new AssemblyInfo {
                    ClassName = "JBHRIS.HRM.ABSENT.SERVICE.IAbsentServiceBll", Path = @"JBHRIS.HRM.ABSENT.SERVICE.dll"
                },
            });
            var helper = new JBService.IOC.ConnectionHelper(Properties.Settings.Default.MyConnectionString);

            containerCreator.builder.Register <JBService.IOC.ConnectionHelper>(p => helper).As <JBService.IOC.ConnectionHelper>();
            containerCreator.RegisterAssemblyFromInfo(assemblyInfoList);//選擇模組

            //手動指定選擇的contructor
            //containerCreator.builder.Register<ClassLibrary1.InterfaceB>(containner => new ImplementA.ImpB(containner.Resolve<ClassLibrary1.InterfaceC>()));

            var container = containerCreator.BuilderContainer();                              //建立類別容器
            var repo      = containerCreator.GetService <JBService.IOC.ConnectionHelper>();
            var service   = containerCreator.GetService <JBHRIS.HRM.ABSENT.IAbsentService>(); //注入
            var data      = service.GetEntitles("110406", "W", new DateTime(2018, 12, 31), new DateTime(2018, 12, 31));

            //service.RunA();//叫用

            //var serviceB = containerCreator.GetService<ClassLibrary1.InterfaceB>();
            //serviceB.RunB();


            Console.Read();
        }
예제 #8
0
        private List <IModule> GetIntegrationDependencies()
        {
            var appSettings = ContainerCreator.LoadAppSettings();

            return(new List <IModule>
            {
                new JobModule(appSettings),
                new BlockchainsModule(appSettings),
                new CqrsTestModule(appSettings.CurrentValue.BlockchainCashinDetectorJob.Cqrs, "test")
            });
        }
예제 #9
0
        public void CreateContainer()
        {
            DataCreator <int, Matrix <Position <IPoint <int> > > > dataCreator = new ContainerCreator <int, Matrix <Position <IPoint <int> > > >();
            var container         = dataCreator.Create();
            var expectedContainer = new Container <Matrix <Position <IPoint <int> > > >();

            var expectedType = expectedContainer.GetType();
            var realType     = container.GetType();

            Assert.AreEqual(expectedType, realType);
        }
예제 #10
0
        void RemoveArticle_returns_unauthorized_when_not_login()
        {
            // rArrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <ArticlesController>();

            // Act
            var result = controller.RemoveArticle(Guid.NewGuid());

            // Assert
            Assert.IsType <UnauthorizedResult>(result);
        }
예제 #11
0
        static void Main(string[] args)
        {
            var container = ContainerCreator.InitializeContainer();
            var game      = container.GetInstance <IGame>();

            Console.WriteLine("Commands:");
            Console.WriteLine($"`{ExitCommand}` - for stoping execution and terminate application");
            Console.WriteLine($"`{RollCommand} 1` - for adding 1 pin in the frame");
            Console.WriteLine($"`{ScoreCommand}` - for showing score");

            while (true)
            {
                var userCommand = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(userCommand))
                {
                    continue;
                }

                if (userCommand.ToLower() == ExitCommand)
                {
                    return;
                }
                try
                {
                    if (userCommand.ToLower().Contains(RollCommand))
                    {
                        var strArray = userCommand.Split(" ");
                        if (strArray.Length < 2 || !short.TryParse(strArray[1], out var pins))
                        {
                            Console.WriteLine($"{RollCommand} command is incorrect. Try again. Template is `{RollCommand} 1`");
                            continue;
                        }

                        game.Roll(pins);
                        continue;
                    }

                    if (userCommand.ToLower() == ScoreCommand)
                    {
                        Console.WriteLine($"Score: {game.Score()}");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
예제 #12
0
        public static IDataCollection <Container <Matrix <Position <IPoint <int> > > > > CreateContainerCollections()
        {
            var positionCreator = new PositionCreator <int, IPoint <int> >();
            var firstPosition   = positionCreator.Create();
            var secondPosition  = positionCreator.Create();
            var thirdPosition   = positionCreator.Create();
            var fourthPosition  = positionCreator.Create();
            var fifthPosition   = positionCreator.Create();

            for (var i = 0; i < 10; i++)
            {
                firstPosition.Add(new Point3D <int>(i, i, i));
                secondPosition.Add(new Point3D <int>(i, i, i));
                thirdPosition.Add(new Point3D <int>(i, i, i));
                fourthPosition.Add(new Point3D <int>(i, i, i));
                fifthPosition.Add(new Point3D <int>(i, i, i));
            }

            var matrixCreator = new MatrixCreator <int, Position <IPoint <int> > >();
            var firstMatrix   = matrixCreator.Create();
            var secondMatrix  = matrixCreator.Create();
            var thirdMatrix   = matrixCreator.Create();

            firstMatrix.Add((Position <IPoint <int> >)firstPosition);
            firstMatrix.Add((Position <IPoint <int> >)secondPosition);
            firstMatrix.Add((Position <IPoint <int> >)thirdPosition);

            secondMatrix.Add((Position <IPoint <int> >)fifthPosition);
            secondMatrix.Add((Position <IPoint <int> >)fourthPosition);
            secondMatrix.Add((Position <IPoint <int> >)thirdPosition);

            thirdMatrix.Add((Position <IPoint <int> >)secondPosition);
            thirdMatrix.Add((Position <IPoint <int> >)fourthPosition);
            thirdMatrix.Add((Position <IPoint <int> >)thirdPosition);

            var containerCreator = new ContainerCreator <int, Matrix <Position <IPoint <int> > > >();
            var container        = containerCreator.Create();

            container.Add((Matrix <Position <IPoint <int> > >)firstMatrix);
            container.Add((Matrix <Position <IPoint <int> > >)secondMatrix);
            container.Add((Matrix <Position <IPoint <int> > >)thirdMatrix);

            var containerColectionCreator = new ContainerCollectionCreator <int, Container <Matrix <Position <IPoint <int> > > > >();
            var containerCollection       = containerColectionCreator.Create();

            containerCollection.Add((Container <Matrix <Position <IPoint <int> > > >)container);
            return(containerCollection);
        }
예제 #13
0
        void RemoveArticle_returns_notfound_when_article_not_exist()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller  = scope.Resolve <ArticlesController>();
            var loginStatus = scope.Resolve <FakeLoginStatus>();

            loginStatus.RealUserId = Guid.NewGuid();

            // Act
            var result = controller.RemoveArticle(Guid.NewGuid());

            // Assert
            Assert.IsType <NotFoundResult>(result);
        }
예제 #14
0
파일: NomadKernel.cs 프로젝트: orb1t/Nomad
        public void Dispose()
        {
            _logger.Debug("Disposing: " + typeof(NomadKernel));

            if (_moduleLoaderCreator != null)
            {
                _moduleLoaderCreator.Dispose();
                _moduleLoaderCreator = null;
            }


            _logger.Debug("Shutting down logger repository");
            if (_repository != null)
            {
                _repository.Shutdown();
                _repository = null;
            }
        }
예제 #15
0
        void CreateArticle_returns_unauthorized_when_not_login()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <ArticlesController>();

            // Act
            var result = controller.CreateArticle(new ArticlesController.CreateArticleModel
            {
                Title = "title23213",
                Text  = "asdasdasdasdasd"
            });

            // Assert
            Assert.IsType <UnauthorizedResult>(result);
        }
예제 #16
0
        void CreateArticle_returns_400_when_model_invalid()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <ArticlesController>();

            // Act
            var result = controller.CreateArticle(new ArticlesController.CreateArticleModel
            {
                Title = "",
                Text  = ""
            });

            // Assert
            var badResult = Assert.IsType <BadRequestObjectResult>(result);

            Assert.Equal("模型无效", badResult.Value);
        }
예제 #17
0
        void CreateUser_returns_400_when_model_invalid()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller = scope.Resolve <UsersController>();

            // Act
            var result = controller.CreateUser(new UsersController.CreateUserModel
            {
                Username = "******",
                Password = "******",
                Nickname = "realchr"
            });

            // Assert
            var badResult = Assert.IsType <BadRequestObjectResult>(result);

            Assert.Equal("ModelInvalid", badResult.Value);
        }
예제 #18
0
파일: NomadKernel.cs 프로젝트: orb1t/Nomad
        private void RegisterCoreServices(NomadConfiguration nomadConfiguration)
        {
            ModuleAppDomain = AppDomain.CreateDomain("Modules AppDomain",
                                                     new Evidence(AppDomain.CurrentDomain.Evidence),
                                                     AppDomain.CurrentDomain.BaseDirectory,
                                                     AppDomain.CurrentDomain.BaseDirectory,
                                                     true);

            // create kernel version of the event aggregator4
            var siteEventAggregator = new EventAggregator(new NullGuiThreadProvider());

            // use container creator to create communication services on modules app domain
            string asmName  = typeof(ContainerCreator).Assembly.FullName;
            string typeName = typeof(ContainerCreator).FullName;

            if (typeName != null)
            {
                _moduleLoaderCreator = (ContainerCreator)
                                       ModuleAppDomain.CreateInstanceAndUnwrap(asmName, typeName);

                DistributedConfiguration distributedConfiguration = nomadConfiguration.DistributedConfiguration;
                String loggerConfiguration = KernelConfiguration.ModulesLoggerConfigurationFilePath;
                _moduleLoaderCreator.Install(distributedConfiguration, loggerConfiguration);

                // create facade for event aggregator combining proxy and on site object
                EventAggregator = new ForwardingEventAggregator(_moduleLoaderCreator.EventAggregatorOnModulesDomain,
                                                                siteEventAggregator);

                // used proxied service locator
                ServiceLocator = _moduleLoaderCreator.ServiceLocator;

                ModuleLoader = _moduleLoaderCreator.CreateModuleLoaderInstance();
            }

            _moduleManager = new ModuleManager(ModuleLoader,
                                               KernelConfiguration.ModuleFilter,
                                               KernelConfiguration.DependencyChecker);
        }
예제 #19
0
        void RemoveArticle_returns_ok_and_change_db_when_all_condition_ok()
        {
            // Arrange
            var container = ContainerCreator.CreateContainer();
            var scope     = container.BeginLifetimeScope();

            var controller  = scope.Resolve <ArticlesController>();
            var loginStatus = scope.Resolve <FakeLoginStatus>();

            // Set userId of login status
            loginStatus.RealUserId = Guid.NewGuid();

            // add an article which not belongs to current user
            var article = new Article
            {
                Id         = Guid.NewGuid(),
                Text       = "asdasdasdas",
                ThumbCount = 0,
                Title      = "asdasdasdad",
                UserId     = loginStatus.UserId
            };

            controller.Context.Articles.Add(article);
            controller.Context.SaveChanges();

            // Act
            var result = controller.RemoveArticle(article.Id);

            // Assert
            Assert.IsType <OkResult>(result);

            // Check database
            var articleInDatabase = controller.Context.Articles.FirstOrDefault(p => p.Id == article.Id);

            Assert.Null(articleInDatabase);
        }
예제 #20
0
        public async Task DepositWalletLockReleasedEventSent__AggregateIsRejectedCashin__NotifyCashinFailedCommandSent()
        {
            var operationId     = Guid.NewGuid();
            var cashinAggregate = CashinAggregate.Restore(operationId,
                                                          "ETC",
                                                          6,
                                                          6,
                                                          10,
                                                          250,
                                                          "ETC",
                                                          "EthereumClassic",
                                                          0,
                                                          DateTime.UtcNow,
                                                          "0x...",
                                                          150,
                                                          250,
                                                          null,
                                                          null,
                                                          null,
                                                          0.05m,
                                                          "0x...",
                                                          DateTime.UtcNow,
                                                          10,
                                                          10,
                                                          DateTime.UtcNow,
                                                          null,
                                                          operationId,
                                                          CashinResult.Unknown,
                                                          null,
                                                          null,
                                                          10,
                                                          250,
                                                          "0xHASH",
                                                          CashinState.ClientRetrieved,
                                                          true,
                                                          "1.0.0",
                                                          CashinErrorCode.Unknown,
                                                          null);
            var cashinRepoMock = new Mock <ICashinRepository>();

            cashinRepoMock.Setup(x => x.GetAsync(It.IsAny <Guid>())).ReturnsAsync(cashinAggregate);
            var repoModule = new RepoMockModule((builder) =>
            {
                var depositWalletLockRepository = new Mock <IDepositWalletLockRepository>();
                var matchingEngineCallsDeduplicationRepository = new Mock <IMatchingEngineCallsDeduplicationRepository>();
                var enrolledBalanceRepository = new Mock <IEnrolledBalanceRepository>();
                builder.RegisterInstance(cashinRepoMock.Object)
                .As <ICashinRepository>();

                builder.RegisterInstance(matchingEngineCallsDeduplicationRepository.Object)
                .As <IMatchingEngineCallsDeduplicationRepository>();

                builder.RegisterInstance(enrolledBalanceRepository.Object)
                .As <IEnrolledBalanceRepository>();

                builder.RegisterInstance(depositWalletLockRepository.Object)
                .As <IDepositWalletLockRepository>();
            });

            var dependencies = GetIntegrationDependencies();

            dependencies.Add(repoModule);
            var testContainer = ContainerCreator.CreateContainer(
                dependencies.ToArray()
                );
            var cqrsEngine = testContainer.Resolve <ICqrsEngine>();
            var @event     = new BlockchainRiskControl.Contract.Events.OperationRejectedEvent()
            {
                OperationId = operationId,
                Message     = "Test"
            };

            cqrsEngine.StartSubscribers();

            cqrsEngine.PublishEvent(@event, BlockchainRiskControl.Contract.BlockchainRiskControlBoundedContext.Name);

            await CqrsTestModule.CommandsInterceptor.WaitForCommandToBeHandledWithTimeoutAsync(
                typeof(ReleaseDepositWalletLockCommand),
                TimeSpan.FromMinutes(4));

            await CqrsTestModule.EventsInterceptor.WaitForEventToBeHandledWithTimeoutAsync(
                typeof(DepositWalletLockReleasedEvent),
                TimeSpan.FromMinutes(4));

            await CqrsTestModule.CommandsInterceptor.WaitForCommandToBeHandledWithTimeoutAsync(
                typeof(NotifyCashinFailedCommand),
                TimeSpan.FromMinutes(4));
        }
예제 #21
0
        public async Task BalanceProcessorStarted__BalanceIsGtThanZero_DepositWalletLockedEventSent()
        {
            var testContainer = ContainerCreator.CreateIntegrationContainer();
            Mock <IBlockchainApiClient> apiClient = new Mock <IBlockchainApiClient>();

            apiClient.Setup(x =>
                            x.EnumerateWalletBalanceBatchesAsync(
                                It.IsAny <int>(),
                                It.IsAny <Func <string, int> >(),
                                It.IsAny <Func <IReadOnlyList <WalletBalance>, Task <bool> > >()))
            .ReturnsAsync <int, Func <string, int>,
                           Func <IReadOnlyList <WalletBalance>, Task <bool> >,
                           IBlockchainApiClient, EnumerationStatistics>
            (
                (batchSize, accuracyProvider, enumerationCallback) =>
            {
                enumerationCallback(new List <WalletBalance>
                {
                    new WalletBalance
                    (
                        new WalletBalanceContract
                    {
                        Address = "0x974542bd37b57a2a5151d0ef1619e3e3d150ce47",
                        AssetId = "ETC",
                        Balance = Conversions.CoinsToContract(1, 6),
                        Block   = 3000000
                    },
                        assetAccuracy: 6
                    )
                }).GetAwaiter().GetResult();

                return(new EnumerationStatistics(1, 1, TimeSpan.FromMilliseconds(1)));
            }
            );

            var cqrsEngine = testContainer.Resolve <ICqrsEngine>();
            var assets     = (await testContainer.Resolve <IAssetsServiceWithCache>().GetAllAssetsAsync(false))
                             .Where(a => a.BlockchainIntegrationLayerId == "EthereumClassic")
                             .ToDictionary(
                a => a.BlockchainIntegrationLayerAssetId,
                a => a);
            var blockchainAssets = await testContainer.Resolve <IBlockchainApiClientProvider>().
                                   Get("EthereumClassic")
                                   .GetAllAssetsAsync(50);

            BalanceProcessor processor = new BalanceProcessor("EthereumClassic",
                                                              testContainer.Resolve <ILogFactory>(),
                                                              testContainer.Resolve <IHotWalletsProvider>(),
                                                              apiClient.Object,
                                                              cqrsEngine,
                                                              testContainer.Resolve <IEnrolledBalanceRepository>(),
                                                              assets,
                                                              blockchainAssets
                                                              );

            cqrsEngine.StartSubscribers();

            await processor.ProcessAsync(100);

            await CqrsTestModule.CommandsInterceptor.WaitForCommandToBeHandledWithTimeoutAsync(typeof(LockDepositWalletCommand),
                                                                                               TimeSpan.MaxValue);

            await CqrsTestModule.EventsInterceptor.WaitForEventToBeHandledWithTimeoutAsync(typeof(DepositWalletLockedEvent),
                                                                                           TimeSpan.FromMilliseconds(Int32.MaxValue));

            Task.Delay(600000).Wait();
        }