示例#1
0
        public void UpdateWatchOptionsSetGetTest(string contractAddr, string rpc, string validatorAddr, string path)
        {
            IDockerControl         mdcc = new MockDockerControl();
            IConfigurationProvider cp   = new MockConfigProvider();
            IContractWrapper       cw   = new MockContractWrapper();

            UpdateWatchOptions watchOpts = new UpdateWatchOptions
            {
                RpcEndpoint           = rpc,
                ContractAddress       = contractAddr,
                ValidatorAddress      = validatorAddr,
                DockerStackPath       = path,
                DockerControl         = mdcc,
                ConfigurationProvider = cp,
                ContractWrapper       = cw,
                WaitTimeAfterUpdate   = 12345
            };

            Assert.Equal(rpc, watchOpts.RpcEndpoint);
            Assert.Equal(contractAddr, watchOpts.ContractAddress);
            Assert.Equal(validatorAddr, watchOpts.ValidatorAddress);
            Assert.Equal(path, watchOpts.DockerStackPath);

            Assert.Equal(mdcc, watchOpts.DockerControl);
            Assert.Equal(cw, watchOpts.ContractWrapper);
            Assert.Equal(cp, watchOpts.ConfigurationProvider);
            Assert.Equal(12345, watchOpts.WaitTimeAfterUpdate);
        }
            public void SetupCalculatorTrolleyApiResult(TrolleyInfo trolleyInfo, decimal calculatedTotal)
            {
                var responseHttpContent = JsonConvert.SerializeObject(calculatedTotal);
                var apiUrl = "http://apihost/api/resource/trolleycalulator";
                var token  = "TestToken";

                MockSerializer
                .Setup(o => o.Serialize(trolleyInfo))
                .Returns <TrolleyInfo>(t => JsonConvert.SerializeObject(t));

                MockExternalApiPathProvider
                .Setup(o => o.GetApiPath(ExternalApiPathName.CalculateTrolley))
                .Returns(apiUrl);

                MockConfigProvider
                .Setup(o => o.GetConfigValue(ConfigKeys.Token))
                .Returns(token);

                var apiRequestUrl = $"{apiUrl}?token={token}";
                var jsonMimeType  = "application/json";

                MockMessageHandler
                .When(HttpMethod.Post, apiRequestUrl)
                .WithContent(JsonConvert.SerializeObject(trolleyInfo))
                .WithHeaders("Content-Type", jsonMimeType)
                .Respond(jsonMimeType, responseHttpContent);
            }
示例#3
0
        public void ShouldGenerateNoActionsOnSameState()
        {
            MockConfigProvider cp = new MockConfigProvider {
                CurrentState = new NodeState
                {
                    IsSigning             = true,
                    DockerImage           = "parity/parity:v2.3.4",
                    DockerChecksum        = "9f0142e1ae1641fbcf6116c49b5c73d5a4b48340e07f9ecb4da8d2d9847a76e6",
                    ChainspecUrl          = "https://foo.bar",
                    ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                    UpdateIntroducedBlock = 1234567
                }
            };

            // Recreate the same state so state object references are different
            NodeState newState = new NodeState
            {
                IsSigning             = true,
                DockerImage           = "parity/parity:v2.3.4",
                DockerChecksum        = "9f0142e1ae1641fbcf6116c49b5c73d5a4b48340e07f9ecb4da8d2d9847a76e6",
                ChainspecUrl          = "https://foo.bar",
                ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                UpdateIntroducedBlock = 1234567
            };

            StateCompare             sc      = new StateCompare(cp);
            List <StateChangeAction> actions = sc.ComputeActionsFromState(newState);

            // Assert
            actions.Should().BeEmpty();
        }
示例#4
0
        public void ShouldGenerateSigningAction()
        {
            MockConfigProvider cp = new MockConfigProvider {
                CurrentState = new NodeState
                {
                    IsSigning             = true,
                    DockerImage           = "parity/parity:v2.3.4",
                    DockerChecksum        = "9f0142e1ae1641fbcf6116c49b5c73d5a4b48340e07f9ecb4da8d2d9847a76e6",
                    ChainspecUrl          = "https://www.example.com/chainspec-20190210.json",
                    ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                    UpdateIntroducedBlock = 1234567
                }
            };

            // Recreate the same state so state object references are different
            NodeState newState = new NodeState
            {
                IsSigning             = false,
                DockerImage           = "parity/parity:v2.3.4",
                DockerChecksum        = "9f0142e1ae1641fbcf6116c49b5c73d5a4b48340e07f9ecb4da8d2d9847a76e6",
                ChainspecUrl          = "https://www.example.com/chainspec-20190210.json",
                ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                UpdateIntroducedBlock = 1234567
            };

            StateCompare             sc      = new StateCompare(cp);
            List <StateChangeAction> actions = sc.ComputeActionsFromState(newState);

            // Assert
            actions.Should().HaveCount(1);
            actions.Should().ContainSingle(action =>
                                           action.Mode == UpdateMode.ToggleSigning &&
                                           action.Payload == false.ToString() &&
                                           action.PayloadHash == string.Empty);
        }
示例#5
0
        public void ShouldGenerateDockerAction()
        {
            MockConfigProvider cp = new MockConfigProvider {
                CurrentState = new NodeState
                {
                    IsSigning             = true,
                    DockerImage           = "parity/parity:v2.3.4",
                    DockerChecksum        = "9f0142e1ae1641fbcf6116c49b5c73d5a4b48340e07f9ecb4da8d2d9847a76e6",
                    ChainspecUrl          = "https://foo.bar",
                    ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                    UpdateIntroducedBlock = 1234567
                }
            };

            // Recreate the same state so state object references are different
            NodeState newState = new NodeState
            {
                IsSigning             = true,
                DockerImage           = "parity/parity:v2.4.4",
                DockerChecksum        = "c30bcff5580cb5d9c4edb0a0c8794210e85a134c2f12ffd166735e7c26079211",
                ChainspecUrl          = "https://foo.bar",
                ChainspecChecksum     = "b76377f4f130134f352e81c8929fb0c8ffca94da722f704d16d0873fc9e030ea",
                UpdateIntroducedBlock = 1234567
            };

            StateCompare             sc      = new StateCompare(cp);
            List <StateChangeAction> actions = sc.ComputeActionsFromState(newState);

            // Assert
            actions.Should().HaveCount(1);
            actions.Should().ContainSingle(action =>
                                           action.Mode == UpdateMode.Docker &&
                                           action.Payload == "parity/parity:v2.4.4" &&
                                           action.PayloadHash == "c30bcff5580cb5d9c4edb0a0c8794210e85a134c2f12ffd166735e7c26079211");
        }
        public void ShouldNotUpdateWhenEqualState()
        {
            // Run the test

            Mock <IContractWrapper> cwMock = new Mock <IContractWrapper>(MockBehavior.Loose);

            cwMock
            .Setup(mock => mock.HasNewUpdate())
            .Returns(() => Task.FromResult(true))
            .Verifiable("Contract was not checked for update event");

            cwMock
            .Setup(mock => mock.GetExpectedState())
            .Returns(() => Task.FromResult(new NodeState
            {
                DockerImage           = "parity/parity:v2.3.3",
                DockerChecksum        = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514",
                ChainspecUrl          = "https://example.com",
                IsSigning             = false,
                ChainspecChecksum     = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514",
                UpdateIntroducedBlock = new BigInteger(20)
            }))
            .Verifiable("Contract was not queried for state");


            // Prime config provider with equal state but older
            MockConfigProvider confMock = new MockConfigProvider
            {
                CurrentState = new NodeState
                {
                    DockerImage           = "parity/parity:v2.3.3",
                    DockerChecksum        = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514",
                    ChainspecUrl          = "https://example.com",
                    IsSigning             = false,
                    ChainspecChecksum     = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514",
                    UpdateIntroducedBlock = new BigInteger(10)
                }
            };

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "./path",
                DockerControl         = new MockDockerControl(),
                ConfigurationProvider = confMock,
                ContractWrapper       = cwMock.Object
            }, new MockLogger());

            // Should yield not update actions and therefore should return false
            bool checkResult = uw.CheckForUpdates();

            checkResult.Should().Be(false);

            cwMock.Verify();
            cwMock.VerifyNoOtherCalls();
        }
示例#7
0
        public void ShouldThrowWhenComparingNullState()
        {
            MockConfigProvider cp = new MockConfigProvider();
            StateCompare       sc = new StateCompare(cp);

            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => { sc.ComputeActionsFromState(null); });

            Assert.Equal("newState", ex.ParamName);
        }
示例#8
0
        public void ShoudThrowOnUnableToPull()
        {
            StateChangeAction changeAction = new StateChangeAction
            {
                Mode        = UpdateMode.Docker,
                Payload     = "parity/parity:v2.3.4",
                PayloadHash = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };
            NodeState nodeState = new NodeState
            {
                DockerImage    = "parity/parity:v2.3.4",
                DockerChecksum = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };


            Mock <IDockerControl> mocDcc = new Mock <IDockerControl>(MockBehavior.Loose);

            // Setup image pull mock
            mocDcc.Setup(mock => mock.PullImage(
                             It.IsAny <ImagesCreateParameters>(),
                             It.IsAny <AuthConfig>(),
                             It.IsAny <Progress <JSONMessage> >()))
            .Throws <Exception>()
            .Verifiable("Did not pull correct image");


            MockConfigProvider confProvider = new MockConfigProvider();

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = mocDcc.Object,
                ConfigurationProvider = confProvider,
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            // Run the update action
            Action updateDocker = () => { uw.UpdateDocker(changeAction, nodeState); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage("Unable to pull new image.");

            // Verify the mocks
            mocDcc.Verify();

            // make sure nothing else was called
            mocDcc.VerifyNoOtherCalls();

            // verify no new state was written
            confProvider.CurrentState.Should().BeNull();
        }
示例#9
0
        public void ShouldThrowWhenNullStateFromConfigProvider()
        {
            MockConfigProvider cp = new MockConfigProvider {
                CurrentState = null
            };
            StateCompare sc = new StateCompare(cp);

            StateCompareException ex = Assert.Throws <StateCompareException>(() =>
            {
                sc.ComputeActionsFromState(new NodeState());
            });

            Assert.Equal("Received state from configuration provider is null. Can't compare", ex.Message);
        }
        public void ShouldUpdateWhenDifferentState(NodeState currentState, NodeState expectedState, bool shouldTriggerUpdate)
        {
            // Run the test

            Mock <IContractWrapper> cwMock = new Mock <IContractWrapper>(MockBehavior.Loose);

            cwMock
            .Setup(mock => mock.HasNewUpdate())
            .Returns(() => Task.FromResult(true))
            .Verifiable("Contract was not checked for update event");

            // Mock expected state from contract
            cwMock
            .Setup(mock => mock.GetExpectedState())
            .Returns(() => Task.FromResult(expectedState))
            .Verifiable("Contract was not queried for state");


            cwMock
            .Setup(mock => mock.ConfirmUpdate())
            .Returns(() => Task.CompletedTask)
            .Verifiable("Contract was not called to confirm update");

            // Prime config provider with equal state but older
            MockConfigProvider confMock = new MockConfigProvider
            {
                CurrentState = currentState
            };

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "https://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "./path",
                DockerControl         = new MockDockerControl(expectedState.DockerChecksum),
                ConfigurationProvider = confMock,
                ContractWrapper       = cwMock.Object,
                WaitTimeAfterUpdate   = 1000 // shorten time to wait
            }, new MockLogger());

            // Should yield update actions and therefore should return true
            bool checkResult = uw.CheckForUpdates();

            checkResult.Should().Be(shouldTriggerUpdate);

            cwMock.Verify();
            cwMock.VerifyNoOtherCalls();
        }
示例#11
0
        public void ShouldGenerateActionCombinations(NodeState currentState, NodeState newState, List <StateChangeAction> expectedActions)
        {
            MockConfigProvider cp = new MockConfigProvider {
                CurrentState = currentState
            };

            StateCompare             sc      = new StateCompare(cp);
            List <StateChangeAction> actions = sc.ComputeActionsFromState(newState);

            // Assert
            actions.Should().HaveCount(expectedActions.Count);

            foreach (StateChangeAction expAction in expectedActions)
            {
                actions.Should().ContainEquivalentOf(expAction);
            }
        }
示例#12
0
            public void SetupGetGetShopperHistoryApiResult(List <ShopperHistory> shopperHistoryList)
            {
                var httpContent = JsonConvert.SerializeObject(shopperHistoryList);
                var apiUrl      = "http://apihost/api/resource/shopperhistory";
                var token       = "TestToken";

                MockSerializer
                .Setup(o => o.Deserialize <List <ShopperHistory> >(It.IsAny <string>()))
                .Returns <string>(s => JsonConvert.DeserializeObject <List <ShopperHistory> >(s));

                MockExternalApiPathProvider
                .Setup(o => o.GetApiPath(ExternalApiPathName.GetShopperHistory))
                .Returns(apiUrl);

                MockConfigProvider
                .Setup(o => o.GetConfigValue(ConfigKeys.Token))
                .Returns(token);

                var apiRequestUrl = $"{apiUrl}?token={token}";

                MockMessageHandler
                .When(HttpMethod.Get, apiRequestUrl)
                .Respond("application/json", httpContent);
            }
示例#13
0
        public void ShoudThrowOnBadHash()
        {
            string expectedImage = "parity/parity:v2.3.4";
            string expectedHash  = "bbbbcc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514";

            StateChangeAction changeAction = new StateChangeAction
            {
                Mode        = UpdateMode.Docker,
                Payload     = "parity/parity:v2.3.4",
                PayloadHash = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };
            NodeState nodeState = new NodeState
            {
                DockerImage    = "parity/parity:v2.3.4",
                DockerChecksum = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };


            Mock <IDockerControl> mocDcc = new Mock <IDockerControl>(MockBehavior.Loose);

            // Setup image pull mock
            mocDcc.Setup(mock => mock.PullImage(
                             It.Is <ImagesCreateParameters>(icp => icp.Tag == "v2.3.4" && icp.FromImage == "parity/parity"),
                             It.Is <AuthConfig>(obj => obj == null),
                             It.IsAny <Progress <JSONMessage> >()))
            .Verifiable("Did not pull correct image");

            // Setup inspect image mock
            mocDcc
            .Setup(mock => mock.InspectImage(
                       It.Is <string>(i => i == expectedImage)
                       ))
            .Returns(new ImageInspectResponse
            {
                ID = expectedHash
            })
            .Verifiable("Did not inspect the correct image");


            // setup delete mock
            mocDcc
            .Setup(mock => mock.DeleteImage(expectedImage))
            .Verifiable("Did not correctly delete the wrong image");

            MockConfigProvider confProvider = new MockConfigProvider();

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = mocDcc.Object,
                ConfigurationProvider = confProvider,
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            // Run the update action
            Action updateDocker = () => { uw.UpdateDocker(changeAction, nodeState); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage("Docker image hashes don't match.");

            // Verify the mocks
            mocDcc.Verify();

            // make sure nothing else was called
            mocDcc.VerifyNoOtherCalls();

            // verify no new state was written
            confProvider.CurrentState.Should().BeNull();
        }