Beispiel #1
6
        public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();
            var settings = new Mock<IApplicationSettings>();
            var mockPipeline = new Mock<IHubPipelineInvoker>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState);

            var prinicipal = new Mock<IPrincipal>();

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);
            request.Setup(m => m.User).Returns(prinicipal.Object);

            // setup context
            chat.Context = new HubCallerContext(request.Object, connectionId);

            return chat;
        }
 public void MessagePassedToConstructorIsReturned()
 {
     const string Msg = "msg";
     var innerRule = new Mock<IRule<string>>();
     var rule = new NotRule<string>(innerRule.Object, Msg);
     Assert.AreEqual(Msg, rule.Message);
 }
        public void Should_Return_Page_Html_Content()
        {
            // Create html content
            var htmlContent = TestDataProvider.CreateNewHtmlContent();
            var pageContent = TestDataProvider.CreateNewPageContent(htmlContent);
            htmlContent.Status = ContentStatus.Published;

            // Create command
            var command = new GetPageHtmlContentCommand();
            command.UnitOfWork = new Mock<IUnitOfWork>().Object;
            command.Repository = new Mock<IRepository>().Object;

            // Mock content service
            var serviceMock = new Mock<IContentService>();
            serviceMock
                .Setup(f => f.GetPageContentForEdit(pageContent.Id))
                .Returns(new Tuple<PageContent, Content>(pageContent, htmlContent));
            command.ContentService = serviceMock.Object;

            // Execute command
            var result = command.Execute(pageContent.Id);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Id, pageContent.Id);
            Assert.AreEqual(result.ContentId, htmlContent.Id);
            Assert.AreEqual(result.ContentName, htmlContent.Name);
            Assert.AreEqual(result.ContentVersion, htmlContent.Version);
            Assert.AreEqual(result.CurrentStatus, htmlContent.Status);
            Assert.AreEqual(result.PageId, pageContent.Page.Id);
            Assert.AreEqual(result.RegionId, pageContent.Region.Id);
            Assert.AreEqual(result.LiveFrom, htmlContent.ActivationDate);
            Assert.AreEqual(result.LiveTo, htmlContent.ExpirationDate);
        }
Beispiel #4
1
    public Task TestFileSave() {
      var response = new FileState {
        Name = "newBekti.png",
        Url = new Uri("https://www.parse.com/newBekti.png"),
        MimeType = "image/png"
      };
      var mockController = new Mock<IParseFileController>();
      mockController.Setup(obj => obj.SaveAsync(It.IsAny<FileState>(),
          It.IsAny<Stream>(),
          It.IsAny<string>(),
          It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
          It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
      var mockCurrentUserController = new Mock<IParseCurrentUserController>();
      ParseCorePlugins.Instance.FileController = mockController.Object;
      ParseCorePlugins.Instance.CurrentUserController = mockCurrentUserController.Object;

      ParseFile file = new ParseFile("bekti.jpeg", new MemoryStream(), "image/jpeg");
      Assert.AreEqual("bekti.jpeg", file.Name);
      Assert.AreEqual("image/jpeg", file.MimeType);
      Assert.True(file.IsDirty);

      return file.SaveAsync().ContinueWith(t => {
        Assert.False(t.IsFaulted);
        Assert.AreEqual("newBekti.png", file.Name);
        Assert.AreEqual("image/png", file.MimeType);
        Assert.AreEqual("https://www.parse.com/newBekti.png", file.Url.AbsoluteUri);
        Assert.False(file.IsDirty);
      });
    }
        public void GetAnonymousCompetitions()
        {
            var repository = new RepositoryForTests<Competition>();
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = true,
                Name = "Public1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = false,
                Name = "Private1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });

            var rightsHelperMock = new Mock<IRightsHelper>();

            var userRolesInfoMock = new Mock<IRepository<UserRolesInfo>>();

            var competitions = new CompetitionsLogic(repository, userRolesInfoMock.Object, rightsHelperMock.Object);

            var result = competitions.GetCompetitions();
            Assert.AreEqual(1, result.Count());
        }
        protected void SetupSubject()
        {
            MockUpdatableAuth = new Mock<IUpdatable<UserAuthentication>>();

            _passwords = new Passwords();
            _translateUserUserAuth = new DataUserToAccountUserTranslator();

            _userAuthProvider = new UserAuthenticationProvider(
                _translateUserUserAuth
                , MockRetrievableUserByEmail.Object
                , MockRetrievableAuthyId.Object
                , MockUpdatableAuth.Object
                , MockCreatableAuth.Object
                , _passwords
                , MockDeletableAuth.Object);

            Subject = new UserAccountProvider(
                _userAuthProvider
                , MockCreateableUser.Object
                , MockRetrievableUserById.Object
                , MockRetrievableUserByEmail.Object
                , MockDeletableUser.Object
                , MockUpdateableUser.Object
                , _translateUserUserAuth
                , MockSystemTime.Object);
        }
        public async Task Run_WhenCheckerThrows_FailureResult()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ThrowsAsync(new Exception("error " + mock.Object.Name));
                    return mock;
                })
                .ToArray();
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.False);
            Assert.That(result.Status, Is.EqualTo("failure"));
            Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
            foreach (var checkerMock in checkerMocks)
            {
                var checkResult = result.Results.Single(x => x.Checker == checkerMock.Object.Name);
                Assert.That(checkResult.Checker, Is.EqualTo(checkerMock.Object.Name));
                Assert.That(checkResult.Passed, Is.False);
                Assert.That(checkResult.Output, Is.EqualTo("error " + checkerMock.Object.Name));
            }
        }
Beispiel #8
1
        public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider()
        {
            // Arrange            
            IPackage packageA = PackageUtility.CreatePackage("A",
                                                            "1.0",
                                                             dependencies: new List<PackageDependency> {
                                                                 new PackageDependency("B")
                                                             });
            IPackage packageB = PackageUtility.CreatePackage("B");
            var repository = new Mock<PackageRepositoryBase>();
            repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
            var dependencyProvider = repository.As<IDependencyResolver>();
            dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest))
                              .Returns(packageB).Verifiable();
            var localRepository = new MockPackageRepository();

            IPackageOperationResolver resolver = new InstallWalker(localRepository,
                                                             repository.Object,
                                                             NullLogger.Instance,
                                                             ignoreDependencies: false,
                                                             allowPrereleaseVersions: false);


            // Act
            var operations = resolver.ResolveOperations(packageA).ToList();

            // Assert
            Assert.Equal(2, operations.Count);
            Assert.Equal(PackageAction.Install, operations.First().Action);
            Assert.Equal(packageB, operations.First().Package);
            Assert.Equal(PackageAction.Install, operations.Last().Action);
            Assert.Equal(packageA, operations.Last().Package);

            dependencyProvider.Verify();
        }
 public void GetUnitOfWorkFactory_uses_same_session_factory_as_provider()
 {
     var factory = new Mock<ISessionFactory>();
     var provider = new HibernateDataServicesProvider(factory.Object);
     var unitOfWorkFactory = (HibernateUnitOfWorkFactory)provider.GetUnitOfWorkFactory();
     Assert.AreEqual(factory.Object, unitOfWorkFactory.SessionFactory);
 }
Beispiel #10
1
 public void Init()
 {
     connectionMock = new Mock<IConnectionChecker>();
     loginMock = new Mock<IAuthorizer>();
     converterMock = new Mock<IUrlConverter>();
     dataProviderMock = new Mock<IDatabaseProvider>();
 }
Beispiel #11
1
        public void TestInitialize()
        {

            IFhirModel _fhirModel;
            FhirPropertyIndex _propIndex;
            ResourceVisitor _resourceVisitor;
            ElementIndexer _elementIndexer;
            var _indexStoreMock = new Mock<IIndexStore>();

            var spPatientName = new SearchParamDefinition() { Resource = "Patient", Name = "name", Description = @"A portion of either family or given name of the patient", Type = SearchParamType.String, Path = new string[] { "Patient.name", } };
            var searchParameters = new List<SearchParamDefinition> { spPatientName };
            var resources = new Dictionary<Type, string> { { typeof(Patient), "Patient" }, { typeof(HumanName), "HumanName" } };
            var enums = new List<Type>();
            //CK: I use real objects: saves me a lot of mocking and provides for a bit of integration testing.
            _fhirModel = new FhirModel(resources, searchParameters, enums);
            _propIndex = new FhirPropertyIndex(_fhirModel, new List<Type> { typeof(Patient), typeof(HumanName) });
            _resourceVisitor = new ResourceVisitor(_propIndex);
            _elementIndexer = new ElementIndexer(_fhirModel);

            //_indexStoreMock.Setup(ixs => ixs.Save(It.IsAny<IndexValue>))

            sutLimited = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);

            _fhirModel = new FhirModel(); //For this test I want all available types and searchparameters.
            _propIndex = new FhirPropertyIndex(_fhirModel);
            _resourceVisitor = new ResourceVisitor(_propIndex);
            _elementIndexer = new ElementIndexer(_fhirModel);

            sutFull = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);
        }
 public void IsInvalidWhen_UserName_MatchesExistingUser()
 {
     const string userName = "******";
     const string userDisplayName = "Bruce Wayne";
     const string personDisplayName = "Adam West";
     var command = new CreatePersonCommand
     {
         DisplayName = personDisplayName,
         UserName = userName,
     };
     var queryProcessor = new Mock<IProcessQueries>(MockBehavior.Strict);
     queryProcessor.Setup(m => m.Execute(It.Is<GetUserByNameQuery>(q => q.Name == command.UserName)))
         .Returns(new User { Person = new Person { DisplayName = userDisplayName, } });
     var validator = new CreatePersonValidator(queryProcessor.Object);
     var results = validator.Validate(command);
     results.IsValid.ShouldBeFalse();
     results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
     var error = results.Errors.SingleOrDefault(e => e.PropertyName == "UserName");
     error.ShouldNotBeNull();
     // ReSharper disable PossibleNullReferenceException
     error.ErrorMessage.ShouldEqual(string.Format(
         ValidateUser.FailedBecauseNameMatchedEntity,
             userName));
     // ReSharper restore PossibleNullReferenceException
 }
        public void CallTest()
        {
            //Arrange
            var domainStatProjectState1 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = true };
            var domainStatProjectState2 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = false };
            var domainStatProjectState3 = new DomainStatProjectState() { Producer = "ProductName", IsSuccessfulUpload = true };

            var domainReport = new DomainReport();

            var statProjectDeletionFilter = new Mock<IStatProjectDeletionFilter>();

            var taggerIPhoneDeletionsFilter = new TaggerIPhoneDeletionsFilter();
            taggerIPhoneDeletionsFilter.Set(statProjectDeletionFilter.Object);

            //Act
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState1, domainReport);
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState2, domainReport);
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState3, domainReport);

            //Assert
            Assert.AreEqual(1, domainReport.TaggerIPhoneDeletions);
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState1, domainReport), Times.Once());
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState2, domainReport), Times.Once());
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState3, domainReport), Times.Once());
        }
        public void GetAllShouldReturnTodos()
        {
            var data = new List<Todo>
            {
                new Todo {Id = 1},
                new Todo {Id = 2},
                new Todo {Id = 3},
            }.AsQueryable();

            var mockSet = new Mock<DbSet<Todo>>();
            mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            var mockContext = new Mock<ApplicationDbContext>();
            mockContext.Setup(c => c.Todos).Returns(mockSet.Object);

            var service = new TodoRepository(mockContext.Object);
            var todos = service.GetAll().ToList();

            Assert.AreEqual(3, todos.Count);
            Assert.AreEqual(1, todos[0].Id);
            Assert.AreEqual(2, todos[1].Id);
            Assert.AreEqual(3, todos[2].Id);
        }
        public void ShouldReturnNameOfLogFactory() {
            var logFactoryRegistry = new LogFactoryRegistry();
            var mylogger = new Mock<ITaskLogFactory>().Object;

            logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
            Assert.That(logFactoryRegistry.FindNameForLogFactory(mylogger), Is.EqualTo("mylogger"));
        }
 public void GetCurrentSession_delegates_to_session_factory()
 {
     var factory = new Mock<ISessionFactory>();
     var provider = new HibernateDataServicesProvider(factory.Object);
     provider.GetCurrentSession();
     factory.Verify(sessionFactory => sessionFactory.GetCurrentSession());
 }
        public void ShouldReturnLogFactoryByName() {
            var logFactoryRegistry = new LogFactoryRegistry();
            var mylogger = new Mock<ITaskLogFactory>().Object;

            logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
            Assert.That(logFactoryRegistry.GetLogFactoryByName("mylogger"), Is.SameAs(mylogger));
        }
        public void scenario_10()
        {
            var propertyUpgradeUoW = new Mock<IPropertyUpgradeUoW>();
            propertyUpgradeUoW.Setup(x => x.ProductTypeRepository.Get())
                .Returns(GetDomainProductTypes());
            var calculator = new CityStorageCalculator(propertyUpgradeUoW.Object);
            var cityStorage = GetCityStorage();
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity = 8;
            var request = new CalculateStorageRequest
            {
                CityStorage = cityStorage,
                NewProductQuantities = new[]
                {
                    new SimGame.Handler.Entities.Product
                    {
                        ProductTypeId = 3,
                        Quantity = 2
                    },
                }
            };

            var ret = calculator.CalculateNewStorageAmounts(request);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity.ShouldEqual(6);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity.ShouldEqual(10);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity.ShouldEqual(8);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity.ShouldEqual(8);
        }
        public void When_a_navigation_button_is_clicked_the_associated_page_should_be_displayed()
        {
            this.testContainer = new UnityContainer();
            this.autoMocker = new AutoMoq.AutoMoqer(this.testContainer);

            var mockPageViewModel = new Mock<IPageViewModel>();
            mockPageViewModel.SetupGet(page => page.Title).Returns("Page1");
            IPageViewModel pageViewModel = mockPageViewModel.Object;

            var viewModelFactoryMock = new Mock<IViewModelFactory>();
            viewModelFactoryMock.Setup(f => f.Get<StartPageViewModel>()).Returns(() => new StartPageViewModel(new Mock<INavigationService>().Object));
            this.autoMocker.SetInstance(viewModelFactoryMock.Object);

            var navigationServiceMock = this.navigationServiceMock;
            navigationServiceMock.Setup(vm => vm.GetDefaultPagesByNames())
                                 .Returns(
                                     new Dictionary<string, Func<IPageViewModel>>
                                         {
                                             { "page1", () => pageViewModel },
                                             { "page2", () => null },
                                             { "page3", () => null },
                                             { "page4", () => null },
                                         });

            INavigationService navigationService = navigationServiceMock.Object;
            this.autoMocker.SetInstance(navigationService);

            var applicationViewModel = this.autoMocker.Resolve<ApplicationViewModel>();

            applicationViewModel.LeftNavigationButtonCollection.Single(btn => btn.DisplayText == "page1").ExecuteAsync(null);

            navigationServiceMock.VerifySet(ns => ns.CurrentPage = pageViewModel);
        }
Beispiel #20
1
        public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Agent = new ClientAgent(mockedConnectionObject, "Chat");

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();
            chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState);

            // setup context
            chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId);

            return chat;
        }
 public void ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False()
 {
     //------------Setup for test--------------------------
     var mainViewModel = new Mock<IMainViewModel>();
     var connectControlSingleton = new Mock<IConnectControlSingleton>();
     var env1 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
     var env2 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
     var connectControlEnvironments = new ObservableCollection<IConnectControlEnvironment>();
     var controEnv1 = new Mock<IConnectControlEnvironment>();
     var controEnv2 = new Mock<IConnectControlEnvironment>();
     controEnv1.Setup(c => c.EnvironmentModel).Returns(env1);
     controEnv2.Setup(c => c.EnvironmentModel).Returns(env2);
     controEnv1.Setup(c => c.IsConnected).Returns(true);
     connectControlEnvironments.Add(controEnv2.Object);
     connectControlEnvironments.Add(controEnv1.Object);
     connectControlSingleton.Setup(c => c.Servers).Returns(connectControlEnvironments);
     var environmentRepository = new Mock<IEnvironmentRepository>();
     ICollection<IEnvironmentModel> environments = new Collection<IEnvironmentModel>
         {
             env1
         };
     environmentRepository.Setup(e => e.All()).Returns(environments);
     var viewModel = new ConnectControlViewModel(mainViewModel.Object, environmentRepository.Object, e => { }, connectControlSingleton.Object, "TEST : ", false);
     //------------Execution-------------------------------
     int serverIndex;
     var didAddNew = viewModel.AddNewServer(out serverIndex, i => { });
     //------------Assert----------------------------------
     Assert.IsNotNull(viewModel);
     Assert.IsFalse(didAddNew);
 }
        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
Beispiel #23
0
        public SelectTests()
        {
            var html = @"

            <div>
            <span class=""center"">here</span>
            <a href=""http://google.com"">link</a>
            <div class=""dollar"">$6,566.00</div>
            <span class=""address"">4332 Forest Hill Blvd<br>West Palm Beach, FL 33406</span>
            <div id=""match-tests"">
            <li>6,566</li>
            <li>6</li>
            <li>8,975</li>
            <li>6,566,888</li>
            </div>
            <div id=""match-tests"">
            <li>10,566</li>
            <li>3</li>
            <li>1,975</li>
            <li>2,566,888</li>
            </div>
            </div>

            ";
            var httpRequest = new Mock<IHttpRequest>();
            httpRequest.Setup(x => x.Download()).Returns(System.Text.Encoding.UTF8.GetBytes(html));

            var requestFactory = new Mock<IHttpRequestFactory>();
            requestFactory.Setup(x => x.Create(It.IsAny<IHttpWire>())).Returns(httpRequest.Object);
            _requestFactory = requestFactory.Object;
        }
        private static IPackageService CreateService(
            Mock<IEntityRepository<PackageRegistration>> packageRegistrationRepository = null,
            Mock<IEntityRepository<Package>> packageRepository = null,
            Mock<IEntityRepository<PackageStatistics>> packageStatsRepo = null,
            Mock<IEntityRepository<PackageOwnerRequest>> packageOwnerRequestRepo = null,
            Mock<IIndexingService> indexingService = null,
            Action<Mock<PackageService>> setup = null)
        {
            packageRegistrationRepository = packageRegistrationRepository ?? new Mock<IEntityRepository<PackageRegistration>>();
            packageRepository = packageRepository ?? new Mock<IEntityRepository<Package>>();
            packageStatsRepo = packageStatsRepo ?? new Mock<IEntityRepository<PackageStatistics>>();
            packageOwnerRequestRepo = packageOwnerRequestRepo ?? new Mock<IEntityRepository<PackageOwnerRequest>>();
            indexingService = indexingService ?? new Mock<IIndexingService>();

            var packageService = new Mock<PackageService>(
                packageRegistrationRepository.Object,
                packageRepository.Object,
                packageStatsRepo.Object,
                packageOwnerRequestRepo.Object,
                indexingService.Object);

            packageService.CallBase = true;

            if (setup != null)
            {
                setup(packageService);
            }

            return packageService.Object;
        }
        private ExecuteMessage RunOutput(bool expectCorrectInput)
        {
            var esbMethod = new DeleteScheduledResource();
            var factory = new Mock<IServerSchedulerFactory>();
            var model = new Mock<IScheduledResourceModel>();
            var ws = new Mock<IWorkspace>();
            var trigger = new ScheduleTrigger(TaskState.Disabled,
                                              new Dev2DailyTrigger(new TaskServiceConvertorFactory(), new DailyTrigger(21)),
                                              new Dev2TaskService(new TaskServiceConvertorFactory()),
                                              new TaskServiceConvertorFactory());
            var res = new ScheduledResource("a", SchedulerStatus.Enabled, DateTime.Now, trigger, "dave");
            var security = new Mock<ISecurityWrapper>();
            esbMethod.SecurityWrapper = security.Object;

            Dictionary<string, StringBuilder> inp = new Dictionary<string, StringBuilder>();
            factory.Setup(
                a =>
                a.CreateModel(GlobalConstants.SchedulerFolderId, It.IsAny<ISecurityWrapper>())).Returns(model.Object);
            Dev2JsonSerializer serialiser = new Dev2JsonSerializer();
            if(expectCorrectInput)
            {

                model.Setup(a => a.DeleteSchedule(It.IsAny<ScheduledResource>())).Verifiable();
                inp.Add("Resource", serialiser.SerializeToBuilder(res));
            }

            esbMethod.SchedulerFactory = factory.Object;

            var output = esbMethod.Execute(inp, ws.Object);
            if(expectCorrectInput)
                model.Verify(a => a.DeleteSchedule(It.IsAny<ScheduledResource>()));
            return serialiser.Deserialize<ExecuteMessage>(output);

        }
 public void Initialise()
 {
     _blogRepo = new SimpleRepository<Data.Blog>(new InMemoryRepositoryDataSource<Data.Blog>(new List<Data.Blog> { new Data.Blog { Id = 1, AuthoritiveUrl = "http://blog.test.con" } }));
     _templateRepo =  new SimpleRepository<BlogTemplate>(new InMemoryRepositoryDataSource<BlogTemplate>());
     _mockHttpContext = new Mock<IHttpContextService>();
     _mockHttpContext.Setup(h => h.RequestUrl).Returns(new Uri("http://blog.test.con/blah"));
 }
        protected void Arrange()
        {
            var random = new Random();
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint)random.Next(0, 1000);
            _readBufferSize = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
                .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
                .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.IsOpen)
                .Returns(true);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestClose(_handle));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int)_bufferSize);
        }
        public void TestAddInterviewerToFieldworkOfficesAsync_WhenExecuted_CallsClientPostAsJsonAsyncWithCorrectArgs()
        {
            const string interviewerId = "interviewerId";
            const string fieldworkOfficeId = "Barcelona";

            var expectedUrl = string.Format(CultureInfo.InvariantCulture, "{0}interviewers/{1}/Offices",
                ServiceAddress,
                interviewerId);

            var mockedNfieldConnection = new Mock<INfieldConnectionClient>();
            var mockedHttpClient = CreateHttpClientMock(mockedNfieldConnection);

            mockedHttpClient
                .Setup(client => client.PostAsJsonAsync(It.IsAny<string>(), It.IsAny<InterviewerFieldworkOfficeModel>()))
                .Returns(CreateTask(HttpStatusCode.OK));

            var target = new NfieldInterviewersService();
            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            target.AddInterviewerToFieldworkOfficesAsync(interviewerId, fieldworkOfficeId);

            mockedHttpClient.Verify(
                h =>
                    h.PostAsJsonAsync(expectedUrl, It.Is<InterviewerFieldworkOfficeModel>(f => f.OfficeId == fieldworkOfficeId)),
                Times.Once());
        }
Beispiel #29
0
        public void ShouldReturnDependenciesMarkedWithAttribute()
        {
            ITask dep = new Mock<ITask>().Object;
            var task = new ATask {A = dep};

            Assert.That(task.Dependencies.Select(d => d.Task), Is.EquivalentTo(new[] {dep}));
        }
        public void ListAll_PerformsCorrectRequest()
        {
            //Setup
            var request = new CategoriesStub("DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            var response = new RestResponse<List<Category>> {Data = new List<Category>()};

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("CountryCode", "NL"));
            restReq.SetupSet(x => x.RootElement = "Categories");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/categories");
            restClient.Setup(x => x.Execute<List<Category>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            List<Category> cats = request.WhereCountryCode(CountryCode.NL).ListAll();
            Assert.IsTrue(cats.Count == 0);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
            public async Task PrereleaseViewersOnOwningPublicationsLatestReleaseCanViewMethodology()
            {
                var expectedReleaseRolesToPass = ListOf(PrereleaseViewer);

                await ForEachReleaseRoleAsync(async releaseRole =>
                {
                    var methodologyRepository = new Mock<IMethodologyRepository>(Strict);
                    var userPublicationRoleRepository = new Mock<IUserPublicationRoleRepository>(Strict);
                    var userReleaseRoleRepository = new Mock<IUserReleaseRoleRepository>(Strict);
                    var preReleaseService = new Mock<IPreReleaseService>(Strict);

                    var release = new Release
                    {
                        ReleaseName = "2000",
                        TimePeriodCoverage = TimeIdentifier.AcademicYear,
                        Publication = new Publication(),
                    };

                    var contentDbContextId = Guid.NewGuid().ToString();
                    await using (var contentDbContext = DbUtils.InMemoryApplicationDbContext(contentDbContextId))
                    {
                        await contentDbContext.AddAsync(release);
                        await contentDbContext.SaveChangesAsync();
                    }

                    await using (var contentDbContext = DbUtils.InMemoryApplicationDbContext(contentDbContextId))
                    {
                        var handler = new ViewSpecificMethodologyAuthorizationHandler(
                            contentDbContext,
                            methodologyRepository.Object,
                            userPublicationRoleRepository.Object,
                            userReleaseRoleRepository.Object,
                            preReleaseService.Object
                        );

                        methodologyRepository.Setup(s =>
                                s.GetOwningPublication(MethodologyVersion.MethodologyId))
                            .ReturnsAsync(release.Publication);

                        methodologyRepository.Setup(s =>
                                s.GetAllPublicationIds(MethodologyVersion.MethodologyId))
                            .ReturnsAsync(new List<Guid> { release.Publication.Id });

                        userPublicationRoleRepository.SetupPublicationOwnerRoleExpectations(
                            UserId, release.Publication, false);

                        userReleaseRoleRepository
                            .Setup(s => s.IsUserEditorOrApproverOnLatestRelease(UserId, release.Publication.Id))
                            .ReturnsAsync(false);

                        userReleaseRoleRepository
                            .Setup(s => s.IsUserPrereleaseViewerOnLatestPreReleaseRelease(UserId, release.Publication.Id))
                            .ReturnsAsync(expectedReleaseRolesToPass.Contains(releaseRole));

                        if (releaseRole == PrereleaseViewer)
                        {
                            preReleaseService
                                .Setup(s => s.GetPreReleaseWindowStatus(
                                    It.Is<Release>(r => r.Id == release.Id),
                                    It.IsAny<DateTime>()))
                                .Returns(new PreReleaseWindowStatus { Access = PreReleaseAccess.Within });
                        }

                        var user = CreateClaimsPrincipal(UserId);
                        var authContext =
                            CreateAuthorizationHandlerContext<ViewSpecificMethodologyRequirement, MethodologyVersion>
                                (user, MethodologyVersion);

                        await handler.HandleAsync(authContext);
                        VerifyAllMocks(
                            methodologyRepository,
                            userPublicationRoleRepository,
                            userReleaseRoleRepository,
                            preReleaseService);

                        // As the user has a role on the latest Release of the owning Publication of this Methodology
                        // they are allowed to view it.
                        Assert.Equal(expectedReleaseRolesToPass.Contains(releaseRole), authContext.HasSucceeded);
                    }
                });
            }
 public AddressBookServiceTests()
 {
     _addressBookLoader = new Mock <IAddressBookLoader>();
     _logger            = new Mock <ILogger <AddressBookService> >();
 }
 public void SetUp()
 {
     _resolverContextMock = new Mock<IResolverContext>();
 }
Beispiel #34
0
        public void SetUp()
        {
            _voucherRepository = new Mock <IVoucherRepository>();
            _voucherRepository.Setup(x => x.GetAllVouchers()).Returns(() => new GetAllVouchersResponse
            {
                VoucherDetails = new List <VoucherDetails>
                {
                    new VoucherDetails
                    {
                        Voucher = new VoucherRecord
                        {
                            Code     = "VOUCHER_CODE",
                            Quantity = 2,
                            Price    = "1^"
                        },
                        AllowedDeliveryTypes = new List <VoucherDeliveryTypeRecord>
                        {
                            new VoucherDeliveryTypeRecord
                            {
                                DeliveryType = new DeliveryTypeRecord
                                {
                                    Name = "Collection"
                                }
                            }
                        },
                        AllowedSizes = new List <VoucherSizeRecord>
                        {
                            new VoucherSizeRecord
                            {
                                Size = new SizeRecord
                                {
                                    Name = "Small"
                                }
                            }
                        }
                    },
                    new VoucherDetails
                    {
                        Voucher = new VoucherRecord
                        {
                            Code     = "VOUCHER_CODE",
                            Quantity = 2,
                            Price    = "1400"
                        },
                        AllowedDeliveryTypes = new List <VoucherDeliveryTypeRecord>
                        {
                            new VoucherDeliveryTypeRecord
                            {
                                DeliveryType = new DeliveryTypeRecord
                                {
                                    Name = "Delivery"
                                }
                            }
                        },
                        AllowedSizes = new List <VoucherSizeRecord>
                        {
                            new VoucherSizeRecord
                            {
                                Size = new SizeRecord
                                {
                                    Name = "Small"
                                }
                            }
                        }
                    }
                }
            });

            var subject = new VoucherService(_voucherRepository.Object);

            var userBasket = new ShoppingCart.Services.UserSession.Basket
            {
                Items = new List <BasketItem>
                {
                    new BasketItem
                    {
                        Size = new SizeRecord
                        {
                            Name = "Small"
                        },
                        Total = Money.From(1400)
                    },
                    new BasketItem
                    {
                        Size = new SizeRecord
                        {
                            Name = "Small"
                        },
                        Total = Money.From(1500)
                    }
                }
            };
            var deliveryTypes = new List <DeliveryType>
            {
                DeliveryType.Collection
            };

            _result = subject.Verify(userBasket, deliveryTypes, "VOUCHER_CODE");
        }
        public void HyperlinkClicked_CorrelatesSearchSelectionAndAction_Succeeds()
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            _ = telemetrySession
                .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
                .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);

            var service = new NuGetVSTelemetryService(telemetrySession.Object);

            var testPackageId      = "testPackage.id";
            var testPackageVersion = new NuGetVersion(1, 0, 0);

            var evtHyperlink = new HyperlinkClickedTelemetryEvent(
                HyperlinkType.DeprecationAlternativeDetails,
                ContractsItemFilter.All,
                isSolutionView: false,
                testPackageId);

            var evtSearch = new SearchSelectionTelemetryEvent(
                parentId: It.IsAny <Guid>(),
                recommendedCount: It.IsAny <int>(),
                itemIndex: It.IsAny <int>(),
                packageId: testPackageId,
                packageVersion: testPackageVersion,
                isPackageVulnerable: It.IsAny <bool>(),
                isPackageDeprecated: true,
                hasDeprecationAlternativePackage: true);

            var evtActions = new VSActionsTelemetryEvent(
                operationId: It.IsAny <string>(),
                projectIds: new[] { Guid.NewGuid().ToString() },
                operationType: NuGetOperationType.Install,
                source: OperationSource.PMC,
                startTime: DateTimeOffset.Now.AddSeconds(-1),
                status: NuGetOperationStatus.NoOp,
                packageCount: 1,
                endTime: DateTimeOffset.Now,
                duration: .40,
                isPackageSourceMappingEnabled: false);

            // Simulate UIActionEngine.AddUiActionEngineTelemetryProperties()
            var pkgAdded = new TelemetryEvent(eventName: null);

            pkgAdded.AddPiiData("id", VSTelemetryServiceUtility.NormalizePackageId(testPackageId));
            pkgAdded.AddPiiData("version", testPackageVersion.ToNormalizedString());

            var packages = new List <TelemetryEvent>
            {
                pkgAdded
            };

            evtActions.ComplexData["AddedPackages"] = packages;

            // Act
            service.EmitTelemetryEvent(evtHyperlink);
            var hyperlinkEmitted = lastTelemetryEvent;

            service.EmitTelemetryEvent(evtSearch);
            var searchEmitted = lastTelemetryEvent;

            service.EmitTelemetryEvent(evtActions);
            var actionEmitted = lastTelemetryEvent;

            // Assert
            var packageIdHyperlink = hyperlinkEmitted.GetPiiData().First(x => x.Key == HyperlinkClickedTelemetryEvent.AlternativePackageIdPropertyName).Value;
            var packageIdSearch    = searchEmitted.GetPiiData().First(x => x.Key == "PackageId").Value;
            var packageIdsAction   = (IEnumerable <TelemetryEvent>)actionEmitted.ComplexData["AddedPackages"];
            var packageIds         = packageIdsAction.Select(x => x.GetPiiData().First(x => x.Key == "id").Value);

            Assert.Equal(packageIdHyperlink, packageIdSearch);
            Assert.Contains(packageIdHyperlink, packageIds);
        }
Beispiel #36
0
        private IPropStore CreateStore()
        {
            var storeMock = new Mock <IPropStore>();

            return(storeMock.Object);
        }
Beispiel #37
0
        public async Task CreateInstallAction_OnInstallingProject_EmitsPkgWasTransitiveTelemetryAndTabAndIsSolutionPropertiesAsync(ContractsItemFilter activeTab, bool isSolutionLevel, string packageIdToInstall, bool?expectedPkgWasTransitive)
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            telemetrySession
            .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);
            var telemetryService = new NuGetVSTelemetryService(telemetrySession.Object);

            TelemetryActivity.NuGetTelemetryService = telemetryService;

            var sourceProvider = new Mock <ISourceRepositoryProvider>();
            var settings       = new Mock <ISettings>();
            var nugetPM        = new NuGetPackageManager(sourceProvider.Object, settings.Object, @"\packagesFolder");
            var lockService    = new NuGetLockService(ThreadHelper.JoinableTaskContext);
            var uiEngine       = new UIActionEngine(sourceProvider.Object, nugetPM, lockService);

            var installedAndTransitive = new InstalledAndTransitivePackages(
                new[] {
                new PackageReferenceContextInfo(new PackageIdentity("installedA", NuGetVersion.Parse("1.0.0")), NuGetFramework.Parse("net472")),
                new PackageReferenceContextInfo(new PackageIdentity("installedB", NuGetVersion.Parse("1.0.0")), NuGetFramework.Parse("net472"))
            },
                new[] {
                new TransitivePackageReferenceContextInfo(new PackageIdentity("transitiveA", NuGetVersion.Parse("1.0.0")), NuGetFramework.Parse("net472"))
            });
            var prjMgrSvc = new Mock <INuGetProjectManagerService>();

            prjMgrSvc
            .Setup(mgr => mgr.GetInstalledAndTransitivePackagesAsync(It.IsAny <IReadOnlyCollection <string> >(), It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <IInstalledAndTransitivePackages>(installedAndTransitive));
            var dictMetadata = new Dictionary <string, object>
            {
                [NuGetProjectMetadataKeys.UniqueName] = "a",
                [NuGetProjectMetadataKeys.ProjectId]  = "a"
            };
            ProjectMetadataContextInfo metadataCtxtInfo = ProjectMetadataContextInfo.Create(dictMetadata);

            prjMgrSvc
            .Setup(mgr => mgr.GetMetadataAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <IProjectMetadataContextInfo>(metadataCtxtInfo));
            var uiService      = new Mock <INuGetUI>();
            var uiContext      = new Mock <INuGetUIContext>();
            var projectContext = new Mock <INuGetProjectContext>();
            var serviceBroker  = new Mock <IServiceBroker>();

            _ = serviceBroker.Setup(sb => sb.GetProxyAsync <INuGetProjectManagerService>(
                                        It.Is <ServiceRpcDescriptor>(s => s == NuGetServices.ProjectManagerService),
                                        It.IsAny <ServiceActivationOptions>(),
                                        It.IsAny <CancellationToken>()))
                .Returns(new ValueTask <INuGetProjectManagerService>(prjMgrSvc.Object));
            uiContext.Setup(ctx => ctx.ServiceBroker).Returns(serviceBroker.Object);
            uiService.Setup(ui => ui.UIContext).Returns(uiContext.Object);
            uiService.Setup(ui => ui.ProjectContext).Returns(projectContext.Object);
            uiService.Setup(ui => ui.Settings).Returns(settings.Object);
            uiService.Setup(ui => ui.Projects).Returns(new[] { new ProjectContextInfo("a", ProjectModel.ProjectStyle.PackageReference, NuGetProjectKind.PackageReference) });

            var action = UserAction.CreateInstallAction(packageIdToInstall, NuGetVersion.Parse("1.0.0"), isSolutionLevel, activeTab);

            // Act
            await uiEngine.PerformInstallOrUninstallAsync(uiService.Object, action, CancellationToken.None);

            // Assert
            Assert.NotNull(lastTelemetryEvent);
            // expect failed action because we mocked just enough objects to emit telemetry
            Assert.Equal(NuGetOperationStatus.Failed, lastTelemetryEvent[nameof(ActionEventBase.Status)]);
            Assert.Equal(NuGetOperationType.Install, lastTelemetryEvent[nameof(ActionsTelemetryEvent.OperationType)]);
            Assert.Equal(isSolutionLevel, lastTelemetryEvent[nameof(VSActionsTelemetryEvent.IsSolutionLevel)]);
            Assert.Equal(activeTab, lastTelemetryEvent[nameof(VSActionsTelemetryEvent.Tab)]);
            Assert.Equal(expectedPkgWasTransitive, lastTelemetryEvent[nameof(VSActionsTelemetryEvent.PackageToInstallWasTransitive)]);
        }
Beispiel #38
0
        public async Task GetPreviewResultsAsync_WhenPackageIdentityIsSubclass_ItIsReplacedWithNewPackageIdentity()
        {
            string projectId         = Guid.NewGuid().ToString();
            var    packageIdentityA1 = new PackageIdentitySubclass(id: "a", NuGetVersion.Parse("1.0.0"));
            var    packageIdentityA2 = new PackageIdentitySubclass(id: "a", NuGetVersion.Parse("2.0.0"));
            var    packageIdentityB1 = new PackageIdentitySubclass(id: "b", NuGetVersion.Parse("3.0.0"));
            var    packageIdentityB2 = new PackageIdentitySubclass(id: "b", NuGetVersion.Parse("4.0.0"));
            var    uninstallAction   = new ProjectAction(
                id: Guid.NewGuid().ToString(),
                projectId,
                packageIdentityA1,
                NuGetProjectActionType.Uninstall,
                implicitActions: new[]
            {
                new ImplicitProjectAction(
                    id: Guid.NewGuid().ToString(),
                    packageIdentityA1,
                    NuGetProjectActionType.Uninstall),
                new ImplicitProjectAction(
                    id: Guid.NewGuid().ToString(),
                    packageIdentityB1,
                    NuGetProjectActionType.Uninstall)
            });
            var installAction = new ProjectAction(
                id: Guid.NewGuid().ToString(),
                projectId,
                packageIdentityA2,
                NuGetProjectActionType.Install,
                implicitActions: new[]
            {
                new ImplicitProjectAction(
                    id: Guid.NewGuid().ToString(),
                    packageIdentityA2,
                    NuGetProjectActionType.Install),
                new ImplicitProjectAction(
                    id: Guid.NewGuid().ToString(),
                    packageIdentityB2,
                    NuGetProjectActionType.Install)
            });
            IReadOnlyList <PreviewResult> previewResults = await UIActionEngine.GetPreviewResultsAsync(
                Mock.Of <INuGetProjectManagerService>(),
                new[] { uninstallAction, installAction },
                CancellationToken.None);

            Assert.Equal(1, previewResults.Count);
            UpdatePreviewResult[] updatedResults = previewResults[0].Updated.ToArray();

            Assert.Equal(2, updatedResults.Length);

            UpdatePreviewResult updatedResult = updatedResults[0];

            Assert.False(updatedResult.Old.GetType().IsSubclassOf(typeof(PackageIdentity)));
            Assert.False(updatedResult.New.GetType().IsSubclassOf(typeof(PackageIdentity)));
            Assert.Equal("a.1.0.0 -> a.2.0.0", updatedResult.ToString());

            updatedResult = updatedResults[1];

            Assert.False(updatedResult.Old.GetType().IsSubclassOf(typeof(PackageIdentity)));
            Assert.False(updatedResult.New.GetType().IsSubclassOf(typeof(PackageIdentity)));
            Assert.Equal("b.3.0.0 -> b.4.0.0", updatedResult.ToString());
        }
        public void RequestProxied_MultipleConcurrentRequests_MarkDestinationUnhealthyAndHealthyAgain()
        {
            var options = Options.Create(
                new TransportFailureRateHealthPolicyOptions {
                DefaultFailureRateLimit = 0.5, DetectionWindowSize = TimeSpan.FromSeconds(30), MinimalTotalCountThreshold = 1
            });
            var clock = new ClockStub {
                TickCount = 10000
            };
            var healthUpdater      = new Mock <IDestinationHealthUpdater>();
            var reactivationPeriod = TimeSpan.FromSeconds(15);
            var policy             = new TransportFailureRateHealthPolicy(options, clock, healthUpdater.Object);

            var cluster = GetClusterInfo("cluster0", destinationCount: 2, reactivationPeriod: reactivationPeriod);

            // Initial state
            Assert.All(cluster.DestinationManager.Items, d => Assert.Equal(DestinationHealth.Unknown, d.Health.Passive));

            // Initial sucessful requests
            for (var i = 0; i < 2; i++)
            {
                policy.RequestProxied(cluster, cluster.DestinationManager.Items[1], new DefaultHttpContext());
            }

            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod), Times.Exactly(2));
            healthUpdater.VerifyNoOtherCalls();

            // Concurrent failed requests.
            // They are 'concurrent' because the clock is not updated.
            for (var i = 0; i < 2; i++)
            {
                policy.RequestProxied(cluster, cluster.DestinationManager.Items[1], GetFailedRequestContext(ProxyError.RequestTimedOut));
            }

            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod), Times.Exactly(3));
            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Unhealthy, reactivationPeriod), Times.Once);
            healthUpdater.VerifyNoOtherCalls();

            // More successful requests
            for (var i = 0; i < 2; i++)
            {
                policy.RequestProxied(cluster, cluster.DestinationManager.Items[1], new DefaultHttpContext());
                clock.TickCount += 100;
            }

            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod), Times.Exactly(5));
            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Unhealthy, reactivationPeriod), Times.Once);
            healthUpdater.VerifyNoOtherCalls();

            // More failed requests
            for (var i = 0; i < 2; i++)
            {
                policy.RequestProxied(cluster, cluster.DestinationManager.Items[1], GetFailedRequestContext(ProxyError.RequestTimedOut));
                clock.TickCount += 100;
            }

            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod), Times.Exactly(6));
            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[1], DestinationHealth.Unhealthy, reactivationPeriod), Times.Exactly(2));
            healthUpdater.VerifyNoOtherCalls();

            policy.RequestProxied(cluster, cluster.DestinationManager.Items[0], new DefaultHttpContext());

            healthUpdater.Verify(u => u.SetPassive(cluster, cluster.DestinationManager.Items[0], DestinationHealth.Healthy, reactivationPeriod), Times.Once);
            healthUpdater.VerifyNoOtherCalls();
        }
        public void RequestProxied_FailureRateLimitExceeded_MarkDestinationUnhealthy()
        {
            var options = Options.Create(
                new TransportFailureRateHealthPolicyOptions {
                DefaultFailureRateLimit = 0.5, DetectionWindowSize = TimeSpan.FromSeconds(30), MinimalTotalCountThreshold = 1
            });
            var clock = new ClockStub {
                TickCount = 10000
            };
            var healthUpdater = new Mock <IDestinationHealthUpdater>();
            var policy        = new TransportFailureRateHealthPolicy(options, clock, healthUpdater.Object);

            Assert.Equal(HealthCheckConstants.PassivePolicy.TransportFailureRate, policy.Name);

            var reactivationPeriod0 = TimeSpan.FromSeconds(60);
            var reactivationPeriod1 = TimeSpan.FromSeconds(100);
            var cluster0            = GetClusterInfo("cluster0", destinationCount: 2);
            var cluster1            = GetClusterInfo("cluster1", destinationCount: 2, failureRateLimit: 0.61, reactivationPeriod1);

            // Initial state
            Assert.All(cluster0.DestinationManager.Items, d => Assert.Equal(DestinationHealth.Unknown, d.Health.Passive));
            Assert.All(cluster1.DestinationManager.Items, d => Assert.Equal(DestinationHealth.Unknown, d.Health.Passive));

            // Successful requests
            for (var i = 0; i < 3; i++)
            {
                policy.RequestProxied(cluster0, cluster0.DestinationManager.Items[0], new DefaultHttpContext());
                policy.RequestProxied(cluster0, cluster0.DestinationManager.Items[1], new DefaultHttpContext());
                policy.RequestProxied(cluster1, cluster1.DestinationManager.Items[0], new DefaultHttpContext());
                policy.RequestProxied(cluster1, cluster1.DestinationManager.Items[1], new DefaultHttpContext());
                clock.TickCount += 4000;
            }

            healthUpdater.Verify(u => u.SetPassive(cluster0, cluster0.DestinationManager.Items[0], DestinationHealth.Healthy, reactivationPeriod0), Times.Exactly(3));
            healthUpdater.Verify(u => u.SetPassive(cluster0, cluster0.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod0), Times.Exactly(3));
            healthUpdater.Verify(u => u.SetPassive(cluster1, cluster1.DestinationManager.Items[0], DestinationHealth.Healthy, reactivationPeriod1), Times.Exactly(3));
            healthUpdater.Verify(u => u.SetPassive(cluster1, cluster1.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod1), Times.Exactly(3));
            healthUpdater.VerifyNoOtherCalls();

            // Failed requests
            for (var i = 0; i < 3; i++)
            {
                policy.RequestProxied(cluster0, cluster0.DestinationManager.Items[1], GetFailedRequestContext(ProxyError.RequestTimedOut));
                policy.RequestProxied(cluster1, cluster1.DestinationManager.Items[0], GetFailedRequestContext(ProxyError.Request));
                clock.TickCount += 4000;
            }

            healthUpdater.Verify(u => u.SetPassive(cluster0, cluster0.DestinationManager.Items[1], DestinationHealth.Healthy, reactivationPeriod0), Times.Exactly(5));
            healthUpdater.Verify(u => u.SetPassive(cluster0, cluster0.DestinationManager.Items[1], DestinationHealth.Unhealthy, reactivationPeriod0), Times.Once);
            healthUpdater.Verify(u => u.SetPassive(cluster1, cluster1.DestinationManager.Items[0], DestinationHealth.Healthy, reactivationPeriod1), Times.Exactly(6));
            healthUpdater.VerifyNoOtherCalls();

            // Two more failed requests
            policy.RequestProxied(cluster1, cluster1.DestinationManager.Items[0], GetFailedRequestContext(ProxyError.Request));
            // End of the detection window
            clock.TickCount += 6000;
            policy.RequestProxied(cluster1, cluster1.DestinationManager.Items[0], GetFailedRequestContext(ProxyError.Request));

            healthUpdater.Verify(u => u.SetPassive(cluster1, cluster1.DestinationManager.Items[0], DestinationHealth.Healthy, reactivationPeriod1), Times.Exactly(7));
            healthUpdater.Verify(u => u.SetPassive(cluster1, cluster1.DestinationManager.Items[0], DestinationHealth.Unhealthy, reactivationPeriod1), Times.Once);
            healthUpdater.VerifyNoOtherCalls();
        }
 public FlurlChannelClientTests()
 {
     _httpTest             = new HttpTest();
     _responseVerifierMock = new Mock <IResponseVerifier>();
     _channelClient        = new FlurlChannelClient(_responseVerifierMock.Object);
 }
 public void SetUp()
 {
     _directoryReader = new Mock<IDirectoryExplorer>();   
 }
Beispiel #43
0
 protected override void SetupMock(IMockProducer mockProducer, Mock <ILayoutDependenciesFactory> mock)
 {
     mock.Setup(m => m.DataConsumerFactory).Returns(mockProducer.SetupMock <IDataConsumerFactory>);
     mock.Setup(m => m.DictionaryFactory).Returns(mockProducer.SetupMock <IDictionaryFactory>);
 }
Beispiel #44
0
 public void Setup()
 {
     _resourceProcessorMock = new Mock <IResourceProcessor>();
     _resourceProcessorMock.Setup(m => m.AddResourceBatchToQueue(It.IsAny <IEnumerable <string> >())).Returns((1, QueuingStatus.QUEUED));
     _controller = new ProcessController(_resourceProcessorMock.Object);
 }
Beispiel #45
0
        public void AddUiActionEngineTelemetryProperties_AddsVulnerabilityInfo_Succeeds()
        {
            // Arrange
            var            telemetrySession   = new Mock <ITelemetrySession>();
            TelemetryEvent lastTelemetryEvent = null;

            telemetrySession
            .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(x => lastTelemetryEvent = x);

            var operationId = Guid.NewGuid().ToString();

            var actionTelemetryData = new VSActionsTelemetryEvent(
                operationId,
                projectIds: new[] { Guid.NewGuid().ToString() },
                operationType: NuGetOperationType.Install,
                source: OperationSource.PMC,
                startTime: DateTimeOffset.Now.AddSeconds(-1),
                status: NuGetOperationStatus.NoOp,
                packageCount: 1,
                endTime: DateTimeOffset.Now,
                duration: .40,
                isPackageSourceMappingEnabled: false);

            UIActionEngine.AddUiActionEngineTelemetryProperties(
                actionTelemetryEvent: actionTelemetryData,
                continueAfterPreview: true,
                acceptedLicense: true,
                userAction: UserAction.CreateInstallAction("mypackageId", new NuGetVersion(1, 0, 0), It.IsAny <bool>(), It.IsAny <ContractsItemFilter>()),
                selectedIndex: 0,
                recommendedCount: 0,
                recommendPackages: false,
                recommenderVersion: null,
                topLevelVulnerablePackagesCount: 3,
                topLevelVulnerablePackagesMaxSeverities: new List <int> {
                1, 1, 3
            },                                                                      // each package has its own max severity
                existingPackages: null,
                addedPackages: null,
                removedPackages: null,
                updatedPackagesOld: null,
                updatedPackagesNew: null,
                targetFrameworks: null);

            // Act
            var service = new NuGetVSTelemetryService(telemetrySession.Object);

            service.EmitTelemetryEvent(actionTelemetryData);

            // Assert
            Assert.NotNull(lastTelemetryEvent);
            Assert.NotNull(lastTelemetryEvent.ComplexData["TopLevelVulnerablePackagesMaxSeverities"] as List <int>);
            var pkgSeverities = lastTelemetryEvent.ComplexData["TopLevelVulnerablePackagesMaxSeverities"] as List <int>;

            Assert.Equal(lastTelemetryEvent["TopLevelVulnerablePackagesCount"], pkgSeverities.Count());
            Assert.Collection(pkgSeverities,
                              item => Assert.Equal(1, item),
                              item => Assert.Equal(1, item),
                              item => Assert.Equal(3, item));
            Assert.Equal(3, pkgSeverities.Count());
        }
 private static Filter CreateFilter(Mock instanceMock)
 {
     return new Filter(instanceMock.Object, FilterScope.Global, null);
 }
        public void Setup()
        {
            custDatDAl = new Mock <ICustomerDataDAL>(MockBehavior.Strict);

            manager = new AuthManager(custDatDAl.Object);
        }
Beispiel #48
0
        public void Setup()
        {
            var createPageCommand = new CreatePage
            {
                SiteId = Guid.NewGuid(),
                Id     = Guid.NewGuid(),
                Name   = "Name",
                Url    = "url"
            };

            var createPageValidatorMock = new Mock <IValidator <CreatePage> >();

            createPageValidatorMock.Setup(x => x.Validate(createPageCommand)).Returns(new ValidationResult());

            _page = Page.CreateNew(createPageCommand, createPageValidatorMock.Object);

            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Header", 1));
            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Header", 2));
            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Content", 1));
            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Content", 2));
            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Footer", 1));
            _page.AddModule(new PageModule(_page.Id, Guid.NewGuid(), Guid.NewGuid(), "Title", "Footer", 2));

            _command = new ReorderPageModules
            {
                SiteId = _page.SiteId,
                PageId = _page.Id,
                Zones  = new List <ReorderPageModules.Zone>
                {
                    new ReorderPageModules.Zone
                    {
                        Name    = "Header",
                        Modules = new List <Guid>
                        {
                            _page.PageModules.FirstOrDefault().ModuleId
                        }
                    },
                    new ReorderPageModules.Zone
                    {
                        Name    = "Content",
                        Modules = new List <Guid>
                        {
                            _page.PageModules.Skip(2).FirstOrDefault().ModuleId,
                            _page.PageModules.Skip(3).FirstOrDefault().ModuleId,
                            _page.PageModules.Skip(1).FirstOrDefault().ModuleId
                        }
                    },
                    new ReorderPageModules.Zone
                    {
                        Name    = "Footer",
                        Modules = new List <Guid>
                        {
                            _page.PageModules.Skip(4).FirstOrDefault().ModuleId,
                            _page.PageModules.Skip(5).FirstOrDefault().ModuleId
                        }
                    }
                }
            };

            var validatorMock = new Mock <IValidator <ReorderPageModules> >();

            validatorMock.Setup(x => x.Validate(_command)).Returns(new ValidationResult());

            _page.ReorderPageModules(_command, validatorMock.Object);

            _event = _page.Events.OfType <PageModulesReordered>().SingleOrDefault();
        }
 public MockBasePackageStore(IOptionsMonitor<PackageStoreOptions> optionsAccessor, IFileSystem fileSystem, ISymbolicLink symbolicLink, IZipUtil zipUtil, Mock<IPackageStore> mock) : base(optionsAccessor, fileSystem, symbolicLink, zipUtil) {
     _mock = mock;
 }
 public static void ClassInitialize(TestContext a)
 {
     _mockClient = new Mock<AmazonShieldClient>("access key", "secret", Amazon.RegionEndpoint.USEast1);
 }
        public void WhenGettingNonExistingServiceWithRegistration_ThenThrowsInvalidOperationException()
        {
            var sp = new Mock <IServiceProvider>();

            Assert.Throws <InvalidOperationException> (() => sp.Object.GetService <IFooReg, IFoo> ());
        }
        public async Task StatisticsHomePage_ValidateFullReportStructureAndAvailability()
        {
            JArray report1 = new JArray
            {
                new JObject
                {
                    { "PackageId", "A" },
                    { "Downloads", 1 },
                },
                new JObject
                {
                    { "PackageId", "B" },
                    { "Downloads", 2 },
                }
            };

            JArray report2 = new JArray
            {
                new JObject
                {
                    { "PackageId", "A" },
                    { "PackageVersion", "1.0" },
                    { "Downloads", 3 },
                },
                new JObject
                {
                    { "PackageId", "A" },
                    { "PackageVersion", "1.1" },
                    { "Downloads", 4 },
                },
                new JObject
                {
                    { "PackageId", "B" },
                    { "PackageVersion", "1.0" },
                    { "Downloads", 5 },
                }
            };

            JArray report3 = new JArray
            {
                new JObject
                {
                    { "ClientMajorVersion", 0 },
                    { "ClientMinorVersion", 0 },
                    { "Downloads", 1349 }
                },
                new JObject
                {
                    { "ClientMajorVersion", 1 },
                    { "ClientMinorVersion", 0 },
                    { "Downloads", 1349 }
                }
            };

            JArray report4 = new JArray
            {
                new JObject
                {
                    { "Year", 2012 },
                    { "WeekOfYear", 11 },
                    { "Downloads", 5383767 }
                },
                new JObject
                {
                    { "Year", 2012 },
                    { "WeekOfYear", 12 },
                    { "Downloads", 5383767 }
                }
            };

            var fakePackageReport        = report1.ToString();
            var fakePackageVersionReport = report2.ToString();
            var fakeNuGetClientVersion   = report3.ToString();
            var fakeLast6Weeks           = report4.ToString();

            var fakeReportService = new Mock <IReportService>();

            fakeReportService.Setup(x => x.Load("recentpopularity.json")).Returns(Task.FromResult(new StatisticsReport(fakePackageReport, DateTime.UtcNow)));
            fakeReportService.Setup(x => x.Load("recentpopularitydetail.json")).Returns(Task.FromResult(new StatisticsReport(fakePackageVersionReport, DateTime.UtcNow)));
            fakeReportService.Setup(x => x.Load("nugetclientversion.json")).Returns(Task.FromResult(new StatisticsReport(fakeNuGetClientVersion, DateTime.UtcNow)));
            fakeReportService.Setup(x => x.Load("last6weeks.json")).Returns(Task.FromResult(new StatisticsReport(fakeLast6Weeks, DateTime.UtcNow)));

            var controller = new StatisticsController(new JsonStatisticsService(fakeReportService.Object));

            var model = (StatisticsPackagesViewModel)((ViewResult)await controller.Index()).Model;

            if (model.IsDownloadPackageAvailable)
            {
                foreach (var item in model.DownloadPackagesSummary)
                {
                    if (item.PackageId == "A" && item.Downloads == 1)
                    {
                        continue;
                    }
                    else if (item.PackageId == "B" && item.Downloads == 2)
                    {
                        continue;
                    }
                    throw new Exception("unexpected data in Package report");
                }
            }

            if (model.IsDownloadPackageVersionsAvailable)
            {
                foreach (var item in model.DownloadPackageVersionsSummary)
                {
                    if (item.PackageId == "A" && item.PackageVersion == "1.0" & item.Downloads == 3)
                    {
                        continue;
                    }
                    if (item.PackageId == "A" && item.PackageVersion == "1.1" & item.Downloads == 4)
                    {
                        continue;
                    }
                    if (item.PackageId == "B" && item.PackageVersion == "1.0" & item.Downloads == 5)
                    {
                        continue;
                    }
                    throw new Exception("unexpected data in Package report");
                }
            }
        }
 public void Setup()
 {
     userSigs = new SortedList<Address, Procedure_v1>();
     this.dynamicLinker = new Mock<IDynamicLinker>();
 }
		public void Initialize()
		{
			logger = new Mock<ILogger>();
			sut = new PasswordEncryption(logger.Object);
		}
Beispiel #55
0
 public void UseSwaggerThrowsForNullApiVersionDescriptionProvider()
 {
     // Arrange
     var swaggerOptions = Mock.Of<IOptions<SwaggerOptions>>();
     var app = Mock.Of<IApplicationBuilder>();
     object TestCode() => app.UseSwagger(default, swaggerOptions);