protected AppendEntryBaseTest()
        {
            // Arrange  
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();

            mocker.Use(ServerIdentifier);

            mocker.Setup<ISubject<AppendEntryMessage>>(p => p.Subscribe(It.IsAny<IObserver<AppendEntryMessage>>()))
                .Callback<IObserver<AppendEntryMessage>>((o) =>
                {
                    AppendEntryCallback = o;
                });
            AppendEntryCallback = mocker.Get<ISubject<AppendEntryMessage>>();

            AppendEntryResult = new Subject<AppendEntryResultMessage>();
            Election = new Election();
            LogReplication = new LogReplication();
            
            AppendEntry = new Rafting.AppendEntry(AppendEntryResult,
                mocker.Get<ISubject<AppendEntryMessage>>(),
                mocker.Get<IHartbeatTimer>(),
                LogReplication,
                Election,
                mocker.Get<ILoggerFactory>(),
                new RaftOptions(),
                mocker.Get<ServerIdentifier>(),
                null);
        }
Exemplo n.º 2
1
        public void DisposeAndStateDoesNotChangeAfterHartbeatTest()
        {
            var mocker = new AutoMocker();
            var serverIdentifier = new ServerIdentifier();

            mocker.Use(serverIdentifier);

            var options = new RaftOptions();
            options.Hartbeat.FromMilliseconds = 50;
            options.Hartbeat.ToMilliseconds = 50;

            var timer = new HartbeatTimer(options, mocker.Get<ILoggerFactory>(), serverIdentifier);
            var state = ServerStateType.Leader;

            var dispose = timer.Subscribe((s) =>
            {
                state = s;
            });

            dispose.Dispose();

            Thread.Sleep(100);

            Assert.Equal(ServerStateType.Leader, state);
        }
        public void WHEN_facet_is_not_configured_in_SearchConfiguration_FacetSetting_SHOULD_return_Null()
        {
            //Arrange
            var registry     = _container.Get <IFacetProviderRegistry>();
            var providerName = GetRandom.String(15);

            registry.RegisterProvider(providerName, typeof(FakeFacetProvider));

            var mockResolver = _container.GetMock <IDependencyResolver>();

            mockResolver.Setup(dr => dr.Resolve(It.IsNotNull <Type>()))
            .Returns(new FakeFacetProvider());

            var sut   = _container.CreateInstance <FacetFactory>();
            var facet = new Facet {
                FieldName = GetRandom.String(5)
            };
            var selectedFacets = new List <SearchFilter>();
            var cultureInfo    = new CultureInfo(CultureName);

            //Act
            var result = sut.CreateFacet(facet, selectedFacets, cultureInfo);

            //Assert
            result.Should().BeNull();
        }
Exemplo n.º 4
0
        public void WhenDependencyResolverIsSpecifiedItInstance()
        {
            var mocker          = new AutoMocker();
            var service1        = mocker.Get <IService>();
            var service2        = mocker.Get <IService2>();
            var service3        = mocker.Get <IService3>();
            var serviceProvider = mocker.GetMock <IServiceProvider>();

            serviceProvider.Setup(x => x.GetService(typeof(IService))).Returns(service1).Verifiable();
            serviceProvider.Setup(x => x.GetService(typeof(IService2))).Returns(service2).Verifiable();
            serviceProvider.Setup(x => x.GetService(typeof(IService3))).Returns(service3).Verifiable();

            DI.Dispose(typeof(ClassWithDependencies).Assembly);
            DI.Init(typeof(IService).Assembly, builder =>
            {
                builder.WithProvider(serviceProvider.Object);
            });

            var sut = new ClassWithDependencies();

            Assert.AreEqual(service1, sut.Service);
            Assert.AreEqual(service2, sut.Service2);
            Assert.AreEqual(service3, sut.Service3);
            serviceProvider.Verify();
        }
Exemplo n.º 5
0
        public void WHEN_passing_valid_arguments_SHOULD_create_viewmodel()
        {
            //Arrange
            var expectedStatus = TestingExtensions.GetRandomEnum <MyAccountStatus>();
            var param          = new GetLoginViewModelParam
            {
                Status            = expectedStatus,
                CultureInfo       = TestingExtensions.GetRandomCulture(),
                Customer          = MockCustomerFactory.CreateRandom(),
                ReturnUrl         = GetRandom.WwwUrl(),
                LoginUrl          = GetRandom.WwwUrl(),
                CreateAccountUrl  = GetRandom.WwwUrl(),
                ForgotPasswordUrl = GetRandom.WwwUrl(),
                Username          = GetRandom.String(32)
            };
            var membershipViewService = _container.CreateInstance <MembershipViewService>();

            membershipViewService.Membership = _container.Get <IMembershipProxy>();

            //Act
            var viewModel = membershipViewService.GetLoginViewModel(param);

            //Assert
            viewModel.Should().NotBeNull("This view model should never be null");
            viewModel.Status.Should().Be(expectedStatus.ToString("G"), "Because we render the status as a string for HBS message switch");
            viewModel.ReturnUrl.Should().Be(param.ReturnUrl);
            viewModel.CreateAccountUrl.Should().Be(param.CreateAccountUrl);
            viewModel.ForgotPasswordUrl.Should().Be(param.ForgotPasswordUrl);
            viewModel.LoginUrl.Should().Be(param.LoginUrl);
            viewModel.FirstName.Should().Be(param.Customer.FirstName);
            viewModel.LastName.Should().Be(param.Customer.LastName);
        }
        public void CorrectSlotTheory(bool[] slotsClosed, int?nextSlot)
        {
            var sensors = new List <IDigitalSensor>();
            var slots   = new List <FeedingSlot>();

            for (int i = 0; i < slotsClosed.Length; i++)
            {
                var sensor = new Mock <IDigitalSensor>();
                sensor.Setup(s => s.Read()).Returns(slotsClosed[i]).Verifiable();
                sensors.Add(sensor.Object);

                slots.Add(new FeedingSlot(i.ToString(),
                                          _mocker.Get <IGateDevice>(),
                                          sensor.Object,
                                          slots,
                                          _mocker.Get <IThingsResource>()));
            }

            var manager = _mocker.CreateInstance <DefaultFeedingManager>();

            manager.Slots = slots;

            var result = manager.NextFeedingSlot();

            _mocker.VerifyAll();

            if (nextSlot.HasValue)
            {
                Assert.Equal(nextSlot.Value.ToString(), result.Name);
            }
            else
            {
                Assert.Null(result);
            }
        }
Exemplo n.º 7
0
        public async Task GetSelfUserAsync_WhenReadyIsNotComplete_WaitsForWhenReady()
        {
            var autoMocker = new AutoMocker();

            var whenReadySource = new TaskCompletionSource <object>();

            autoMocker.GetMock <IReadySynchronizationProvider>()
            .Setup(x => x.WhenReady)
            .Returns(() => whenReadySource.Task);

            var selfUser = autoMocker.Get <ISocketSelfUser>();

            autoMocker.GetMock <IDiscordSocketClient>()
            .Setup(x => x.CurrentUser)
            .Returns(() => autoMocker.Get <ISocketSelfUser>());

            var uut = autoMocker.CreateInstance <SelfUserProvider>();

            var result = uut.GetSelfUserAsync();

            result.IsCompleted.ShouldBeFalse();

            whenReadySource.SetResult(null);
            await result;

            result.IsCompleted.ShouldBeTrue();
            result.Result.ShouldBeSameAs(selfUser);
        }
Exemplo n.º 8
0
        public CandidateBaseTests()
        {
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();
            mocker.Use(ServerIdentifier);


            Election = new Election();
            RequestVoteResult = new Subject<RequestVoteResultMessage>();
            RequestVote = new Subject<RequestVoteMessage>();
            MockVotingSystem = mocker.GetMock<IVotingSystem>();


            Candidate = new Rafting.States.Candidate(mocker.Get<ServerIdentifier>(),
                mocker.Get<IElectionTimer>(),
                RequestVote,
                RequestVoteResult,
                MockVotingSystem.Object,
                Election,
                mocker.Get<ILogReplication>(),
                mocker.Get<Nodes>(),
                mocker.Get<ILoggerFactory>(),
                new RaftOptions());
        }
Exemplo n.º 9
0
            public void You_can_setup_a_mock_using_the_classic_Setup_style()
            {
                mocker.Setup <IService2>(x => x.Other).Returns(Mock.Of <IService1>());
                var mock = mocker.Get <IService2>();

                mock.ShouldNotBeNull();
                mock.Other.ShouldNotBeNull();
            }
        public void ConstructorParametersCanBeMocked()
        {
            var mocker = new AutoMocker();
            var sut    = mocker.CreateInstance <ClassWithDependencies>();

            Assert.AreEqual(mocker.Get <IService>(), sut.Service);
            Assert.AreEqual(mocker.Get <IService2>(), sut.Service2);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Get <see cref="FeedingSlot"/>
 /// </summary>
 /// <param name="mocker">Instance of <see cref="AutoMocker"/></param>
 /// <param name="name">Name of the slot</param>
 /// <param name="sensor">The sensor to link with the <see cref="FeedingSlot"/></param>
 /// <returns></returns>
 public static FeedingSlot GetSlotWithSensor(this AutoMocker mocker, string name, Mock <IDigitalSensor> sensor)
 {
     return(new FeedingSlot(name,
                            mocker.Get <IGateDevice>(),
                            sensor.Object,
                            Enumerable.Empty <FeedingSlot>(),
                            mocker.Get <IThingsResource>()));
 }
        public void Convenience_methods_work()
        {
            var mocker = new AutoMocker();

            mocker.Combine <IService1, IService2, IService3>();

            Assert.AreSame(mocker.Get <IService2>(), mocker.Get <IService1>());
            Assert.AreSame(mocker.Get <IService3>(), mocker.Get <IService2>());
        }
        public void Combine_method_should_maintain_setups()
        {
            var mocker = new AutoMocker(MockBehavior.Loose);

            mocker.GetMock <IDerivedInterface>().Setup(x => x.Foo()).Returns(() => "42");
            mocker.Combine(typeof(IDerivedInterface), typeof(IBaseInterface));

            Assert.AreEqual("42", mocker.Get <IBaseInterface>().Foo());
            Assert.AreEqual("42", mocker.Get <IDerivedInterface>().Foo());
        }
Exemplo n.º 14
0
            public void It_extracts_instances_that_were_placed_with_Use()
            {
                var setupInstance = Mock.Of <IService1>();

                mocker.Use(setupInstance);

                var actualInstance = mocker.Get <IService1>();

                actualInstance.ShouldBeSameAs(setupInstance);
            }
        public void It_uses_the_same_mock_for_all_instances()
        {
            var mocker = new AutoMocker();

            mocker.Combine(typeof(IService1), typeof(IService2),
                           typeof(IService3));

            Assert.AreSame(mocker.Get <IService2>(), mocker.Get <IService1>());
            Assert.AreSame(mocker.Get <IService3>(), mocker.Get <IService2>());
        }
Exemplo n.º 16
0
        public void ConstructorParametersCanBeMocked()
        {
            var mocker = new AutoMocker();
            var sut    = mocker.CreateInstance <ClassWithDependencies>();

            Assert.AreEqual(mocker.Get <IService>(), sut.Service);
            Assert.AreEqual(mocker.Get <IService2>(), sut.Service2);
            //Property wont resolve because there is no resolver specified
            Assert.IsNull(sut.Service3);
        }
Exemplo n.º 17
0
            public void It_extracts_instances_that_were_placed_with_Use()
            {
                var setupInstance = Mock.Of <IService1>();

                mocker.Use(setupInstance);

                var actualInstance = mocker.Get <IService1>();

                Assert.AreSame(setupInstance, actualInstance);
            }
Exemplo n.º 18
0
            public void You_can_verify_a_method_that_returns_a_value_type()
            {
                mocker.Setup <IServiceWithPrimitives, long>(s => s.ReturnsALong()).Returns(100L);

                var mock = mocker.Get <IServiceWithPrimitives>();

                mock.ReturnsALong().ShouldEqual(100L);

                mocker.Verify <IServiceWithPrimitives, long>(s => s.ReturnsALong(), Times.Once());
            }
Exemplo n.º 19
0
        public void Init()
        {
            var mocker = new AutoMocker();

            var machine = new Machine<State, Trigger>(State.First,
                mocker.Get<ILoggerFactory>(),
                mocker.Get<IObservableProvider>());

            machine.On(State.First).
                OnEntry(() =>
                {
                    Assert.Equal(State.First, machine.State);

                    System.Console.WriteLine($"first {machine.State}");
                })
                .Permit(Trigger.ChangeToSecond, State.Second)
                .Permit(Trigger.ChangeToFirst, State.First);

            machine.On(State.Second).
                OnEntry(() =>
                {
                    Assert.Equal(State.Second, machine.State);

                    System.Console.WriteLine($"second {machine.State}");
                })
                .Permit(Trigger.ChangeToSecond, State.Second)
                .Permit(Trigger.ChangeToThird, State.Third);

            machine.On(State.Third).
                OnEntry(() =>
                {
                    Assert.Equal(State.Third, machine.State);
                });

            machine.OnNext(Trigger.ChangeToFirst);

            Assert.Equal(State.First, machine.State);

            machine.OnNext(Trigger.ChangeToThird);

            Assert.Equal(State.First, machine.State);

            machine.OnNext(Trigger.ChangeToSecond);

            Assert.Equal(State.Second, machine.State);

            machine.OnNext(Trigger.ChangeToThird);

            Assert.Equal(State.Third, machine.State);

            machine.OnNext(Trigger.ChangeToFirst);


        }
Exemplo n.º 20
0
        public void UseConcreteClassFor()
        {
            AutoMocker <ConcreteClass> mocker = createAutoMocker <ConcreteClass>();

            mocker.UseConcreteClassFor <ConcreteThing>();

            var thing = mocker.Get <ConcreteThing>();

            thing.ShouldBeOfType <ConcreteThing>();

            Assert.AreSame(mocker.Get <IMockedService>(), thing.Service);
            Assert.AreSame(mocker.Get <IMockedService2>(), thing.Service2);
        }
Exemplo n.º 21
0
        public void UseConcreteClassFor()
        {
            AutoMocker <ConcreteClass> mocker = createAutoMocker <ConcreteClass>();

            mocker.UseConcreteClassFor <ConcreteThing>();

            var thing = mocker.Get <ConcreteThing>();

            Assert.IsInstanceOfType(typeof(ConcreteThing), thing);

            Assert.AreSame(mocker.Get <IMockedService>(), thing.Service);
            Assert.AreSame(mocker.Get <IMockedService2>(), thing.Service2);
        }
Exemplo n.º 22
0
        public async Task CreateTag_TagAlreadyExistsWithSameCasing_Throws()
        {
            var botContext = _autoMocker.Get <BotContext>();
            await botContext.Tags.AddAsync(new TagEntity()
            {
                Name = "tag"
            });

            await botContext.SaveChangesAsync();

            await Assert.ThrowsAsync <InvalidOperationException>(
                () => _tagService.CreateTagAsync(0, 0, "tag", "content"));
        }
Exemplo n.º 23
0
            public void It_uses_the_same_mock_for_all_instances()
            {
                mocker.Combine(typeof(IService1), typeof(IService2),
                               typeof(IService3));

                Assert.Same(mocker.Get <IService2>(), mocker.Get <IService1>());
                Assert.Same(mocker.Get <IService3>(), mocker.Get <IService2>());
            }
Exemplo n.º 24
0
        public void TheAutoMockerPushesInMocksForAllOfTheConstructorArgumentsForAPartialMock()
        {
            AutoMocker <ConcreteClass> autoMocker = createAutoMocker <ConcreteClass>();

            var service  = autoMocker.Get <IMockedService>();
            var service2 = autoMocker.Get <IMockedService2>();
            var service3 = autoMocker.Get <IMockedService3>();

            autoMocker.PartialMockTheClassUnderTest();
            ConcreteClass concreteClass = autoMocker.ClassUnderTest;

            Assert.AreSame(service, concreteClass.Service);
            Assert.AreSame(service2, concreteClass.Service2);
            Assert.AreSame(service3, concreteClass.Service3);
        }
Exemplo n.º 25
0
        public void ResolvesFuncReturningDefinedParameter(Type delegateType, object expected)
        {
            if (delegateType is null)
            {
                throw new ArgumentNullException(nameof(delegateType));
            }
            if (expected is null)
            {
                throw new ArgumentNullException(nameof(expected));
            }

            var mocker = new AutoMocker {
                Resolvers = { new FuncResolver() }
            };

            mocker.Use(expected.GetType(), expected);

            var func = (Delegate)mocker.Get(delegateType) !;

            Assert.IsNotNull(func);

            var @params = new object[delegateType.GetGenericArguments().Length - 1];

            Assert.AreEqual(expected, func.DynamicInvoke(@params));
        }
Exemplo n.º 26
0
        public void It_Returns_Achievement_Details_For_The_Current_User()
        {
            //--arrange
            var achievementId = AchievementId.BusyBee;
            var expectedPlayerAchievementDetails = new PlayerAchievementDetails();

            AutoMocker.Get <IPlayerAchievementRetriever>().Expect(mock => mock.GetPlayerAchievement(Arg <PlayerAchievementQuery> .Is.Anything))
            .Return(expectedPlayerAchievementDetails);
            var expectedPlayerAchievementViewModel = new PlayerAchievementViewModel();

            AutoMocker.Get <ITransformer>().Expect(mock => mock.Transform <PlayerAchievementViewModel>(expectedPlayerAchievementDetails))
            .Return(expectedPlayerAchievementViewModel);

            //--act
            var viewResult = AutoMocker.ClassUnderTest.DetailsForCurrentUser(achievementId, CurrentUser) as ViewResult;

            //--assert
            viewResult.ShouldNotBeNull();
            viewResult.ViewName.ShouldBe(MVC.Achievement.Views.Details);
            var firstCall =
                AutoMocker.Get <IPlayerAchievementRetriever>()
                .GetArgumentsForCallsMadeOn(x => x.GetPlayerAchievement(Arg <PlayerAchievementQuery> .Is.Anything));
            var query = firstCall.AssertFirstCallIsType <PlayerAchievementQuery>();

            query.AchievementId.ShouldBe(achievementId);
            query.ApplicationUserId.ShouldBe(CurrentUser.Id);
            query.GamingGroupId.ShouldBe(CurrentUser.CurrentGamingGroupId);
            var playerAchievementViewModel = viewResult.Model as PlayerAchievementViewModel;

            playerAchievementViewModel.ShouldBe(expectedPlayerAchievementViewModel);
        }
        public void It_Sets_The_WinnerType_Based_On_The_Ranks_Of_The_Players()
        {
            //--arrange
            var playerGameResults = new List <PlayerGameResult>
            {
                new PlayerGameResult
                {
                    GameRank = 1
                },
                new PlayerGameResult
                {
                    GameRank = 2
                }
            };
            var expectedWinnerType = WinnerTypes.TeamLoss;

            AutoMocker.Get <IWinnerTypeCalculator>()
            .Expect(mock => mock.CalculateWinnerType(Arg <IList <int> > .Is.Anything)).Return(expectedWinnerType);

            //--act
            var result = AutoMocker.ClassUnderTest.TransformNewlyCompletedGameIntoPlayedGame(new NewlyCompletedGame(), GAMING_GROUP_ID, CurrentUser.Id, playerGameResults);

            //--assert
            var arguments = AutoMocker.Get <IWinnerTypeCalculator>()
                            .GetArgumentsForCallsMadeOn(mock => mock.CalculateWinnerType(Arg <IList <int> > .Is.Anything));
            var gameRanks = arguments.AssertFirstCallIsType <IList <int> >();

            gameRanks.ShouldContain(playerGameResults[0].GameRank);
            gameRanks.ShouldContain(playerGameResults[1].GameRank);
            result.WinnerType.ShouldBe(expectedWinnerType);
        }
Exemplo n.º 28
0
        public async Task DeleteTag_OwnerIdDoesntMatch_Throws()
        {
            var botContext = _autoMocker.Get <BotContext>();

            var entity = new TagEntity()
            {
                Name    = "name",
                OwnerId = 0
            };
            await botContext.Tags.AddAsync(entity);

            await botContext.SaveChangesAsync();

            await Assert.ThrowsAsync <InvalidOperationException>(
                () => _tagService.DeleteTagAsync(0, 1, "name"));
        }
        public void It_creates_a_mock_if_the_object_is_missing_using_Get()
        {
            var mocker = new AutoMocker();
            var mock   = mocker.Get <IService1>();

            Assert.IsNotNull(mock);
        }
Exemplo n.º 30
0
        public async Task DeleteAccount_PostsNotification()
        {
            //Arrange
            var mocker  = new AutoMocker().WithMessenger();
            var watcher = new MessageWatcher <DatabaseEvent <Account> >();

            mocker.Get <IMessenger>().Register(watcher);
            using var factory = mocker.WithDbScope();

            var account1 = new Account();

            using var setupContext = factory.Create();
            setupContext.Accounts.Add(account1);
            await setupContext.SaveChangesAsync();

            //Act
            using var actContext = factory.Create();
            var account = await actContext.Accounts.FindAsync(account1.ID);

            actContext.Accounts.Remove(account);
            await actContext.SaveChangesAsync();

            //Assert
            DatabaseEvent <Account>?message = watcher.Messages.Last();

            Assert.AreEqual(account1.ID, message.Item.ID);
            Assert.AreEqual(EventType.Deleted, message.Type);
        }
        public override void SetUp()
        {
            base.SetUp();

            gamingGroupList = new List <GamingGroup>
            {
                new GamingGroup
                {
                    Id = gamingGroupId1,
                    UserGamingGroups = new List <UserGamingGroup>
                    {
                        new UserGamingGroup
                        {
                            ApplicationUserId = CurrentUser.Id
                        }
                    }
                },
                new GamingGroup
                {
                    Id = gamingGroupId2,
                    UserGamingGroups = new List <UserGamingGroup>
                    {
                        new UserGamingGroup
                        {
                            ApplicationUserId = "some other application id"
                        }
                    }
                }
            };

            AutoMocker.Get <IDataContext>().Expect(mock => mock.GetQueryable <GamingGroup>())
            .Return(gamingGroupList.AsQueryable());
        }
Exemplo n.º 32
0
        public void UseTheAutoMockerToStartUpTheConcreteClass()
        {
            AutoMocker <ConcreteClass> autoMocker = createAutoMocker <ConcreteClass>();

            setExpectation(autoMocker.Get <IMockedService>(), x => x.Name, "Jeremy");
            autoMocker.ClassUnderTest.Name.ShouldEqual("Jeremy");
        }
Exemplo n.º 33
0
        public override void SetUp()
        {
            base.SetUp();

            var notExistingPlayerName = "not exists";

            Request.PlayerRanks = new List <CreatePlayerRankRequest>
            {
                new CreatePlayerRankRequest
                {
                    GameRank   = 1,
                    PlayerId   = 1,
                    PlayerName = "existing player"
                },
                new CreatePlayerRankRequest
                {
                    GameRank   = 2,
                    PlayerName = notExistingPlayerName
                }
            };

            AutoMocker.Get <IPlayerSaver>()
            .Expect(
                x =>
                x.CreatePlayer(
                    Arg <CreatePlayerRequest> .Matches(
                        m => m.Name == notExistingPlayerName), Arg <ApplicationUser> .Is.Equal(CurrentUser), Arg <bool> .Is.Anything))
            .Repeat.Once().Return(new Player {
                Id = 2
            });
        }
Exemplo n.º 34
0
        public void TheAutoMockerPushesInMocksAndAPreBuiltStubForAllOfTheConstructorArguments()
        {
            AutoMocker <ConcreteClass> autoMocker = createAutoMocker <ConcreteClass>();
            var stub = new StubService();

            autoMocker.Inject <IMockedService>(stub);

            var service2 = autoMocker.Get <IMockedService2>();
            var service3 = autoMocker.Get <IMockedService3>();

            ConcreteClass concreteClass = autoMocker.ClassUnderTest;

            Assert.AreSame(stub, concreteClass.Service);
            Assert.AreSame(service2, concreteClass.Service2);
            Assert.AreSame(service3, concreteClass.Service3);
        }
Exemplo n.º 35
0
        public void TestGetCloudantSecurityDocument_Should_Return_A_Valid_Document()
        {
            //SETUP
            var mocker = new AutoMocker();

            //connection returns base uri
            mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost"));

            //GetCouchResponse returns security doc as per Cloudant documentation
            const string responseString = "{ " +
                                          "\"_id\":\"_security\"," +
                                          "\"cloudant\":" +
                                          "{" +
                                          "  \"userwithreadonlyaccess\": [" +
                                          "    \"_reader\"" +
                                          "  ]," +
                                          "  \"userwithreadandwriteaccess\": [" +
                                          "    \"_reader\"," +
                                          "    \"_writer\"" +
                                          "  ]" +
                                          "}," +
                                          "\"ok\":true" +
                                          "}";
            mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString);
            mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK);
            mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>());

            //couchFactory returns request
            mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>()))
                .Returns(mocker.Get<ICouchRequest>());
            //Get request returns request
            mocker.Setup<ICouchRequest>(r => r.Get()).Returns(mocker.Get<ICouchRequest>());
            //Json content type returns request
            mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>());

            //TEST
            var database = mocker.CreateInstance<CloudantDatabase>();

            var securityDocument = (CloudantSecurityDocument)database.GetSecurityDocument();

            securityDocument.Id.Should().Be("_security");
            securityDocument.CloudantSecuritySection.GetAssignment("userwithreadonlyaccess").Should().BeEquivalentTo("_reader");
            securityDocument.CloudantSecuritySection.GetAssignment("userwithreadandwriteaccess").Should().BeEquivalentTo("_reader", "_writer");
            securityDocument.Ok.Should().BeTrue();

            mocker.VerifyAll();
        }
        protected VoteReceivedBaseTests()
        {
            // Arrange
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();

            mocker.Use(ServerIdentifier);

            mocker.Setup<ISubject<RequestVoteMessage>>(p => p.Subscribe(It.IsAny<IObserver<RequestVoteMessage>>()))
                .Callback<IObserver<RequestVoteMessage>>((o) =>
                {
                    RequestVoteCallback = o;
                });
            RequestVoteCallback = mocker.Get<ISubject<RequestVoteMessage>>();

            Election = new Election();

            Message = new RequestVoteResultMessage();

            mocker.Setup<ISubject<RequestVoteResultMessage>>(p => p.OnNext(It.IsAny<RequestVoteResultMessage>()))
                .Callback<RequestVoteResultMessage>((o) =>
                {
                    Message = o;
                });

            VoteReceived = new Rafting.VoteReceived(mocker.Get<ISubject<RequestVoteResultMessage>>(),
                mocker.Get<ServerIdentifier>(),
                mocker.Get<ISubject<RequestVoteMessage>>(),
                Election,
                mocker.Get<ILoggerFactory>(),
                new Nodes(),
                new RaftOptions(),
                mocker.Get<ILogReplication>());
        }
Exemplo n.º 37
0
        public void ChangeStates()
        {
            // Arrange
            var mocker = new AutoMocker();
            mocker.Setup<IHartbeatTimer>(p => p.Reset()).Callback(() =>
            {

            });

            var mockFollower = mocker.GetMock<Follower>();
            var mockCandidate = mocker.GetMock<Candidate>();
            var mockLeader = mocker.GetMock<Leader>();

            mocker.Setup<IObservableProvider>(p =>  p.GetObservable<Follower, ServerStateType>())
                .Returns(mockFollower.Object);

            mocker.Setup<IObservableProvider>(p => p.GetObservable<Candidate, ServerStateType>())
                .Returns(mockCandidate.Object);

            mocker.Setup<IObservableProvider>(p => p.GetObservable<Leader, ServerStateType>())
                .Returns(mockLeader.Object);

            Machine<ServerStateType, ServerStateType> machine = null;
            mocker.Setup<IHartbeatTimer>(p => p.Subscribe(It.IsAny<Machine<ServerStateType, ServerStateType>>()))
                .Returns(new Disposable())
                .Callback<Machine<ServerStateType, ServerStateType>>(m =>
                {
                    machine = m;
                });
            
            var node = new Node(mocker.Get<IVoteReceived>(),
                mocker.Get<IAppendEntry>(),
                mocker.Get<IHartbeatTimer>(),
                mocker.Get<ILoggerFactory>(),
                mocker.Get<IObservableProvider>(),
                mocker.Get<ILogReplication>(),
                mocker.Get<ServerIdentifier>());

            var mockHartbeat = mocker.GetMock<IHartbeatTimer>();

            // Assert
            Assert.Equal(ServerStateType.Follower, node.State);

            machine.OnNext(ServerStateType.Candidate);

            Assert.Equal(ServerStateType.Candidate, node.State);

            machine.OnNext(ServerStateType.Leader);
        }
Exemplo n.º 38
0
        public void SubscribeTest()
        {
            var mocker = new AutoMocker();

            var serverIdentifier = new ServerIdentifier();

            mocker.Use(serverIdentifier);

            var options = new RaftOptions();
            options.Hartbeat.FromMilliseconds = 0;
            options.Hartbeat.ToMilliseconds = 0;

            var timer = new HartbeatTimer(options, mocker.Get<ILoggerFactory>(), serverIdentifier);
            var state = ServerStateType.Leader;

            timer.Subscribe((s) =>
            {
                state = s;    
            });

            Thread.Sleep(100);

            Assert.Equal(ServerStateType.Candidate, state);
        }
Exemplo n.º 39
0
        public void TestUpdateSecurityDoc_Should_Succeed_For_Valid_Document()
        {
            //SETUP
            var mocker = new AutoMocker();

            //connection returns base uri
            mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost"));

            //GetCouchResponse returns security doc as per Cloudant documentation
            const string responseString = "{ " +
                                          "\"ok\":true" +
                                          "}";
            mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString);
            mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK);
            mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>());

            //couchFactory returns request
            mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>()))
                .Returns(mocker.Get<ICouchRequest>());
            //Get request returns request
            mocker.Setup<ICouchRequest>(r => r.Put()).Returns(mocker.Get<ICouchRequest>());
            //Json content type returns request
            mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>());
            //Data returns request
            mocker.Setup<ICouchRequest>(r => r.Data(It.IsAny<string>())).Returns(mocker.Get<ICouchRequest>());

            //security doc
            var securityDoc = new CloudantSecurityDocument();
            securityDoc.CloudantSecuritySection.AddUser("user1", "_reader");
            securityDoc.CloudantSecuritySection.AddUser("user2", "_reader","_writer");

            //TEST
            var database = mocker.CreateInstance<CloudantDatabase>();

            database.UpdateSecurityDocument(securityDoc);

            mocker.VerifyAll();
        }
Exemplo n.º 40
-1
        public LeaderBaseTests()
        {
            var mocker = new AutoMocker();

            ServerIdentifier = new ServerIdentifier();
            mocker.Use(ServerIdentifier);

            Election = new Election();
            AppendEntryResult = new Subject<AppendEntryResultMessage>();
            AppendEntry = new Subject<AppendEntryMessage>();
            LogReplication = new LogReplication();
            Nodes = new Nodes();

            Leader = new Rafting.States.Leader(
                Election,
                mocker.Get<IHartbeatTimer>(),
                AppendEntryResult,
                AppendEntry,
                mocker.Get<IObserver<ClientResultMessage>>(),
                mocker.Get<IObservable<ClientMessage>>(),
                LogReplication,
                Nodes,
                mocker.Get<ILoggerFactory>(),
                new RaftOptions(),
                mocker.Get<ServerIdentifier>());
        }