public void Initalize() { _factory = new MockRepository(MockBehavior.Loose); _container = new AutoMockContainer(_factory); _coins = new List<Coin>(); _purchaseServiceMock = _container.GetMock<IPurchaseService>(); var product_a = new Product() { Price = 1, Title = "Apple" }; var product_b = new Product() { Price = .75m, Title = "Banana" }; var slot_a = new Slot() { Button = "A", Product = product_a, MaxNumberOfProduct = 5, Quantity = 4 }; var slot_b = new Slot() { Button = "B", Product = product_b, MaxNumberOfProduct = 5, Quantity = 0 }; _dollar = new Coin() { Title = "One Dollar", Value = 1, ShortName = "O" }; _quarter = new Coin() { Title = "Quarter", Value = .25m, ShortName = "Q" }; _dime = new Coin() { Title = "Dime", Value = .1m, ShortName = "d" }; _nickle = new Coin() { Title = "Nickle", Value = .05m, ShortName = "n" }; _penny = new Coin() { Title = "Penny", Value = .01m, ShortName = "p" }; _slots = new List<Slot>() { slot_a, slot_b }; _maxSlots = 5; _machineService = new MachineService(_maxSlots, _purchaseServiceMock.Object); }
public async Task Persist_TransactionWithInputs_SpendOutputs() { var repositoryMock = AutoMockContainer.GetMock <IRepository>(); var input = new ContractTransaction { Hash = UInt256.Parse(RandomInt().ToString("X64")), Inputs = new CoinReference[3] }; var txs = new Transaction[3]; for (var i = 0; i < input.Inputs.Length; i++) { var reference = new CoinReference { PrevHash = UInt256.Parse(RandomInt().ToString("X64")), PrevIndex = 0 }; input.Inputs[i] = reference; txs[i] = new Transaction { Hash = reference.PrevHash, Outputs = new[] { new TransactionOutput { AssetId = UInt256.Parse(RandomInt().ToString("X64")), ScriptHash = UInt160.Parse(RandomInt().ToString("X40")), Value = new Fixed8(RandomInt()) } } }; repositoryMock .Setup(m => m.GetTransaction(reference.PrevHash)) .ReturnsAsync(txs[i]); repositoryMock .Setup(m => m.GetCoinStates(reference.PrevHash)) .ReturnsAsync(new[] { CoinState.Confirmed }); } var accountManagerMock = AutoMockContainer.GetMock <IAccountManager>(); var testee = AutoMockContainer.Create <TransactionPersister>(); await testee.Persist(input); for (var i = 0; i < input.Outputs.Length; i++) { var output = txs[i].Outputs[0]; accountManagerMock.Verify(m => m.UpdateBalance(output.ScriptHash, output.AssetId, -output.Value)); var hash = txs[i].Hash; repositoryMock.Verify(m => m.AddCoinStates(It.Is <UInt256>(u => u.Equals(hash)), It.Is <CoinState[]>(cs => cs.Length == 1 && cs[0].Equals(CoinState.Confirmed | CoinState.Spent)))); } }
public void TestSaveWalletFileExists() { var expectedFileName = "name.json"; var fileWrapper = AutoMockContainer.GetMock <IFileWrapper>(); fileWrapper.Setup(x => x.Exists(expectedFileName)).Returns(true); var mockWalletManager = AutoMockContainer.Create <Nep6WalletManager>(); mockWalletManager.CreateWallet(expectedFileName); }
public async Task GetIndexHeight_ValueFound_ReturnsValue() { var expectedHeight = (uint)RandomInt(); var contextMock = AutoMockContainer.GetMock <IRedisDbContext>(); contextMock.Setup(m => m.Get(DataEntryPrefix.IxIndexHeight.ToString())).ReturnsAsync(expectedHeight); var testee = AutoMockContainer.Create <RedisDbBinaryRepository>(); var result = await testee.GetIndexHeight(); result.Should().Be(expectedHeight); }
public void Throw_on_receiving_of_unknown_message() { // Arrange var containerMock = AutoMockContainer.GetMock <IContainer>(); var messageHandlerProxy = new MessageHandlerProxy(containerMock.Object, new Type[0]); // Act Action a = () => messageHandlerProxy.Handle(new VersionMessage(), null); // Assert a.Should().Throw <InvalidOperationException>(); }
public void Indica_duplicacao_quando_pesquisa_devolve_true(ServicoVerificacaoDuplicacaoNif servico, int id, string nif, bool resultado) { const int totalRegistosDevolver = 1; "Dado um servico de verificação" .Given(() => servico = _container.Create <ServicoVerificacaoDuplicacaoNif>()); "e um id" .And(() => id = 1); "e um nif" .And(() => nif = "123456789"); "E alguns mocks" .And(() => PreparaMocks(id, nif, totalRegistosDevolver)); "Quando verificamos a duplicação" .When(() => resultado = servico.NifDuplicado(nif, id)); "O resultado deve ser true" .Then(() => resultado.Should().BeTrue()); "E servico deve ter sido usado corretamente" .And(() => { _container.GetMock <ISession>().VerifyAll(); _container.GetMock <ISQLQuery>().VerifyAll(); }); }
public void SendRequest_Request_Null_Fails() { // Arrange _autoMockContainer .Register <IRequestService, RequestService>(); var mockUnitOfWork = _autoMockContainer .GetMock <IUnitOfWork>(); var requestEntity = new Domain.Entities.Request(); mockUnitOfWork .Setup(uow => uow.CreateEntity <Domain.Entities.Request>()) .Returns(requestEntity); _autoMockContainer .GetMock <IUnitOfWorkFactory>().Setup(uowf => uowf.Create()) .Returns(mockUnitOfWork.Object); _autoMockContainer .GetMock <IDateTimeService>() .Setup(dts => dts.GetCurrentDateAndTime()) .Returns(DateTime.Now); // Act Request request = null; Assert.ThrowsDelegate sendRequestAction = () => _autoMockContainer.Resolve <IRequestService>().CreateRequest(request); // Assert Assert.Throws <ArgumentNullException>(sendRequestAction); }
public void Cenario_com_sucesso(RepositorioFuncionarios repositorio, Funcionario funcionario) { "Dado um repositorio" .Given(() => repositorio = _container.Create <RepositorioFuncionarios>()); "E um funcionário com NIF não repetido" .And(() => funcionario = Funcionario.CriaVazio(new TipoFuncionario())); "E alguns mocks" .And(() => { _container.GetMock <IVerificadorNif>() .Setup(v => v.NifDuplicado(It.IsAny <string>(), It.IsAny <int>())) .Returns(false); _container.GetMock <ISession>() .Setup(s => s.SaveOrUpdate(It.IsAny <object>())); }); "Quando gravamos o funcionário" .When(() => repositorio.Grava(funcionario)); "Então~não obtemos exceção e serviço verificação é usado" .Then(() => { _container.GetMock <IVerificadorNif>().VerifyAll(); _container.GetMock <ISession>().VerifyAll(); }); }
public async Task Get_ReturnsRepositoryValue() { var input = UInt160.Parse(RandomInt().ToString("X40")); var expectedResult = new Account(); var repositoryMock = AutoMockContainer.GetMock <IRepository>(); repositoryMock.Setup(m => m.GetAccount(input)).ReturnsAsync(expectedResult); var testee = AutoMockContainer.Create <AccountManager>(); var result = await testee.Get(input); result.Should().Be(expectedResult); }
public async Task SetTotalBlockHeight_SaveCorrectKeyValue() { var input = (uint)RandomInt(); var expectedValue = BitConverter.GetBytes(input); var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); var testee = AutoMockContainer.Create <RocksDbRepository>(); await testee.SetTotalBlockHeight(input); rocksDbContextMock.Verify(m => m.Save(It.Is <byte[]>(b => b.SequenceEqual(new[] { (byte)DataEntryPrefix.SysCurrentBlock })), It.Is <byte[]>(b => b.SequenceEqual(expectedValue)))); }
public async Task GetVersion_NoValueFound_ReturnsUIntMinValue() { var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); redisDbContextMock .Setup(x => x.Get(DataEntryPrefix.SysVersion.ToString())) .ReturnsAsync(RedisValue.Null); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); var result = await testee.GetVersion(); result.Should().BeNull(); }
public async Task GetTotalBlockHeight_NoValueFound_ReturnsUIntMinValue() { var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); redisDbContextMock .Setup(x => x.Get(DataEntryPrefix.SysCurrentBlock.ToString())) .ReturnsAsync(RedisValue.Null); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); var result = await testee.GetTotalBlockHeight(); result.Should().Be(uint.MinValue); }
public void StopNetwork_Stops_Server() { // Arrange var serverMock = AutoMockContainer.GetMock <IServer>(); var networkManager = AutoMockContainer.Create <NetworkManager>(); // Act networkManager.StopNetwork(); // Asset serverMock.Verify(x => x.Stop(), Times.Once); }
public void Register_AllObjectsAreCorrectlyRegister() { // Arrange var containerBuilderMock = AutoMockContainer.GetMock <IContainerBuilder>(); var module = AutoMockContainer.Create <LoggingModule>(); // Act module.Register(containerBuilderMock.Object); // Assert containerBuilderMock.Verify(x => x.RegisterSingleton <Microsoft.Extensions.Logging.ILoggerFactory, NLogLoggerFactory>(), Times.Once); containerBuilderMock.Verify(x => x.RegisterSingleton(typeof(ILogger <>), typeof(LoggerAdapter <>)), Times.Once); }
public void Can_listen_for_peers_on_start() { // Arrange AutoMockContainer.Register(GetNetworkConfig()); var peerListenerMock = AutoMockContainer.GetMock <IPeerListener>(); var server = AutoMockContainer.Create <Server>(); // Act server.Start(); // Asset peerListenerMock.Verify(x => x.Start(), Times.Once); }
public async Task GetIndexClaimable_NoValueFound_ReturnsEmptySet() { var input = UInt160.Parse(RandomInt().ToString("X40")); var contextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); contextMock.Setup(m => m.Get(input.BuildIxClaimableKey())).ReturnsAsync(RedisValue.Null); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); var result = await testee.GetIndexClaimable(input); result.Should().BeOfType(typeof(HashSet <CoinReference>)); result.Count.Should().Be(0); }
public async Task GetTotalBlockHeaderHeight_NoValueFound_ReturnsUIntMinValue() { var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); rocksDbContextMock .Setup(x => x.Get(It.Is <byte[]>(b => b.SequenceEqual(new[] { (byte)DataEntryPrefix.SysCurrentHeader })))) .ReturnsAsync((byte[])null); var testee = AutoMockContainer.Create <RocksDbRepository>(); var result = await testee.GetTotalBlockHeaderHeight(); result.Should().Be(uint.MinValue); }
public async Task DeleteStorage_DeletesCorrectKey() { var inputHash = UInt160.Parse(RandomInt().ToString("X40")); var input = new StorageKey { ScriptHash = inputHash, Key = new byte[0] }; var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); await testee.DeleteStorage(input); redisDbContextMock.Verify(m => m.Delete(It.Is <RedisKey>(b => b == input.BuildStateStorageKey()))); }
public async Task GetVersion_NoValueFound_ReturnsUIntMinValue() { var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); rocksDbContextMock .Setup(x => x.Get(It.Is <byte[]>(b => b.SequenceEqual(new[] { (byte)DataEntryPrefix.SysVersion })))) .ReturnsAsync((byte[])null); var testee = AutoMockContainer.Create <RocksDbRepository>(); var result = await testee.GetVersion(); result.Should().BeNull(); }
public async Task Persist_MarksClaimsFromMultipleTx() { var txHash1 = UInt256.Parse(RandomInt().ToString("X64")); var txHash2 = UInt256.Parse(RandomInt().ToString("X64")); var txHash3 = UInt256.Parse(RandomInt().ToString("X64")); var input = new ClaimTransaction { Claims = new[] { new CoinReference { PrevHash = txHash1, PrevIndex = 0 }, new CoinReference { PrevHash = txHash2, PrevIndex = 0 }, new CoinReference { PrevHash = txHash3, PrevIndex = 0 } } }; var coinStates = new[] { CoinState.Confirmed | CoinState.Spent, CoinState.Confirmed | CoinState.Spent, CoinState.Confirmed | CoinState.Spent }; var repositoryMock = AutoMockContainer.GetMock <IRepository>(); repositoryMock.Setup(m => m.GetCoinStates(txHash1)) .ReturnsAsync(coinStates.Skip(0).Take(1).ToArray()); repositoryMock.Setup(m => m.GetCoinStates(txHash2)) .ReturnsAsync(coinStates.Skip(1).Take(1).ToArray()); repositoryMock.Setup(m => m.GetCoinStates(txHash3)) .ReturnsAsync(coinStates.Skip(2).Take(1).ToArray()); var testee = AutoMockContainer.Create <ClaimTransactionPersister>(); await testee.Persist(input); repositoryMock.Verify(m => m.AddCoinStates( It.Is <UInt256>(u => u.Equals(txHash1)), It.Is <CoinState[]>(c => c[0].HasFlag(CoinState.Confirmed | CoinState.Spent | CoinState.Claimed)) )); repositoryMock.Verify(m => m.AddCoinStates( It.Is <UInt256>(u => u.Equals(txHash2)), It.Is <CoinState[]>(c => c[0].HasFlag(CoinState.Confirmed | CoinState.Spent | CoinState.Claimed)) )); repositoryMock.Verify(m => m.AddCoinStates( It.Is <UInt256>(u => u.Equals(txHash3)), It.Is <CoinState[]>(c => c[0].HasFlag(CoinState.Confirmed | CoinState.Spent | CoinState.Claimed)) )); }
public async Task GetContract_NoValue_ReturnsNull() { var input = UInt160.Parse(RandomInt().ToString("X40")); var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); redisDbContextMock .Setup(m => m.Get(It.Is <RedisKey>(b => b == input.BuildStateContractKey()))) .ReturnsAsync(RedisValue.Null); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); var result = await testee.GetContract(input); result.Should().BeNull(); }
public async Task DeleteValidator_DeletesCorrectKey() { var pubkey = new byte[33]; pubkey[0] = 0x02; var input = new ECPoint(pubkey); var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbJsonContext>(); var testee = AutoMockContainer.Create <RedisDbJsonRepository>(); await testee.DeleteValidator(input); redisDbContextMock.Verify( m => m.Delete(It.Is <RedisKey>(b => b == input.BuildStateValidatorKey()))); }
public async Task AddBlockHeader_ValidBlockHeader_BlockHeaderAndHeightHashSaved() { // Arrange var expectedBlockByteArray = new byte[] { 157, 179, 60, 8, 66, 122, 255, 105, 126, 49, 180, 74, 212, 41, 126, 177, 14, 255, 59, 82, 218, 113, 248, 145, 98, 5, 128, 140, 42, 70, 32, 69, 0 }; var hash = UInt256.Parse("0x4520462a8c80056291f871da523bff0eb17e29d44ab4317e69ff7a42083cb39d"); const uint index = 0; var timestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var blockHeaderParameter = new BlockHeader { Hash = hash, Index = index }; blockHeaderParameter.Timestamp = timestamp; _serializerMock .Setup(x => x.Serialize(blockHeaderParameter, null)) .Returns(expectedBlockByteArray); var redisDbContextMock = AutoMockContainer.GetMock <IRedisDbContext>(); var testee = AutoMockContainer.Create <RedisDbBinaryRepository>(); // Act await testee.AddBlockHeader(blockHeaderParameter); // Assert redisDbContextMock.Verify(x => x.Set( It.IsAny <RedisKey>(), It.IsAny <RedisValue>()), Times.Once); redisDbContextMock.Verify(x => x.AddToIndex( It.Is <RedisIndex>(a => a == RedisIndex.BlockTimestamp), It.Is <UInt256>(a => a == blockHeaderParameter.Hash), It.Is <double>(a => a == blockHeaderParameter.Timestamp)), Times.Once); redisDbContextMock.Verify(x => x.AddToIndex( It.Is <RedisIndex>(a => a == RedisIndex.BlockHeight), It.Is <UInt256>(a => a == blockHeaderParameter.Hash), It.Is <double>(a => a == blockHeaderParameter.Index)), Times.Once); }
public void Register_AllObjectsAreCorrectlyRegister() { // Arrange var containerBuilderMock = AutoMockContainer.GetMock <IContainerBuilder>(); var module = AutoMockContainer.Create <ClientModule>(); // Act module.Register(containerBuilderMock.Object); // Assert containerBuilderMock.Verify(x => x.Register <IBootstrapper, Bootstrapper>(), Times.Once); containerBuilderMock.Verify(x => x.RegisterSingleton <IPrompt, Prompt>(), Times.Once); containerBuilderMock.Verify(x => x.RegisterSingleton <IConsoleHandler, ConsoleHandler>(), Times.Once); }
public async Task GetIndexHeight_ValueFound_ReturnsUint() { var expectedHeight = (uint)RandomInt(); var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); rocksDbContextMock .Setup(m => m.Get(It.Is <byte[]>(b => b.Length == 1 && b[0] == (byte)DataEntryPrefix.IxIndexHeight))) .ReturnsAsync(BitConverter.GetBytes(expectedHeight)); var testee = AutoMockContainer.Create <RocksDbRepository>(); var result = await testee.GetIndexHeight(); result.Should().Be(expectedHeight); }
public async Task DeleteValidator_DeletesCorrectKey() { var pubkey = new byte[33]; pubkey[0] = 0x02; var input = new ECPoint(pubkey); var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); var testee = AutoMockContainer.Create <RocksDbRepository>(); await testee.DeleteValidator(input); rocksDbContextMock.Verify( m => m.Delete(It.Is <byte[]>(b => b.SequenceEqual(input.BuildStateValidatorKey())))); }
public async Task AddCoinStates_WritesCorrectKeyValue() { var inputHash = UInt256.Parse(RandomInt().ToString("X64")); var inputStates = new[] { new CoinState() }; var expectedBytes = new byte[1]; _serializerMock.Setup(m => m.Serialize(inputStates, null)).Returns(expectedBytes); var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); var testee = AutoMockContainer.Create <RocksDbRepository>(); await testee.AddCoinStates(inputHash, inputStates); rocksDbContextMock.Verify(m => m.Save(It.Is <byte[]>(b => b.SequenceEqual(inputHash.BuildStateCoinKey())), expectedBytes)); }
public void Initialize() { var networkConfig = GetNetworkConfig(); _peerEndPoint = networkConfig.PeerEndPoints[0]; AutoMockContainer.Register(networkConfig); var blockchainContextMock = AutoMockContainer.GetMock <IBlockchainContext>(); blockchainContextMock .SetupGet(x => x.CurrentBlock) .Returns(new Block()); }
public void Register_AllObjectsAreCorrectlyRegister() { // Arrange var containerBuilderMock = AutoMockContainer.GetMock <IContainerBuilder>(); var module = AutoMockContainer.Create <CoreModule>(); // Act module.Register(containerBuilderMock.Object); // Assert containerBuilderMock.Verify(x => x.RegisterModule <BlockchainModule>(), Times.Once); containerBuilderMock.Verify(x => x.RegisterModule <NetworkModule>(), Times.Once); containerBuilderMock.Verify(x => x.RegisterModule <HelpersModule>(), Times.Once); }
public async Task GetContract_NoValue_ReturnsNull() { var input = UInt160.Parse(RandomInt().ToString("X40")); var rocksDbContextMock = AutoMockContainer.GetMock <IRocksDbContext>(); rocksDbContextMock .Setup(m => m.Get(It.Is <byte[]>(b => b.SequenceEqual(input.BuildStateContractKey())))) .ReturnsAsync((byte[])null); var testee = AutoMockContainer.Create <RocksDbRepository>(); var result = await testee.GetContract(input); result.Should().BeNull(); }
public void Can_stop_server_on_dispose() { // Arrange AutoMockContainer.Register(GetNetworkConfig()); var peerListenerMock = AutoMockContainer.GetMock <IPeerListener>(); var server = AutoMockContainer.Create <Server>(); // Act server.Start(); server.Dispose(); // Asset peerListenerMock.Verify(x => x.Stop(), Times.AtLeastOnce); }
public void Initalize() { _factory = new MockRepository(MockBehavior.Loose); _container = new AutoMockContainer(_factory); _frameServiceMock = _container.GetMock<IFrameService>(); _players = new List<Player>(); _frames = new List<Frame>(); var score = 0; var player_a = new Player() { FirstName = "Andrew", LastName = "Leaf", Frames = _frames, Score = score }; var player_b = new Player() { FirstName = "Jennifer", LastName = "Leaf", Frames = _frames, Score = score }; _players.Add(player_a); _players.Add(player_b); _gameService = new GameService(_frameServiceMock.Object); }