Exemple #1
0
        public static IViewModelMapper Create(params Assembly[] assemblies)
        {
            var registry = new ViewModelMetadataRegistry();

            ViewModelMetadataRegistry.Current = registry;

            foreach (var assembly in assemblies)
            {
                registry.LoadViewModelMetadataInAssemblyOf(assembly);
            }

            var formatterMock = new Mock <IViewModelPropertyFormatter>();

            formatterMock.Setup(m => m.Format(It.IsAny <object>(), It.IsNotNull <IPropertyMetadata>(), It.IsAny <CultureInfo>()))
            .Returns((object value, IPropertyMetadata meta, CultureInfo culture) => value?.ToString());

            var lookupServiceMock        = new Mock <ILookupService>();
            var localizationProviderMock = new Mock <ILocalizationProvider>();

            var mapper = new ViewModelMapper(registry, formatterMock.Object, lookupServiceMock.Object, localizationProviderMock.Object);

            return(mapper);
        }
        internal static Mock <SpannerClient> SetupBatchCreateSessionsAsync(this Mock <SpannerClient> spannerClientMock)
        {
            spannerClientMock
            .Setup(client => client.BatchCreateSessionsAsync(It.IsNotNull <BatchCreateSessionsRequest>(), It.IsAny <CallSettings>()))
            .Returns <BatchCreateSessionsRequest, CallSettings>((request, _) =>
            {
                BatchCreateSessionsResponse response = new BatchCreateSessionsResponse();

                for (int i = 0; i < request.SessionCount; i++)
                {
                    var session         = request.SessionTemplate.Clone();
                    session.CreateTime  = session.ApproximateLastUseTime = spannerClientMock.GetNowTimestamp();
                    session.Expired     = false;
                    session.Name        = Guid.NewGuid().ToString();
                    session.SessionName = new SessionName(ProjectId, Instance, Database, session.Name);

                    response.Session.Add(session);
                }

                return(Task.FromResult(response));
            });
            return(spannerClientMock);
        }
Exemple #3
0
        private void Given_ExecutableProgram(string exeName, Address address)
        {
            var bytes      = new byte[0x1000];
            var mem        = new MemoryArea(address, bytes);
            var segmentMap = new SegmentMap(address,
                                            new ImageSegment(".text", mem, AccessMode.ReadWriteExecute));
            var program = new Program
            {
                Architecture = arch.Object,
                Platform     = mockFactory.CreateMockPlatform().Object,
                SegmentMap   = segmentMap,
                ImageMap     = segmentMap.CreateImageMap()
            };

            loader.Setup(l => l.LoadImageBytes(
                             It.Is <string>(s => s.EndsWith(exeName)),
                             It.IsAny <int>())).Returns(bytes);
            loader.Setup(l => l.LoadExecutable(
                             It.Is <string>(s => s.EndsWith(exeName)),
                             It.IsNotNull <byte[]>(),
                             null,
                             null)).Returns(program);
        }
        public async Task StartAsync_WhenRetrieverError_ShouldThrowFromExecuteAsync()
        {
            // Arrange.
            var stopped = new TaskCompletionSource <object?>();

            this.background.SetException(new Exception());

            this.retriever
            .Setup(r => r.StopAsync(It.IsAny <CancellationToken>()))
            .Callback(() => stopped.SetResult(null));

            // Act.
            await this.subject.StartAsync();

            await stopped.Task;

            // Assert.
            this.retriever.Verify(
                r => r.StartAsync(It.IsNotNull <IBlockListener>(), It.IsNotIn(CancellationToken.None)),
                Times.Once());

            this.retriever.Verify(
                r => r.StopAsync(default),
Exemple #5
0
        public async Task GenerateAsync_GenerateInvokesHashMethodOfHasher_returnsTrue()
        {
            // Arrange
            var mockHasher = new Mock <IFastHasher>();
            var sequence   = mockHasher.SetupSequence(m => m.ComputeFast(It.IsAny <byte[]>()));

            for (var i = 0; i < 256; i++)
            {
                sequence.Returns(i);
            }
            var salt = Stubs.Get <IMemoryProtectedBytes>();
            var sut  = GetSut(mockHasher.Object, sessionSalt: salt);
            await sut.GenerateAsync(It.IsAny <byte>()); // To ensure salt is initialized

            mockHasher.Reset();

            // Act
            await sut.GenerateAsync(It.IsAny <byte>());

            // Assert
            mockHasher.Verify(x =>
                              x.ComputeFast(It.IsNotNull <byte[]>()), Times.Exactly(1));
        }
Exemple #6
0
        private void Given_BinaryFile(string exeName, Address address)
        {
            var bytes   = new byte[0x10];
            var program = new Program
            {
                Architecture = arch.Object,
                SegmentMap   = new SegmentMap(
                    address,
                    new ImageSegment(
                        ".text",
                        new MemoryArea(address, bytes),
                        AccessMode.ReadWriteExecute))
            };

            loader.Setup(l => l.LoadImageBytes(
                             It.Is <string>(s => s.EndsWith(exeName)),
                             It.IsAny <int>())).Returns(bytes);
            loader.Setup(l => l.LoadExecutable(
                             It.Is <string>(s => s.EndsWith(exeName)),
                             It.IsNotNull <byte[]>(),
                             null,
                             null)).Returns(program);
        }
Exemple #7
0
        public void Execute_CopyProjectFullPath(string path)
        {
            var feature = GetFeature();

            _shellHelperServiceMock.Setup(s => s.GetCurrentProjectPath()).Returns(path).Verifiable();
            _utilsServiceMock.Setup(u => u.SetClipboardData(It.IsNotNull <string>())).Verifiable();

            var result = feature.Execute(CommandIDs.COPY_FULL_PATH);

            if (!string.IsNullOrEmpty(path))
            {
                Assert.That(result, Is.True);
                _utilsServiceMock.Verify(u => u.SetClipboardData(path));
                _shellStatusBarServiceMock.Verify(s => s.SetStatusBarText(path));
            }
            else
            {
                Assert.That(result, Is.False);
                _utilsServiceMock.Verify(u => u.SetClipboardData(It.IsAny <string>()), Times.Never);
                _shellStatusBarServiceMock.Verify(s => s.SetStatusBarText(It.IsNotNull <string>()));
            }
            _shellHelperServiceMock.Verify(s => s.GetCurrentProjectPath());
        }
        public static void Can_Configure_xunit_For_ILoggerBuilderAccessor_TestOutputHelper()
        {
            // Arrange
            var mockOutputHelper = new Mock <ITestOutputHelper>();
            var outputHelper     = mockOutputHelper.Object;

            var mockAccessor = new Mock <ITestOutputHelperAccessor>();

            mockAccessor
            .Setup((p) => p.OutputHelper)
            .Returns(outputHelper);

            var accessor = mockAccessor.Object;

            var logger = BootstrapBuilder((builder) => builder.AddXUnit(accessor));

            // Act
            logger.LogError("This is a brand new problem, a problem without any clues.");
            logger.LogInformation("If you know the clues, it's easy to get through.");

            // Assert
            mockOutputHelper.Verify((p) => p.WriteLine(It.IsNotNull <string>()), Times.Exactly(2));
        }
Exemple #9
0
        public void Setup_with_It_IsNotNull_It_IsAnyType()
        {
            var invocationCount = 0;
            var mock            = new Mock <IY>();

            mock.Setup(m => m.Method(It.IsNotNull <It.IsAnyType>()))
            .Callback((object arg) => invocationCount++);

            _ = mock.Object.Method <string>("42");
            Assert.Equal(1, invocationCount);

            _ = mock.Object.Method <string>(null);
            Assert.Equal(1, invocationCount);

            _ = mock.Object.Method <int>(42);
            Assert.Equal(2, invocationCount);

            _ = mock.Object.Method <int?>(42);
            Assert.Equal(3, invocationCount);

            _ = mock.Object.Method <int?>(null);
            Assert.Equal(3, invocationCount);
        }
Exemple #10
0
        public void TransfercodeOfHistoryWillBeReused()
        {
            const string transferCode  = "abcdefgh";
            var          settingsModel = CreateSettingsModel("qqqqqqqq");

            settingsModel.TransferCodeHistory.Add(transferCode); // Good transfercode is in history
            byte[] encryptedRepository = CreateEncryptedRepository(transferCode);

            Mock <IStoryBoard> storyBoard = new Mock <IStoryBoard>();

            storyBoard.
            Setup(m => m.LoadFromSession <byte[]>(It.Is <SynchronizationStorySessionKey>(p => p == SynchronizationStorySessionKey.BinaryCloudRepository))).
            Returns(encryptedRepository);
            Mock <ISettingsService> settingsService = new Mock <ISettingsService>();

            settingsService.
            Setup(m => m.LoadSettingsOrDefault()).Returns(settingsModel);
            Mock <INoteRepositoryUpdater> updater = new Mock <INoteRepositoryUpdater>();

            // Run step
            var step = new DecryptCloudRepositoryStep(
                SynchronizationStoryStepId.DecryptCloudRepository,
                storyBoard.Object,
                CommonMocksAndStubs.LanguageService(),
                CommonMocksAndStubs.FeedbackService(),
                settingsService.Object,
                updater.Object);

            Assert.DoesNotThrowAsync(step.Run);

            // transfercode was moved from history to current and was stored
            Assert.AreEqual(transferCode, settingsModel.TransferCode);
            settingsService.Verify(m => m.TrySaveSettingsToLocalDevice(It.IsNotNull <SettingsModel>()), Times.Once);

            // Next step is called
            storyBoard.Verify(m => m.ContinueWith(It.Is <SynchronizationStoryStepId>(x => x == SynchronizationStoryStepId.IsSameRepository)), Times.Once);
        }
Exemple #11
0
        public void BeginResponseAsync_CallsRequestHandler()
        {
            using (var test = new InboundRequestContextTest())
                using (var handledEvent = new ManualResetEventSlim(initialState: false))
                {
                    var requestHandler = new Mock <IRequestHandler>(MockBehavior.Strict);

                    requestHandler.Setup(x => x.HandleResponseAsync(
                                             It.IsNotNull <IConnection>(),
                                             It.IsNotNull <Message>(),
                                             It.IsNotNull <IResponseHandler>(),
                                             It.IsAny <CancellationToken>()))
                    .Callback <IConnection, Message, IResponseHandler, CancellationToken>(
                        (connection, message, responseHandler, cancellationToken) =>
                    {
                        handledEvent.Set();
                    })
                    .Returns(Task.FromResult(0));

                    test.Context.BeginResponseAsync(
                        new Message(
                            test.RequestId,
                            MessageType.Request,
                            MessageMethod.GetOperationClaims,
                            payload: null),
                        requestHandler.Object,
                        Mock.Of <IResponseHandler>());

                    handledEvent.Wait();

                    requestHandler.Verify(x => x.HandleResponseAsync(
                                              It.IsNotNull <IConnection>(),
                                              It.IsNotNull <Message>(),
                                              It.IsNotNull <IResponseHandler>(),
                                              It.IsAny <CancellationToken>()), Times.Once);
                }
        }
Exemple #12
0
        protected override void SetupMocks()
        {
            _sequence = new MockSequence();

            SessionMock.InSequence(_sequence).Setup(p => p.ConnectionInfo).Returns(ConnectionInfoMock.Object);
            ConnectionInfoMock.InSequence(_sequence).Setup(p => p.RetryAttempts).Returns(1);
            SessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            SessionMock.InSequence(_sequence)
            .Setup(
                p =>
                p.SendMessage(
                    It.Is <ChannelOpenMessage>(
                        m =>
                        m.LocalChannelNumber == _localChannelNumber &&
                        m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                        m.Info is SessionChannelOpenInfo)));
            SessionMock.InSequence(_sequence)
            .Setup(p => p.WaitOnHandle(It.IsNotNull <WaitHandle>()))
            .Callback <WaitHandle>(
                w =>
            {
                SessionMock.Raise(
                    s => s.ChannelOpenConfirmationReceived += null,
                    new MessageEventArgs <ChannelOpenConfirmationMessage>(
                        new ChannelOpenConfirmationMessage(
                            _localChannelNumber,
                            _remoteWindowSize,
                            _remotePacketSize,
                            _remoteChannelNumber)));
                w.WaitOne();
            });
            SessionMock.Setup(p => p.IsConnected).Returns(true);
            SessionMock.InSequence(_sequence)
            .Setup(
                p => p.TrySendMessage(It.Is <ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber)))
            .Returns(false);
        }
        public void TestConfigureServicesThrowsWhenSetupWizardConfigurationDemands()
        {
            var mockConfiguration = new Mock <IConfiguration>();

            Assert.ThrowsException <ArgumentNullException>(() => new Application(mockConfiguration.Object, null));

            var mockHostingEnvironment = new Mock <IHostingEnvironment>();

            var app = new Application(mockConfiguration.Object, mockHostingEnvironment.Object);

            var mockOptions = new Mock <IOptions <GeneralConfiguration> >();

            mockOptions.SetupGet(x => x.Value).Returns(new GeneralConfiguration
            {
                SetupWizardMode = SetupWizardMode.Only
            }).Verifiable();

            var fakeServiceDescriptor = new List <ServiceDescriptor>()
            {
                new ServiceDescriptor(typeof(IApplicationLifetime), typeof(MockApplicationLifetime), ServiceLifetime.Singleton),
                new ServiceDescriptor(typeof(ISetupWizard), typeof(MockSetupWizard), ServiceLifetime.Singleton),
                new ServiceDescriptor(typeof(IOptions <GeneralConfiguration>), mockOptions.Object)
            };

            var mockServiceCollection = new Mock <IServiceCollection>();

            var mockConfigSection = new Mock <IConfigurationSection>();

            mockConfiguration.Setup(x => x.GetSection(It.IsNotNull <string>())).Returns(mockConfigSection.Object).Verifiable();
            mockServiceCollection.Setup(x => x.GetEnumerator()).Returns(() => fakeServiceDescriptor.GetEnumerator()).Verifiable();

            Assert.ThrowsException <OperationCanceledException>(() => app.ConfigureServices(mockServiceCollection.Object));

            mockOptions.VerifyAll();
            mockConfiguration.VerifyAll();
            mockServiceCollection.VerifyAll();
        }
Exemple #14
0
        public async void ValidarObterResponsaveis()
        {
            // Arrange
            var query        = new ObterResponsaveisQuery();
            var responsaveis = PagedList <ResponsavelDto> .Create(new List <ResponsavelDto>
            {
                new ResponsavelDto
                {
                    Id    = 1,
                    Nome  = "Nome",
                    Cpf   = "Cpf",
                    Email = "Email",
                    Foto  = new byte[1]
                },
                new ResponsavelDto
                {
                    Id    = 2,
                    Nome  = "Nome2",
                    Cpf   = "Cpf2",
                    Email = "Email2",
                    Foto  = new byte[1]
                }
            }.AsQueryable(),
                                                                  pageNumber : 1,
                                                                  pageSize : 30);

            this.mockMediator
            .Setup(m => m.Send(query, default))
            .Returns(Task.FromResult(new RequestResponseWrapper <PagedList <ResponsavelDto> >(true, responsaveis)));

            // Act
            var response = await this.sut.ObterResponsaveisAsync(query);

            // Assert
            response.Should().BeEquivalentTo(responsaveis);
            this.mockMediator.Verify(mockMediator => mockMediator.Send(It.IsNotNull <ObterResponsaveisQuery>(), default), Times.Once);
        }
Exemple #15
0
        public void WhenPackageHasTwoOwnersAndTheCurrentUserIsAnOwnerAndNotMultiFactorAuthenticated_WhenRequiredSignerIsNull()
        {
            var package = new Package()
            {
                PackageRegistration = new PackageRegistration()
                {
                    Owners = new List <User>()
                    {
                        _currentUser, _otherUser
                    }
                },
                Version = "1.0.0"
            };
            var target = new ListPackageItemRequiredSignerViewModelFactory(
                _securityPolicyService.Object, Mock.Of <IIconUrlProvider>(), Mock.Of <IPackageVulnerabilitiesService>());

            _securityPolicyService.Setup(
                x => x.IsSubscribed(
                    It.IsNotNull <User>(),
                    It.Is <string>(s => s == ControlRequiredSignerPolicy.PolicyName)))
            .Returns(false);

            var viewModel = target.Create(
                package,
                _currentUser,
                wasAADLoginOrMultiFactorAuthenticated: false);

            Assert.Equal(string.Empty, viewModel.RequiredSigner.Username);
            Assert.Equal("Any", viewModel.RequiredSigner.DisplayText);
            Assert.Null(viewModel.RequiredSignerMessage);
            VerifySigners(package.PackageRegistration.Owners, viewModel.AllSigners, expectAnySigner: true);
            Assert.True(viewModel.ShowRequiredSigner);
            Assert.False(viewModel.ShowTextBox);
            Assert.False(viewModel.CanEditRequiredSigner);

            _securityPolicyService.VerifyAll();
        }
        public RecurringJobSchedulerFacts()
        {
            _storage        = new Mock <JobStorage>();
            _client         = new Mock <IBackgroundJobClient>();
            _instantFactory = new Mock <IScheduleInstantFactory>();
            _throttler      = new Mock <IThrottler>();
            _token          = new CancellationTokenSource().Token;

            // Setting up the successful path
            _instant = new Mock <IScheduleInstant>();
            _instant.Setup(x => x.GetNextInstants(It.IsAny <DateTime?>())).Returns(new[] { _instant.Object.NowInstant });

            _timeZone = TimeZoneInfo.Local;

            _instantFactory.Setup(x => x.GetInstant(It.IsNotNull <CrontabSchedule>(), It.IsNotNull <TimeZoneInfo>()))
            .Returns(() => _instant.Object);

            _recurringJob = new Dictionary <string, string>
            {
                { "Cron", "* * * * *" },
                { "Job", JobHelper.ToJson(InvocationData.Serialize(Job.FromExpression(() => Console.WriteLine()))) },
                { "TimeZoneId", _timeZone.Id }
            };

            _connection = new Mock <IStorageConnection>();
            _storage.Setup(x => x.GetConnection()).Returns(_connection.Object);

            _connection.Setup(x => x.GetAllItemsFromSet("recurring-jobs"))
            .Returns(new HashSet <string> {
                RecurringJobId
            });

            _connection.Setup(x => x.GetAllEntriesFromHash(String.Format("recurring-job:{0}", RecurringJobId)))
            .Returns(_recurringJob);

            _client.Setup(x => x.Create(It.IsAny <Job>(), It.IsAny <IState>())).Returns("job-id");
        }
Exemple #17
0
        public async Task FilterTryNextTwoTimes()
        {
            var stack        = new List <string>();
            var callsCounter = new int[3];

            Func <IServerFilterContextInternal, ValueTask> last = context =>
            {
                Interlocked.Increment(ref callsCounter[2]);
                stack.Add("last");
                return(new ValueTask(Task.CompletedTask));
            };

            _filter
            .Setup(f => f.InvokeAsync(_context.Object, It.IsNotNull <Func <ValueTask> >()))
            .Returns <IServerFilterContextInternal, Func <ValueTask> >(async(context, next) =>
            {
                Interlocked.Increment(ref callsCounter[0]);
                stack.Add("filter1");
                await next().ConfigureAwait(false);
                await next().ConfigureAwait(false);
            });

            _filter2
            .Setup(f => f.InvokeAsync(_context.Object, It.IsNotNull <Func <ValueTask> >()))
            .Returns <IServerFilterContextInternal, Func <ValueTask> >(async(context, next) =>
            {
                Interlocked.Increment(ref callsCounter[1]);
                stack.Add("filter2");
                await next().ConfigureAwait(false);
                await next().ConfigureAwait(false);
            });

            await _sut.InvokeAsync(last).ConfigureAwait(false);

            stack.ShouldBe(new[] { "filter1", "filter2", "last" });
            callsCounter.ShouldBe(new[] { 1, 1, 1 });
        }
        public void DeleteInstanceThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
        {
            var customer = new Customer
            {
                Id = 187224
            };

            var mockSqlDialect = new Mock <ISqlDialect>();

            mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull <IObjectInfo>(), customer.Id)).Returns(new SqlQuery(""));

            var mockCommand = new Mock <IDbCommand>();

            mockCommand.Setup(x => x.ExecuteNonQuery()).Throws <InvalidOperationException>();

            var mockConnection = new Mock <IDbConnection>();

            mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);

            var mockDbDriver = new Mock <IDbDriver>();

            mockDbDriver.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);

            var session = new Session(
                ConnectionScope.PerTransaction,
                mockSqlDialect.Object,
                mockDbDriver.Object,
                new SessionListeners());

            var exception = Assert.Throws <MicroLiteException>(() => session.Delete(customer));

            Assert.NotNull(exception.InnerException);
            Assert.Equal(exception.InnerException.Message, exception.Message);

            // Command should still be disposed.
            mockCommand.VerifyAll();
        }
        public async Task SimpleTest()
        {
            var loggerMock = new Mock <ILogger>();

            loggerMock
            .Setup(logger => logger.Log <object>(
                       LogLevel.Information,
                       0,
                       It.IsNotNull <object>(),
                       null,
                       It.IsNotNull <Func <object, Exception, string> >()));

            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock
            .Setup(loggerFactory => loggerFactory.CreateLogger(It.IsNotNull <string>()))
            .Returns(loggerMock.Object);
            LoggingLogger.LoggerFactory = loggerFactoryMock.Object;

            var logger = Sys.GetLogger();

            logger.Info("Log1 {arg1} {arg2}", 1, "a");

            await Task.Delay(TimeSpan.FromSeconds(1));

            loggerFactoryMock.Verify(
                loggerFactory => loggerFactory.CreateLogger(It.IsNotNull <string>()),
                Times.Once());
            loggerMock.Verify(
                logger => logger.Log <object>(
                    LogLevel.Information,
                    0,
                    It.IsNotNull <object>(),
                    null,
                    It.IsNotNull <Func <object, Exception, string> >()),
                Times.Once());
        }
Exemple #20
0
        public async Task TestExisting()
        {
            // Setup
            var path           = "/This/is/a/deeplink/";
            var storageService = new Mock <IIOStorageService>(MockBehavior.Strict);

            storageService.Setup(r => r.DirectoryExists(path)).Returns(true);

            storageService.Setup(r => r.GetDirectoryNames(path)).Returns <string>(a => RandomEntries(2));
            storageService.Setup(r => r.GetFileNames(path)).Returns <string>(a => RandomEntries(3, true));

            var args = new FilerViewModel.FilerArgs {
                CurrentDirectory = path
            };

            var filerWebHandler = new Mock <IFilerWebHandler>(MockBehavior.Strict);

            filerWebHandler
            .Setup(r => r.GetDirectoryListingAsync(args, It.IsNotNull <CancellationToken>()))
            .Returns <FilerViewModel.FilerArgs, CancellationToken>((a, b) => this.GetRandomEntriesAsync(path, true));

            var navigationService = new Mock <IMvxNavigationService>(MockBehavior.Strict);

            this.Ioc.RegisterSingleton(navigationService.Object);
            this.Ioc.RegisterSingleton(filerWebHandler.Object);
            this.Ioc.RegisterSingleton(storageService.Object);

            var viewModel = this.Ioc.IoCConstruct <FilerViewModel>();

            // Exercise
            await viewModel.Init(args);

            // Verify
            Assert.AreEqual(8, viewModel.Listings.Count);

            Assert.AreEqual(1, viewModel.Listings.Count(t => t.Name.Equals("existing")));
        }
        public void UpdateInstanceBuildsAndExecutesQuery()
        {
            var customer = new Customer
            {
                Id = 187224
            };

            var rowsAffected = 1;

            var mockSqlDialect = new Mock <ISqlDialect>();

            mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull <IObjectInfo>(), customer)).Returns(new SqlQuery(""));

            var mockCommand = new Mock <IDbCommand>();

            mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected);

            var mockConnection = new Mock <IDbConnection>();

            mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);

            var mockDbDriver = new Mock <IDbDriver>();

            mockDbDriver.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);

            var session = new Session(
                ConnectionScope.PerTransaction,
                mockSqlDialect.Object,
                mockDbDriver.Object,
                new SessionListeners());

            session.Update(customer);

            mockSqlDialect.VerifyAll();
            mockDbDriver.VerifyAll();
            mockCommand.VerifyAll();
        }
        public async Task WHEN_unknown_CustomerId_SHOULD_return_null()
        {
            //Arrange
            var expectedCustomerId  = GetRandom.Guid();
            var expectedScope       = GetRandom.String(32);
            var expectedCultureInfo = TestingExtensions.GetRandomCulture();
            var customerRepository  = _container.CreateInstance <CustomerRepository>();

            _container.GetMock <IOvertureClient>()
            .Setup(r => r.SendAsync(It.Is <GetCustomerRequest>(
                                        param => param.CustomerId == expectedCustomerId)))
            .ReturnsAsync(null);

            //3.8 upgrade
            _container.GetMock <ICacheProvider>()
            .Setup(provider => provider.GetOrAddAsync(
                       It.IsNotNull <CacheKey>(),
                       It.IsNotNull <Func <Task <Customer> > >(),
                       It.IsAny <Func <Customer, Task> >(),
                       It.IsAny <CacheKey>()))
            .Returns <CacheKey, Func <Task <Customer> >, Func <Customer, Task>, CacheKey>(
                (key, func, arg3, arg4) => func())
            .Verifiable("This value must be proprelly cached by Id");

            //Act
            var customer = await customerRepository.GetCustomerByIdAsync(new GetCustomerByIdParam
            {
                CustomerId  = expectedCustomerId,
                Scope       = expectedScope,
                CultureInfo = expectedCultureInfo
            });

            //Assert
            customer.Should().BeNull();

            _container.GetMock <ICacheProvider>().VerifyAll();
        }
Exemple #23
0
        private static Mock <IDamProvider> CreateDamProvider()
        {
            Mock <IDamProvider> damProvider = new Mock <IDamProvider>();

            List <ProductMainImage> dummyMainImages = new List <ProductMainImage>
            {
                new ProductMainImage
                {
                    ProductId = GetRandom.String(32),
                    VariantId = GetRandom.String(32),
                    ImageUrl  = GetRandom.WwwUrl(),
                }
            };

            List <AllProductImages> dummyAllProductImages = new List <AllProductImages>
            {
                new AllProductImages
                {
                    ProductId           = GetRandom.String(32),
                    VariantId           = GetRandom.String(32),
                    SequenceNumber      = GetRandom.PositiveInt(),
                    ImageUrl            = GetRandom.WwwUrl(),
                    ThumbnailUrl        = GetRandom.WwwUrl(),
                    ProductZoomImageUrl = GetRandom.WwwUrl(),
                }
            };

            damProvider.Setup(context => context.GetProductMainImagesAsync(It.IsNotNull <GetProductMainImagesParam>()))
            .ReturnsAsync(dummyMainImages)
            .Verifiable();

            damProvider.Setup(context => context.GetAllProductImagesAsync(It.IsNotNull <GetAllProductImagesParam>()))
            .ReturnsAsync(dummyAllProductImages)
            .Verifiable();

            return(damProvider);
        }
Exemple #24
0
        public void UnicastMessage_AcknowlegeSlaveException()
        {
            var mock = new Mock <ModbusTransport>()
            {
                CallBase = true
            };
            var transport  = mock.Object;
            int callsCount = 0;

            // set the wait to retry property to a small value so the test completes quickly
            transport.WaitToRetryMilliseconds = 5;

            mock.Setup(t => t.Write(It.IsNotNull <IModbusMessage>()));

            // return a slave exception a greater number of times than number of retries to make sure we aren't just retrying
            mock.Setup(t => t.ReadResponse <ReadHoldingInputRegistersResponse>())
            .Returns(() =>
            {
                if (callsCount < transport.Retries + 1)
                {
                    ++callsCount;
                    return(new SlaveExceptionResponse(1, Modbus.ReadHoldingRegisters + Modbus.ExceptionOffset, Modbus.Acknowledge));
                }

                return(new ReadHoldingInputRegistersResponse(Modbus.ReadHoldingRegisters, 1, new RegisterCollection(1)));
            });

            mock.Setup(t => t.OnValidateResponse(It.IsNotNull <IModbusMessage>(), It.IsNotNull <IModbusMessage>()));

            var request          = new ReadHoldingInputRegistersRequest(Modbus.ReadHoldingRegisters, 1, 1, 1);
            var expectedResponse = new ReadHoldingInputRegistersResponse(Modbus.ReadHoldingRegisters, 1, new RegisterCollection(1));
            var response         = transport.UnicastMessage <ReadHoldingInputRegistersResponse>(request);

            Assert.Equal(transport.Retries + 1, callsCount);
            Assert.Equal(expectedResponse.MessageFrame, response.MessageFrame);
            mock.VerifyAll();
        }
Exemple #25
0
        public void UnicastMessage_TimeoutException()
        {
            var mock = new Mock <ModbusTransport>()
            {
                CallBase = true
            };
            var transport              = mock.Object;
            int writeCallsCount        = 0;
            int readResponseCallsCount = 0;

            mock.Setup(t => t.Write(It.IsNotNull <IModbusMessage>()))
            .Callback(() => ++ writeCallsCount);

            mock.Setup(t => t.ReadResponse <ReadCoilsInputsResponse>())
            .Callback(() => ++ readResponseCallsCount)
            .Throws <TimeoutException>();

            var request = new ReadCoilsInputsRequest(Modbus.ReadInputs, 2, 3, 4);

            Assert.Throws <TimeoutException>(() => transport.UnicastMessage <ReadCoilsInputsResponse>(request));
            Assert.Equal(Modbus.DefaultRetries + 1, writeCallsCount);
            Assert.Equal(Modbus.DefaultRetries + 1, readResponseCallsCount);
            mock.VerifyAll();
        }
Exemple #26
0
        public void UnicastMessage_TooManyFailingExceptions(Type exceptionType)
        {
            var mock = new Mock <ModbusTransport>()
            {
                CallBase = true
            };
            var transport              = mock.Object;
            int writeCallsCount        = 0;
            int readResponseCallsCount = 0;

            mock.Setup(t => t.Write(It.IsNotNull <IModbusMessage>()))
            .Callback(() => ++ writeCallsCount);

            mock.Setup(t => t.ReadResponse <ReadCoilsInputsResponse>())
            .Callback(() => ++ readResponseCallsCount)
            .Throws((Exception)Activator.CreateInstance(exceptionType));

            var request = new ReadCoilsInputsRequest(Modbus.ReadCoils, 2, 3, 4);

            Assert.Throws(exceptionType, () => transport.UnicastMessage <ReadCoilsInputsResponse>(request));
            Assert.Equal(transport.Retries + 1, writeCallsCount);
            Assert.Equal(transport.Retries + 1, readResponseCallsCount);
            mock.VerifyAll();
        }
        public void Mfi_FinishDecompilation_UpdateProcedureList()
        {
            Given_MainFormInteractor();
            Given_LoadPreferences();
            Given_DecompilerInstance();
            Given_XmlWriter();
            Given_SavePrompt(false);
            decompiler.Setup(d => d.AnalyzeDataFlow());
            decompiler.Setup(d => d.ReconstructTypes());
            decompiler.Setup(d => d.StructureProgram());
            fsSvc.Setup(f => f.MakeRelativePath("foo.dcproject", "foo.exe")).Returns("foo.exe");
            brSvc.Setup(b => b.Reload())
            .Verifiable();
            procSvc.Setup(p => p.Load(
                              It.IsNotNull <Project>()))
            .Verifiable();

            When_CreateMainFormInteractor();
            interactor.OpenBinary("foo.exe");

            Assert.AreSame(interactor.InitialPageInteractor, interactor.CurrentPhase);
            interactor.FinishDecompilation();
            procSvc.Verify();
        }
        private void Given_DecompilerInstance()
        {
            this.decompiler = new Mock <IDecompiler>();
            // Having a compiler presupposes having a project.
            var platform = mockFactory.CreateMockPlatform();
            var mem      = new ByteMemoryArea(Address.Ptr32(0x00010000), new byte[100]);
            var project  = new Project
            {
                Programs = { new Program
                             {
                                 Filename   = "foo.exe",
                                 SegmentMap = new SegmentMap(
                                     mem.BaseAddress,
                                     new ImageSegment(".text", mem, AccessMode.ReadExecute)),
                                 Platform     = platform.Object,
                                 Architecture = platform.Object.Architecture,
                             } }
            };

            dcSvc.Setup(d => d.Decompiler).Returns(decompiler.Object);
            dcSvc.Setup(d => d.ProjectName).Returns("foo.exe");
            decompiler.Setup(d => d.Project).Returns(project);
            decompiler.Setup(d => d.Load(It.IsNotNull <string>(), null, null)).Returns(false);
        }
Exemple #29
0
        public void ExecuteWithUpdateAuditStateTest()
        {
            //Arrange
            var updateParam = new Domain.AuditState.AuditState()
            {
                Active = true,
                Code   = "Code 2",
                Color  = "#FFCC22",
                Name   = "Programada"
            };

            var mockAuditStateRepository = new Mock <IAuditStateRepository>();

            mockAuditStateRepository.Setup(e => e.Update(It.IsNotNull <Domain.AuditState.AuditState>())).Returns(updateParam);
            mockAuditStateRepository.Setup(e => e.Get(It.IsNotNull <int>())).Returns(updateParam);

            UpdateAuditStateUseCase useCase = new UpdateAuditStateUseCase(mockAuditStateRepository.Object);

            //Act
            var res = useCase.Execute(updateParam);

            //Assert
            Assert.IsType <AuditStateOutput>(res);
        }
Exemple #30
0
        public async Task PutConcertThrowsDbUpdateExceptionTest()
        {
            // Arrange
            var mock    = new Mock <IUpdateEntry>();
            var entries = new List <IUpdateEntry>();

            entries.Add(mock.Object);

            int     testId     = 1;
            Concert concert    = GetTestConcerts().FirstOrDefault(p => p.Id == testId);
            var     mockLogger = new Mock <ILogger <ConcertsController> >();
            var     mockRepo   = new Mock <IConcertRepository>();

            mockRepo.Setup(c => c.ChangeState(concert, EntityState.Modified))
            .Verifiable();
            mockRepo.Setup(c => c.SaveChanges()).Throws(
                new DbUpdateConcurrencyException(It.IsNotNull <string>(), entries));
            mockRepo.Setup(c => c.ConcertExists(testId)).Returns(true);
            var controller = new ConcertsController(mockRepo.Object, mockLogger.Object);

            // Act Assert
            await Assert.ThrowsAsync <DbUpdateConcurrencyException>(() =>
                                                                    controller.PutConcert(testId, concert));
        }