Ejemplo n.º 1
0
        public Task StartAsync_NotStarted_ShouldStart()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Act.
                await this.subject.StartAsync(cancellationToken);
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedPreExecuteAsync.Verify(
                    f => f(It.IsNotIn(cancellationToken, CancellationToken.None)),
                    Times.Once()
                    );

                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.IsNotIn(cancellationToken, CancellationToken.None)),
                    Times.Once()
                    );

                this.subject.StubbedPostExecuteAsync.Verify(
                    f => f(CancellationToken.None),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(It.IsAny <Type>(), It.IsAny <Exception>(), It.IsAny <CancellationToken>()),
                    Times.Never()
                    );
            }));
        }
Ejemplo n.º 2
0
        public void Setup()
        {
            _field           = new Mock <IField>();
            _distanceHandler = new Mock <IDistanceHandler>();
            _positionChecker = new Mock <IPositionChecker>();

            _position = new Point(0, 0);

            IAnimal[,] defaultAnimals = new IAnimal[2, 3];

            defaultAnimals[0, 0] = new Antilope();
            defaultAnimals[0, 1] = new Antilope();
            defaultAnimals[0, 2] = new Lion();
            defaultAnimals[1, 0] = null;
            defaultAnimals[1, 1] = null;
            defaultAnimals[1, 2] = new Lion();

            _field.Setup(f => f.Width).Returns(3);
            _field.Setup(f => f.Heigth).Returns(2);
            _field.Setup(f => f.Animals).Returns(defaultAnimals);

            List <Point> ExistingAnimals = new List <Point>();

            ExistingAnimals.Add(new Point(0, 0));
            ExistingAnimals.Add(new Point(1, 0));
            ExistingAnimals.Add(new Point(2, 1));
            ExistingAnimals.Add(new Point(2, 0));

            _positionChecker.Setup(f => f.CheckEmpty(It.IsIn <Point>(ExistingAnimals))).Returns(false);
            _positionChecker.Setup(f => f.CheckEmpty(It.IsNotIn <Point>(ExistingAnimals))).Returns(true);

            _systemUnderTest = new AnimalFinder(_field.Object, _positionChecker.Object, _distanceHandler.Object);
        }
Ejemplo n.º 3
0
        public async Task FixObviouslyWrongEstimationsAsync()
        {
            var mockRpc = CreateAndConfigureRpcClient(hasPeersInfo: true);
            var any     = EstimateSmartFeeMode.Conservative;

            mockRpc.Setup(rpc => rpc.GetMempoolInfoAsync()).ReturnsAsync(
                new MemPoolInfo
            {
                MemPoolMinFee = 0.00001000,                         // 1 s/b (default value)
                Histogram     = MempoolInfoGenerator.FeeRanges.Select((x, i) => new FeeRateGroup
                {
                    Count = (uint)(200 * (i + 1)),
                    Sizes = (uint)(40 * 100 * (i + 1)),
                    From  = new FeeRate((decimal)x.from),
                    To    = new FeeRate((decimal)x.to),
                    Fees  = Money.Zero,
                    Group = x.from
                }).ToArray()
            });
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(2, any)).ReturnsAsync(FeeRateResponse(2, 3_500m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(3, any)).ReturnsAsync(FeeRateResponse(3, 500m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(6, any)).ReturnsAsync(FeeRateResponse(6, 10m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(18, any)).ReturnsAsync(FeeRateResponse(18, 5m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(36, any)).ReturnsAsync(FeeRateResponse(36, 5m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(1008, any)).ReturnsAsync(FeeRateResponse(1008, 1m));
            mockRpc.Setup(rpc => rpc.EstimateSmartFeeAsync(It.IsNotIn <int>(2, 3, 5, 6, 8, 11, 13, 15, 1008), any)).ThrowsAsync(new NoEstimationException(0));

            var allFee = await mockRpc.Object.EstimateAllFeeAsync(EstimateSmartFeeMode.Conservative);

            Assert.Equal(3_500, allFee.Estimations[2]);
            Assert.True(allFee.Estimations[3] > 500);
            Assert.True(allFee.Estimations[1008] > 1);
        }
Ejemplo n.º 4
0
        public async Task StopAsync_AlreadyRunning_ShouldCancelWaitForNewBlock()
        {
            // Arrange.
            this.handler.GetBlockHintAsync(Arg.Any <CancellationToken>()).Returns(1);

            this.rpc.Setup(r => r.GetBlockAsync(1, It.IsAny <CancellationToken>()))
            .ThrowsAsync(new RPCException(
                             RPCErrorCode.RPC_INVALID_PARAMETER,
                             "Block height out of range",
                             null
                             ));

            var background = await this.subject.StartAsync(this.handler, CancellationToken.None);

            // Act.
            await this.subject.StopAsync(CancellationToken.None);

            // Assert.
            _ = this.handler.Received(1).GetBlockHintAsync(Arg.Any <CancellationToken>());
            this.rpc.Verify(r => r.GetBlockAsync(1, It.IsNotIn(CancellationToken.None)), Times.Once());
            _ = this.handler.Received(0).ProcessBlockAsync(Arg.Any <Block>(), Arg.Any <int>(), Arg.Any <CancellationToken>());

            this.subject.IsRunning.Should().BeFalse();
            background.IsCanceled.Should().BeTrue();
        }
Ejemplo n.º 5
0
        public async Task StopAsync_AlreadyRunning_ShouldCancelProcessBlockAsync()
        {
            var block = Block.CreateBlock(ZcoinNetworks.Instance.Regtest);

            // Arrange.
            this.handler.GetBlockHintAsync(Arg.Any <CancellationToken>()).Returns(0);
            this.rpc.Setup(r => r.GetBlockAsync(0, It.IsAny <CancellationToken>())).ReturnsAsync(block);
            this.handler.When(h => h.ProcessBlockAsync(block, 0, Arg.Any <CancellationToken>())).Do(call =>
            {
                var token = call.ArgAt <CancellationToken>(2);

                token.WaitHandle.WaitOne();
                token.ThrowIfCancellationRequested();
            });

            var background = await this.subject.StartAsync(this.handler, CancellationToken.None);

            // Act.
            await this.subject.StopAsync(CancellationToken.None);

            // Assert.
            _ = this.handler.Received(1).GetBlockHintAsync(Arg.Any <CancellationToken>());
            this.rpc.Verify(r => r.GetBlockAsync(0, It.IsNotIn(CancellationToken.None)), Times.Once());
            _ = this.handler.Received(1).ProcessBlockAsync(block, 0, Arg.Any <CancellationToken>());

            this.subject.IsRunning.Should().BeFalse();
            background.IsCanceled.Should().BeTrue();
        }
        public async Task Test_that_read_block_command_is_processed()
        {
            //ARRANGE
            var countdown = new CountdownEvent(2);
            Mock <IBlockReader> blockReader = null;
            var blockEventsHandlerMock      = BlockEventsHandlerCreateMock((intName, evt, headers, messagePublisher) =>
            {
            });

            var(client, apiFactory, testServer) = PrepareClient <AppSettings>(
                serverOptions =>
            {
                CreateMocks(
                    out blockReader,
                    out var blockProvider);

                serverOptions.IntegrationName = _integrationName;
                serverOptions.UseTransferAmountTransactionsModel();
                blockReader
                .Setup(x => x.ReadBlockAsync(2, It.IsAny <IBlockListener>()))
                .Returns(Task.CompletedTask)
                .Callback(() => { countdown.Signal(); });

                blockReader
                .Setup(x => x.ReadBlockAsync(1, It.IsAny <IBlockListener>()))
                .Returns(Task.CompletedTask)
                .Callback(() => { countdown.Signal(); });
                blockProvider.Setup(x => x.GetLastAsync()).ReturnsAsync(new LastIrreversibleBlockUpdatedEvent(1, "1"));
                ConfigureFactories(serverOptions, blockReader, blockProvider);
            },
                clientOptions =>
            {
                clientOptions.BlockEventsHandlerFactory =
                    (context) => blockEventsHandlerMock.Object;
                clientOptions.RabbitVhost        = _rabbitMqSettings.Vhost;
                clientOptions.RabbitMqConnString = _rabbitMqSettings.GetConnectionString();
                clientOptions.AddIntegration(_integrationName);
            });

            //ACT
            using (testServer)
                using (client)
                {
                    client.Initialize();

                    var apiBlocksReader = apiFactory.Create(_integrationName);

                    await apiBlocksReader.SendAsync(new ReadBlockCommand(1), null);

                    await apiBlocksReader.SendAsync(new ReadBlockCommand(2), null);

                    countdown.Wait(Waiting.Timeout);
                }

            //ASSERT

            blockReader.Verify(x => x.ReadBlockAsync(1, It.IsNotNull <IBlockListener>()), Times.AtLeastOnce);
            blockReader.Verify(x => x.ReadBlockAsync(2, It.IsNotNull <IBlockListener>()), Times.AtLeastOnce);
            blockReader.Verify(x => x.ReadBlockAsync(It.IsNotIn(1, 2), It.IsNotNull <IBlockListener>()), Times.Never);
        }
Ejemplo n.º 7
0
        public async Task StartAsync_GetBlockHintAsyncReturnTooHeight_ShouldWaitForNewBlockNotification()
        {
            // Arrange.
            var block = Block.CreateBlock(ZcoinNetworks.Instance.Regtest);

            this.handler.GetBlockHintAsync(Arg.Any <CancellationToken>()).Returns(1);

            this.rpc.SetupSequence(r => r.GetBlockAsync(1, It.IsAny <CancellationToken>()))
            .ThrowsAsync(new RPCException(
                             RPCErrorCode.RPC_INVALID_PARAMETER,
                             "Block height out of range",
                             null
                             ))
            .ReturnsAsync(block);

            // Act.
            var background = await this.subject.StartAsync(this.handler, CancellationToken.None);

            await Task.Delay(500);

            this.handler.ProcessBlockAsync(block, 1, Arg.Any <CancellationToken>()).Returns(Task.FromException <int>(new OperationCanceledException()));

            this.publisher.SendMoreFrame("hashblock").SendMoreFrame(uint256.One.ToBytes()).SendFrame(BitConverter.GetBytes(0));
            await Task.WhenAny(background);

            // Assert.
            _ = this.handler.Received(1).GetBlockHintAsync(Arg.Any <CancellationToken>());
            this.rpc.Verify(
                r => r.GetBlockAsync(1, It.IsNotIn(CancellationToken.None)),
                Times.Exactly(2)
                );
            _ = this.handler.Received(1).ProcessBlockAsync(block, 1, Arg.Any <CancellationToken>());
        }
Ejemplo n.º 8
0
        public void PassingUnAuthorisableGroupIDToControllerThrowsUnauthorizedResult()
        {
            //Mock the repository
            var repository =
                new Mock <IStagingRepository <MassTerminationModelSerialized> >(MockBehavior.Strict);


            //Mock data factory
            var dataFactory =
                new Mock <IDataFactory>(MockBehavior.Strict);

            dataFactory.Setup(d => d.GetMassTerminateRepository()).Returns(repository.Object);

            //Mapping factory
            IMappingFactory mapFactory = new MappingFactory();

            //Mock Auth
            var authorization = new Mock <IAuthorizationProvider>(MockBehavior.Strict);

            authorization.Setup(s => s.IsAuthorized(It.IsNotIn <string>(new List <string>()
            {
                "426"
            }))).Returns(false);

            var controller = new MassTerminateController(dataFactory.Object, authorization.Object, mapFactory);


            Task <IHttpActionResult> actionResult = controller.SetDataAsync("123", models);

            Assert.IsInstanceOfType(actionResult.Result, typeof(UnauthorizedResult));
        }
        public void Arrange()
        {
            OrgQueryRepository = new Mock <IOrganisationQueryRepository>();

            ContactQueryRepository = new Mock <IContactQueryRepository>();
            ContactQueryRepository.Setup(r => r.GetBySignInId(It.IsNotIn(Guid.Empty)))
            .Returns(Task.FromResult(new Contact()
            {
                Id             = It.IsAny <Guid>(), Status = ContactStatus.Live,
                OrganisationId = It.IsAny <Guid>(), Username = "******", Email = "*****@*****.**"
            }));
            ContactQueryRepository.Setup(r => r.GetBySignInId(Guid.Empty))
            .Returns(Task.FromResult(new Contact()
            {
                Id             = Guid.Empty, Status = ContactStatus.InvitePending,
                OrganisationId = It.IsAny <Guid>(), Username = "******", Email = "*****@*****.**"
            }));

            OrgQueryRepository.Setup(r => r.Get(It.IsAny <Guid>())).ReturnsAsync(new Organisation
            {
                EndPointAssessorName  = "SomeName",
                EndPointAssessorUkprn = 12345,
                Id     = It.IsAny <Guid>(),
                Status = OrganisationStatus.New
            });

            ContactRepository = new Mock <IContactRepository>();
            ContactRepository.Setup(x => x.UpdateUserName(It.IsAny <Guid>(), It.IsAny <string>())).Returns(Task.FromResult(default(object)));

            RegisterRepository = new Mock <IRegisterRepository>();
            RegisterRepository.Setup(m => m.UpdateEpaOrganisationPrimaryContact(It.IsAny <Guid>(), It.IsAny <string>())).Returns(Task.FromResult(default(object)));

            Handler = new LoginHandler(new Mock <ILogger <LoginHandler> >().Object,
                                       OrgQueryRepository.Object, ContactQueryRepository.Object, ContactRepository.Object, RegisterRepository.Object);
        }
        public void Get_Team_NotInTeam()
        {
            var spelerMock = new Mock <ISpelerRepository>();
            var teamMock   = new Mock <ITeamRepository>();

            //Arrange
            var id = 2;

            spelerMock.Setup(s => s.GetSpeler(id)).Returns(new Speler()
            {
                Id           = 2,
                AssignedTeam = null,
                DeviceId     = "1",
            });
            spelerMock.Setup(s => s.GetSpeler(It.IsNotIn(2))).Returns((Speler)null);
            teamMock.Setup(t => t.GetTeam(1)).Returns(_fakeTeamRepo.GetTeam(1));
            teamMock.Setup(t => t.GetTeam(2)).Returns(_fakeTeamRepo.GetTeam(2));
            teamMock.Setup(t => t.GetTeam(3)).Returns(_fakeTeamRepo.GetTeam(3));
            teamMock.Setup(t => t.GetTeam(It.IsNotIn(1, 2, 3))).Returns((Team)null);
            var speler = new SpelerService(spelerMock.Object, teamMock.Object);

            var sid = 2;
            // Act
            Team result = speler.GetTeamFromSpeler(sid);

            // Assert
            Assert.Null(result);
        }
Ejemplo n.º 11
0
        public void TestNewTopicCommandSuccess()
        {
            string projectIdParam = null;
            string details        = null;

            _dataSourceMock.Setup(ds => ds.NewTopicAsync(It.IsAny <string>())).Returns(Task.FromResult(s_topic));
            _objectUnderTest.Initialize(_contextMock.Object);
            _objectUnderTest.NewTopicUserPrompt = projectId =>
            {
                projectIdParam = projectId;
                return(MockTopicFullName);
            };
            UserPromptWindow.PromptUserFunction = options =>
            {
                details = options.ErrorDetails;
                return(true);
            };

            _objectUnderTest.OnNewTopicCommand();

            Assert.AreEqual(MockProjectId, projectIdParam);
            Assert.IsNull(details);
            Assert.AreEqual(1, _objectUnderTest.RefreshHitCount);
            _dataSourceMock.Verify(ds => ds.NewTopicAsync(MockTopicFullName), Times.Once);
            _dataSourceMock.Verify(ds => ds.NewTopicAsync(It.IsNotIn(MockTopicFullName)), Times.Never);
        }
Ejemplo n.º 12
0
 public TestsFixture()
 {
     // Do "global" initialization here; Only called once.
     MockPinService = new Mock <IPinService>();
     MockPinService.Setup(x => x.VerifyPin(It.IsAny <long>(), 1234)).Returns(true);
     MockPinService.Setup(x => x.VerifyPin(It.IsAny <long>(), It.IsNotIn(1234))).Returns(false);
 }
        public CourseLibraryServiceTest()
        {
            mockAuthor = new Mock <Author>();
            mockCourseLibraryService.Setup(m => m.AddAuthor(It.IsAny <Author>())).ReturnsAsync(new SuccessOperationResult <Author> {
                Result = mockAuthor.Object, Code = ConstOperationCodes.AUTHOR_CREATED
            });

            mockCourseLibraryService.Setup(m => m.GetAuthor(It.IsNotIn(Guid.Empty), false)).ReturnsAsync(new SuccessOperationResult <Author>
            {
                Code   = ConstOperationCodes.AUTHOR_FOUND,
                Result = mockAuthor.Object
            });
            mockCourseLibraryService.Setup(m => m.GetAuthor(It.Is <Guid>(g => g.Equals(Guid.Empty)), false)).ReturnsAsync(
                new FailedOperationResult <Author>
            {
                Code = ConstOperationCodes.AUTHOR_NOT_FOUND,
            }
                );
            mockCourseLibraryService.Setup(m => m.AddAuthor(It.Is <Author>(a => a.FirstName == "exsits"))).ReturnsAsync(
                new FailedOperationResult <Author>
            {
                Code = ConstOperationCodes.AUTHOR_NAME_ALREADY_EXISTS,
            }
                );
        }
Ejemplo n.º 14
0
        public static void SetupFor(this Mock <IRequesterSecurity> requesterSecurity, Requester requester)
        {
            requesterSecurity.AssertNotNull("requesterSecurity");
            requester.AssertNotNull("requester");

            if (requester.Equals(Requester.Unauthenticated))
            {
                throw new ArgumentException("Requester must be authorized.", "requester");
            }

            requesterSecurity.Setup(v => v.AuthenticateAsync(Requester.Unauthenticated))
            .Throws(new UnauthorizedException());

            requesterSecurity.Setup(v => v.AuthenticateAsync(requester))
            .ReturnsAsync(requester.UserId);

            requesterSecurity.Setup(v => v.AuthenticateAsAsync(Requester.Unauthenticated, It.IsAny <UserId>()))
            .Throws(new UnauthorizedException());

            requesterSecurity.Setup(v => v.AuthenticateAsAsync(requester, It.IsNotIn(requester.UserId)))
            .Throws(new UnauthorizedException());

            requesterSecurity.Setup(v => v.AuthenticateAsAsync(requester, requester.UserId))
            .ReturnsAsync(requester.UserId);
        }
Ejemplo n.º 15
0
        public void SetActive_Puzzel_ExistingTeam()
        {
            var fakeTeam = GameDBFake.teams.ToList();;

            var _LocalfakeTeamRepo = new TeamRepositoryFake();
            var spelerMock         = new Mock <ISpelerRepository>();
            var sessieMock         = new Mock <ISessionRepository>();
            var teamMock           = new Mock <ITeamRepository>();
            var puzzelMock         = new Mock <IPuzzelRepository>();

            teamMock.Setup(t => t.GetTeams()).Returns(fakeTeam);
            teamMock.Setup(t => t.GetTeam(It.IsIn(1, 2))).Returns((int i) => fakeTeam[0]);
            teamMock.Setup(t => t.SetActivePuzzel(It.IsIn(1, 2), It.IsAny <int>())).Callback <int, int>((a, b) => fakeTeam[0].ActivePuzzel = 0);
            teamMock.Setup(t => t.GetTeam(It.IsNotIn(1, 2))).Returns((Team)null);
            puzzelMock.Setup(p => p.GetPuzzel(It.IsAny <int>())).Returns(new Puzzel());
            var team = new TeamService(teamMock.Object,
                                       spelerMock.Object,
                                       sessieMock.Object,
                                       puzzelMock.Object);
            //Arrange
            var teamId = 1;

            // Act
            var result   = team.SetActivePuzzel(teamId, false);
            var resultId = team.ActivePuzzelID(teamId);

            // Assert
            Assert.IsType <Puzzel>(result);
            Assert.NotEqual(-1, resultId);
        }
Ejemplo n.º 16
0
        public void TestCaption()
        {
            pdfBuilder.AppendText("Not be in same paragraph as image", TextStyle.Normal);
            inline.IsImage = true;
            string altText = "alt";

            inline.AppendChild(new LiteralInline(altText));

            Mock <PdfBuilder> builder = new Mock <PdfBuilder>(document, PdfOptions.Default);

            builder.Setup(b => b.AppendText(altText, It.IsAny <TextStyle>())).Callback <string, TextStyle>((_, style) => Assert.AreEqual(TextStyle.Normal, style)).CallBase();
            builder.Setup(b => b.AppendText(It.IsNotIn(altText), It.IsAny <TextStyle>())).Callback <string, TextStyle>((_, style) => Assert.AreEqual(TextStyle.Strong, style)).CallBase();

            using (Image image = new Bitmap(4, 4))
            {
                Mock <LinkInlineRenderer> renderer = new Mock <LinkInlineRenderer>(null);
                renderer.CallBase = true;
                renderer.Setup(r => r.GetImage(It.IsAny <string>())).Returns(image);
                renderer.Object.Write(builder.Object, inline);
            }
            Assert.AreEqual(2, TestContext.CurrentContext.AssertCount, "Plumbing is broken");

            Assert.AreEqual(2, document.LastSection.Elements.Count);
            Paragraph caption = (Paragraph)document.LastSection.Elements[1];

            Assert.AreEqual(2, caption.Elements.Count);
            FormattedText figureNumber     = (FormattedText)caption.Elements[0];
            FormattedText formattedAltText = (FormattedText)caption.Elements[1];

            Text figureText      = (Text)figureNumber.Elements[0];
            Text insertedAltText = (Text)formattedAltText.Elements[0];

            Assert.AreEqual("Figure 1: ", figureText.Content);
            Assert.AreEqual(altText, insertedAltText.Content);
        }
Ejemplo n.º 17
0
        public void SetActive_Puzzel_NotexistingTeam()
        {
            var _LocalfakeTeamRepo = new TeamRepositoryFake();
            var spelerMock         = new Mock <ISpelerRepository>();
            var sessieMock         = new Mock <ISessionRepository>();
            var teamMock           = new Mock <ITeamRepository>();
            var puzzelMock         = new Mock <IPuzzelRepository>();

            teamMock.Setup(t => t.GetTeams()).Returns(_LocalfakeTeamRepo.GetTeams());
            teamMock.Setup(t => t.GetTeam(It.IsIn(1, 2))).Returns((int i) => _LocalfakeTeamRepo.GetTeam(i));
            teamMock.Setup(t => t.SetActivePuzzel(It.IsIn(1, 2), It.IsAny <int>())).Callback <int, int>((a, b) => _LocalfakeTeamRepo.SetActivePuzzel(a, b));
            teamMock.Setup(t => t.GetTeam(It.IsNotIn(1, 2))).Returns((Team)null);
            puzzelMock.Setup(p => p.GetPuzzel(It.IsAny <int>())).Returns(new Puzzel());
            var team = new TeamService(teamMock.Object,
                                       spelerMock.Object,
                                       sessieMock.Object,
                                       puzzelMock.Object);
            //Arrange
            var teamId = 9999;

            // Act
            var result   = team.SetActivePuzzel(teamId, false);
            var resultId = team.ActivePuzzelID(teamId);

            // Assert
            Assert.Equal(-1, resultId);
            Assert.Null(result);
        }
Ejemplo n.º 18
0
        public void TestPickBestOccurrence()
        {
            const int occurrenceCount        = 10;
            const int groupingsPerOccurrence = 5;
            const int individualsPerGrouping = 2;

            // build several meaningless occurrences to for the mock generator to return
            var occurrences = Enumerable
                              .Range(0, occurrenceCount)
                              .Select(_ => new Occurrence(DateTimeOffset.UtcNow,
                                                          Enumerable.Range(0, groupingsPerOccurrence)
                                                          .Select(__ => Enumerable.Range(0, individualsPerGrouping)
                                                                  .Select(___ => Guid.NewGuid().ToString())
                                                                  .ToList()).ToList())).ToList();

            // arbitrarily pick one to be the expected best occurrence
            var expectedOccurrence = occurrences[3];

            var generator = new Mock <IOccurrenceGenerator>(MockBehavior.Strict);

            generator.Setup(x => x.EnumerateOccurrences()).Returns(occurrences);

            // build a mock IPairingScorer that gives high scores to expectedOccurrence
            var scorer = new Mock <IPairingScorer>(MockBehavior.Strict);

            scorer.Setup(x => x.ScorePairing(It.IsIn(expectedOccurrence.Groupings.SelectMany(i => i)), It.IsAny <string>()))
            .Returns(50d);
            scorer.Setup(x => x.ScorePairing(It.IsNotIn(expectedOccurrence.Groupings.SelectMany(i => i)), It.IsAny <string>()))
            .Returns(1d);

            var picker           = new OccurrencePicker(generator.Object, scorer.Object);
            var actualOccurrence = picker.PickBestOccurrence();

            Assert.That(actualOccurrence, Is.EqualTo(expectedOccurrence), "The correct occurrence should be selected");
        }
Ejemplo n.º 19
0
        public void SetUp()
        {
            this.logger = new ActionLog();
            GlobalConstants.ActionLog = this.logger;

            this.target = new CombatEngine(Mock.Of <IRollable>(
                                               roller => roller.RollSuccesses(
                                                   It.IsAny <int>(),
                                                   It.IsIn <int>(7)) == 1 &&
                                               roller.RollSuccesses(
                                                   It.IsAny <int>(),
                                                   It.IsNotIn(7)) == 2));
            this.statisticHandler    = new EntityStatisticHandler();
            this.skillHandler        = new EntitySkillHandler();
            this.derivedValueHandler = new DerivedValueHandler(this.statisticHandler, this.skillHandler);
            this.abilityHandler      = new AbilityHandler();

            this.materialHandler = new MaterialHandler();

            this.objectIconHandler = new ObjectIconHandler(new RNG());

            this.itemHandler = new LiveItemHandler(new RNG());

            GlobalConstants.GameManager = Mock.Of <IGameManager>(
                manager => manager.ItemHandler == this.itemHandler &&
                manager.ObjectIconHandler == this.objectIconHandler);

            this.needHandler = new NeedHandler();
        }
            public SubscriptionService GetService()
            {
                MockAddCommand.Setup(m => m.Add(NewSubscription.FirstName,
                                                NewSubscription.LastName,
                                                NewSubscription.EmailAddress,
                                                It.IsAny <Func <Subscription, Task <Subscription> > >()))
                .Callback <string, string, string, Func <Subscription, Task <Subscription> > >((f, l, e, func) => Assert.NotNull(func(NewSubscription).Result))
                .ReturnsAsync(NewSubscription);

                MockAddCommand.Setup(m => m.Add(FailedSubscription.FirstName,
                                                FailedSubscription.LastName,
                                                FailedSubscription.EmailAddress,
                                                It.IsAny <Func <Subscription, Task <Subscription> > >()))
                .Callback <string, string, string, Func <Subscription, Task <Subscription> > >(async(f, l, e, func) => await Assert.ThrowsAsync <MessagingException>(async() => await func(FailedSubscription)))
                .ReturnsAsync(null);

                MockUpdateCommand.Setup(m => m.Update(It.Is <Subscription>(s => s.EmailAddress == NewSubscription.EmailAddress), It.IsAny <Func <Subscription, IDbConnection, IDbTransaction, Task> >()))
                .Callback <Subscription, Func <Subscription, Task> >(async(s, t) => await t(s))
                .Returns(Task.CompletedTask);

                MockOfflineProcessing.Setup(m => m.NotifySubscriber(It.IsNotIn(NewSubscription.Id)))
                .Throws(new ServerBusyException("message"));

                MockOfflineProcessing.Setup(m => m.ConfirmationReceived(It.IsNotIn(NewSubscription)))
                .Throws(new ServerBusyException("message"));

                return(new SubscriptionService(MockAddCommand.Object, MockUpdateCommand.Object, MockOfflineProcessing.Object));
            }
Ejemplo n.º 21
0
        public async Task StartAsync_ProcessBlockAsyncReturnValidHeight_ShouldRetrieveThatBlock()
        {
            // Arrange.
            var block1 = Block.CreateBlock(ZcoinNetworks.Instance.Regtest);

            block1.Header.Nonce = 1;
            block1.Header.PrecomputeHash(invalidateExisting: true, lazily: false);

            var block2 = Block.CreateBlock(ZcoinNetworks.Instance.Regtest);

            block2.Header.Nonce = 2;
            block2.Header.PrecomputeHash(invalidateExisting: true, lazily: false);

            this.handler.GetBlockHintAsync(Arg.Any <CancellationToken>()).Returns(0);
            this.rpc.Setup(r => r.GetBlockAsync(0, It.IsAny <CancellationToken>())).ReturnsAsync(block1);
            this.handler.ProcessBlockAsync(block1, 0, Arg.Any <CancellationToken>()).Returns(1);
            this.rpc.Setup(r => r.GetBlockAsync(1, It.IsAny <CancellationToken>())).ReturnsAsync(block2);
            this.handler.ProcessBlockAsync(block2, 1, Arg.Any <CancellationToken>()).Returns(Task.FromException <int>(new OperationCanceledException()));

            // Act.
            var background = await this.subject.StartAsync(this.handler, CancellationToken.None);

            await Task.WhenAny(background);

            // Assert.
            _ = this.handler.Received(1).GetBlockHintAsync(Arg.Any <CancellationToken>());
            this.rpc.Verify(r => r.GetBlockAsync(0, It.IsNotIn(CancellationToken.None)), Times.Once());
            _ = this.handler.Received(1).ProcessBlockAsync(block1, 0, Arg.Any <CancellationToken>());
            this.rpc.Verify(r => r.GetBlockAsync(1, It.IsNotIn(CancellationToken.None)), Times.Once());
            _ = this.handler.Received(1).ProcessBlockAsync(block2, 1, Arg.Any <CancellationToken>());
        }
Ejemplo n.º 22
0
        public void SelectFormatter_WithNoMatchingAcceptHeadersAndRequestContentType_PicksFormatterBasedOnObjectType
            (string acceptHeader)
        {
            // For no accept headers,
            // can write is called twice once for the request Content-Type and once for the type match pass.
            // For each additional accept header, it is called once.
            // Arrange
            var acceptHeaderCollection = string.IsNullOrEmpty(acceptHeader) ?
                                         null : MediaTypeHeaderValue.ParseList(new[] { acceptHeader }).ToArray();
            var stream       = new MemoryStream();
            var httpResponse = new Mock <HttpResponse>();

            httpResponse.SetupProperty <string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object,
                                                        requestAcceptHeader: acceptHeader,
                                                        requestContentType: "application/xml");
            var input  = "testInput";
            var result = new ObjectResult(input);
            var mockCountingFormatter = new Mock <IOutputFormatter>();

            var context = new OutputFormatterContext()
            {
                HttpContext  = actionContext.HttpContext,
                Object       = input,
                DeclaredType = typeof(string)
            };
            var mockCountingSupportedContentType = MediaTypeHeaderValue.Parse("application/text");

            mockCountingFormatter.Setup(o => o.CanWriteResult(context,
                                                              It.Is <MediaTypeHeaderValue>(mth => mth == null)))
            .Returns(true);
            mockCountingFormatter.Setup(o => o.CanWriteResult(context, mockCountingSupportedContentType))
            .Returns(true);

            // Set more than one formatters. The test output formatter throws on write.
            result.Formatters = new List <IOutputFormatter>
            {
                new CannotWriteFormatter(),
                mockCountingFormatter.Object,
            };

            // Act
            var formatter = result.SelectFormatter(context, result.Formatters);

            // Assert
            Assert.Equal(mockCountingFormatter.Object, formatter);
            mockCountingFormatter.Verify(v => v.CanWriteResult(context, null), Times.Once());

            // CanWriteResult is invoked for the following cases:
            // 1. For each accept header present
            // 2. Request Content-Type
            // 3. Type based match
            var callCount = (acceptHeaderCollection == null ? 0 : acceptHeaderCollection.Count()) + 2;

            mockCountingFormatter.Verify(v => v.CanWriteResult(context,
                                                               It.IsNotIn <MediaTypeHeaderValue>(mockCountingSupportedContentType)),
                                         Times.Exactly(callCount));
        }
Ejemplo n.º 23
0
        public async Task StopAsync_AlreadyRunning_ShouldCancelGetBlockAsync()
        {
            // Arrange.
            this.handler.GetBlockHintAsync(Arg.Any <CancellationToken>()).Returns(0);

            this.rpc.Setup(r => r.GetBlockAsync(0, It.IsAny <CancellationToken>()))
            .Callback <int, CancellationToken>((h, c) =>
            {
                c.WaitHandle.WaitOne();
                c.ThrowIfCancellationRequested();
            });

            var background = await this.subject.StartAsync(this.handler, CancellationToken.None);

            // Act.
            await this.subject.StopAsync(CancellationToken.None);

            // Assert.
            _ = this.handler.Received(1).GetBlockHintAsync(Arg.Any <CancellationToken>());
            this.rpc.Verify(r => r.GetBlockAsync(0, It.IsNotIn(CancellationToken.None)), Times.Once());
            _ = this.handler.Received(0).ProcessBlockAsync(Arg.Any <Block>(), Arg.Any <int>(), Arg.Any <CancellationToken>());

            this.subject.IsRunning.Should().BeFalse();
            background.IsCanceled.Should().BeTrue();
        }
Ejemplo n.º 24
0
        public void ShouldRemoveUserInMemory()
        {
            var user = new User()
            {
                Email          = "*****@*****.**",
                Guid           = System.Guid.NewGuid().ToString(),
                HashedPassword = "******",
                Name           = "name",
                Role           = "admin",
                Surname        = "dksk"
            };

            var mockSet = new MockDbSet <User>();

            var mockContext = new Mock <WorkSiteDbContext>();

            mockContext.Setup(c => c.Set <User>()).Returns(mockSet.Object);

            using (var uow = new WorkSiteUow(mockContext.Object))
            {
                uow.Users.Create(user);
                uow.Save();
                uow.Users.Delete(user.Guid);
                uow.Save();
            }

            mockSet.Verify(u => u.Remove(It.IsNotIn(user)), Times.Never);
        }
        private IPolysurfaceVertex MockVertex(int index)
        {
            if (!_mockVertices.ContainsKey(index))
            {
                var answer = new Mock <IPolysurfaceVertex>();

                _mockVertices.Add(index, answer.Object);

                var edges = new List <IPolysurfaceEdge>
                {
                    MockEdge(index),
                    MockEdge((index + 1) % _numIndices)
                };

                answer.Setup(v => v.Edges).Returns(edges);
                answer.Setup(v => v.Point).Returns(MockVertexPoint(index));
                answer.Setup(v => v.Order).Returns(index);

                answer.Setup(v => v.Equals(answer.Object)).Returns(true);
                answer.Setup(v => v.Equals(It.IsNotIn(answer.Object))).Returns(false);
                answer.Setup(v => v.GetHashCode()).Returns(index);
            }

            return(_mockVertices[index]);
        }
Ejemplo n.º 26
0
        public void ExistingSpeler_Join_NotExistingTeam()
        {
            var spelerMock = new Mock <ISpelerRepository>();
            var sessieMock = new Mock <ISessionRepository>();
            var teamMock   = new Mock <ITeamRepository>();
            var puzzelMock = new Mock <IPuzzelRepository>();

            teamMock.Setup(t => t.GetTeams()).Returns(_fakeTeamRepo.GetTeams());
            teamMock.Setup(t => t.GetTeam(1)).Returns(_fakeTeamRepo.GetTeam(1));
            teamMock.Setup(t => t.GetTeam(It.IsNotIn(1))).Returns((Team)null);
            sessieMock.Setup(s => s.GetSessie(1)).Returns(_fakeSessieRepo.GetSessie(1));
            spelerMock.Setup(s => s.GetSpeler(It.IsIn(1, 2, 3, 4, 5))).Returns((int i) => _fakeSpelerRepo.GetSpeler(i));
            spelerMock.Setup(s => s.GetSpeler(It.IsNotIn(1, 2, 3, 4, 5))).Returns((Speler)null);
            var team = new TeamService(teamMock.Object,
                                       spelerMock.Object,
                                       sessieMock.Object,
                                       puzzelMock.Object);
            //Arrange
            var teamId   = 9999;
            var spelerId = 2;

            // Act
            bool result = team.SpelerJoin(spelerId, teamId);

            // Assert
            Assert.False(result);
        }
        private void SetupSearchResultMock()
        {
            var facetGroupMock = new Mock <ISearchFacetGroup>();

            facetGroupMock.Setup(x => x.Name).Returns("FacetGroupName");
            facetGroupMock.Setup(x => x.FieldName).Returns("FacetGroupFieldName");
            _facet = new Facet(facetGroupMock.Object, "FacetKey", "FacetName", 10);
            var facetList = new ISearchFacet[] { _facet };

            facetGroupMock.Setup(x => x.Facets).Returns(() => facetList);

            var searchDocumentMock = new Mock <ISearchDocument>();

            searchDocumentMock.Setup(x => x["displayname"])
            .Returns(() => new SearchField("displayname", "DisplayName"));
            searchDocumentMock.Setup(x => x["image_url"])
            .Returns(() => new SearchField("image_url", "/image.jpg"));      // Tests will ensures that hostname gets removed
            searchDocumentMock.Setup(x => x["content_link"])
            .Returns(() => new SearchField("content_link", "1"));
            searchDocumentMock.Setup(x => x[It.IsNotIn(new[] { "displayname", "image_url", "content_link" })])
            .Returns(() => new SearchField("name", ConvertToPrefixCodedLong(1m)));

            searchDocumentMock.Setup(x => x["brand"]).Returns(() => new SearchField("brand", "Brand"));
            searchDocumentMock.Setup(x => x["code"]).Returns(() => new SearchField("code", "Code"));

            _searchResultsMock = new Mock <ISearchResults>();
            _searchResultsMock.Setup(x => x.FacetGroups).Returns(() => new[] { facetGroupMock.Object });

            _searchResultsMock.Setup(x => x.Documents)
            .Returns(() => new SearchDocuments {
                searchDocumentMock.Object
            });
        }
Ejemplo n.º 28
0
        public void GetActive_Puzzel_existingTeam()
        {
            var _LocalfakeTeamRepo = new TeamRepositoryFake();
            var spelerMock         = new Mock <ISpelerRepository>();
            var sessieMock         = new Mock <ISessionRepository>();
            var teamMock           = new Mock <ITeamRepository>();
            var puzzelMock         = new Mock <IPuzzelRepository>();

            teamMock.Setup(t => t.GetTeams()).Returns(_LocalfakeTeamRepo.GetTeams());
            teamMock.Setup(t => t.GetTeam(It.IsIn(1, 2))).Returns((int id) => { return(GameDBFake.teams.Where(g => g.Id == id).FirstOrDefault()); });
            teamMock.Setup(t => t.GetTeam(It.IsNotIn(1, 2))).Returns((Team)null);
            teamMock.Setup(t => t.GetActivePuzzel(2)).Returns((int id) => { return(GameDBFake.teams.Where(g => g.Id == id).FirstOrDefault().ActivePuzzel); });
            teamMock.Setup(t => t.GetActivePuzzel(1)).Returns((int id) => { return(-1); });
            puzzelMock.Setup(p => p.GetPuzzel(It.IsAny <int>())).Returns(new Puzzel());
            var team = new TeamService(teamMock.Object,
                                       spelerMock.Object,
                                       sessieMock.Object,
                                       puzzelMock.Object);
            //Arrange
            var teamIdActive    = 2; //team 2 is bezig met een actieve puzzel
            var teamIdNotActive = 1; //team1 is niet bezig met een puzzel

            // Act
            var resultActive    = team.ActivePuzzel(teamIdActive);
            var resultNotActive = team.ActivePuzzel(teamIdNotActive);
            var activepuzzelID  = team.GetActivePuzzel(1);

            // Assert
            Assert.IsType <Puzzel>(resultActive);
            Assert.Equal(-1, activepuzzelID);
            Assert.Null(resultNotActive);
        }
Ejemplo n.º 29
0
        public void SetupCheckpoints(params CheckpointFixture[] checkpoints)
        {
            if (checkpoints.GroupBy(h => h.Height).Any(g => g.Count() > 1))
            {
                throw new ArgumentException("Checkpoint heights must be unique.");
            }

            if (checkpoints.Any(h => h.Height < 0))
            {
                throw new ArgumentException("Checkpoint heights cannot be negative.");
            }

            foreach (CheckpointFixture checkpoint in checkpoints.OrderBy(h => h.Height))
            {
                var checkpointInfo = new CheckpointInfo(checkpoint.Header.GetHash());
                this.checkpoints
                .Setup(c => c.GetCheckpoint(checkpoint.Height))
                .Returns(checkpointInfo);
            }

            this.checkpoints
            .Setup(c => c.GetCheckpoint(It.IsNotIn(checkpoints.Select(h => h.Height))))
            .Returns((CheckpointInfo)null);

            this.checkpoints
            .Setup(c => c.GetLastCheckpointHeight())
            .Returns(checkpoints.OrderBy(h => h.Height).Last().Height);

            this.checkpoints
            .Setup(c => c.LastCheckpointHeight)
            .Returns(checkpoints.OrderBy(h => h.Height).Last().Height);
        }
Ejemplo n.º 30
0
        public Task StartAsync_WhenExecuteAsyncThrow_ShouldInvokeExceptionHandler()
        {
            return(AsynchronousTesting.WithCancellationTokenAsync(async cancellationToken =>
            {
                // Arrange.
                this.subject.StubbedExecuteAsync
                .Setup(f => f(It.IsAny <CancellationToken>()))
                .ThrowsAsync(new Exception());

                // Act.
                await this.subject.StartAsync(cancellationToken);
                await this.subject.StopAsync(CancellationToken.None);

                // Assert.
                this.subject.StubbedExecuteAsync.Verify(
                    f => f(It.IsNotIn(cancellationToken, CancellationToken.None)),
                    Times.Once()
                    );

                this.subject.StubbedPostExecuteAsync.Verify(
                    f => f(CancellationToken.None),
                    Times.Once()
                    );

                this.exceptionHandler.Verify(
                    h => h.RunAsync(this.subject.GetType(), It.Is <Exception>(ex => ex != null), CancellationToken.None),
                    Times.Once()
                    );
            }));
        }