Beispiel #1
0
 public void AddFromStringTestNullstring()
 {
     Assert.Throws <ArgumentNullException>(() => { _service.AddFromString(null); });
     _repoMock.Verify(x => x.AddRecord(It.IsAny <Person>()), Times.Never);
 }
Beispiel #2
0
		public async Task FindAndCacheDevicesWithFailingMlaunchTest ()
		{
			string processPath = null;
			MlaunchArguments passedArguments = null;

			// Moq.SetupSequence doesn't allow custom callbacks so we need to count ourselves
			var calls = 0;

			// moq It.Is is not working as nicelly as we would like it, we capture data and use asserts
			processManager.Setup (p => p.RunAsync (It.IsAny<Process> (), It.IsAny<MlaunchArguments> (), It.IsAny<ILog> (), It.IsAny<TimeSpan?> (), It.IsAny<Dictionary<string, string>> (), It.IsAny<CancellationToken?> (), It.IsAny<bool?> ()))
				.Returns<Process, MlaunchArguments, ILog, TimeSpan?, Dictionary<string, string>, CancellationToken?, bool?> ((p, args, log, t, env, token, d) => {
					calls++;

					if (calls == 1) {
						// Mlaunch can sometimes time out and we are testing that a subsequent Load will trigger it again
						return Task.FromResult (new ProcessExecutionResult { ExitCode = 137, TimedOut = true });
					}

					processPath = p.StartInfo.FileName;
					passedArguments = args;

					// we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)
					var tempPath = args.Where (a => a is ListDevicesArgument).First ().AsCommandLineArgument ();
					tempPath = tempPath.Substring (tempPath.IndexOf ('=') + 1).Replace ("\"", string.Empty);

					var name = GetType ().Assembly.GetManifestResourceNames ().Where (a => a.EndsWith ("devices.xml", StringComparison.Ordinal)).FirstOrDefault ();
					using (var outputStream = new StreamWriter (tempPath))
					using (var sampleStream = new StreamReader (GetType ().Assembly.GetManifestResourceStream (name))) {
						string line;
						while ((line = sampleStream.ReadLine ()) != null)
							outputStream.WriteLine (line);
					}
					return Task.FromResult (new ProcessExecutionResult { ExitCode = 0, TimedOut = false });
				});

			Assert.ThrowsAsync<Exception> (async () => await devices.LoadDevices (executionLog.Object));

			Assert.IsEmpty (devices.ConnectedDevices);
			Assert.AreEqual (1, calls);
			await devices.LoadDevices (executionLog.Object);
			Assert.AreEqual (2, calls);
			Assert.IsNotEmpty (devices.ConnectedDevices);
			await devices.LoadDevices (executionLog.Object);
			Assert.AreEqual (2, calls);
			await devices.LoadDevices (executionLog.Object);
			Assert.AreEqual (2, calls);
		}
Beispiel #3
0
		public async Task LoadAsyncProcessSuccess (bool extraData)
		{
			string processPath = null;
			MlaunchArguments passedArguments = null;

			// moq It.Is is not working as nicelly as we would like it, we capture data and use asserts
			processManager.Setup (p => p.RunAsync (It.IsAny<Process> (), It.IsAny<MlaunchArguments> (), It.IsAny<ILog> (), It.IsAny<TimeSpan?> (), It.IsAny<Dictionary<string, string>> (), It.IsAny<CancellationToken?> (), It.IsAny<bool?> ()))
				.Returns<Process, MlaunchArguments, ILog, TimeSpan?, Dictionary<string, string>, CancellationToken?, bool?> ((p, args, log, t, env, token, d) => {
					processPath = p.StartInfo.FileName;
					passedArguments = args;

					// we get the temp file that was passed as the args, and write our sample xml, which will be parsed to get the devices :)
					var tempPath = args.Where (a => a is ListDevicesArgument).First ().AsCommandLineArgument ();
					tempPath = tempPath.Substring (tempPath.IndexOf('=') + 1).Replace ("\"", string.Empty);

					var name = GetType ().Assembly.GetManifestResourceNames ().Where (a => a.EndsWith ("devices.xml", StringComparison.Ordinal)).FirstOrDefault ();
					using (var outputStream = new StreamWriter (tempPath))
					using (var sampleStream = new StreamReader (GetType ().Assembly.GetManifestResourceStream (name))) {
						string line;
						while ((line = sampleStream.ReadLine ()) != null)
							outputStream.WriteLine (line);
					}
					return Task.FromResult (new ProcessExecutionResult { ExitCode = 0, TimedOut = false });
				});

			await devices.LoadDevices (executionLog.Object, listExtraData: extraData);

			// assert the devices that are expected from the sample xml
			MlaunchArgument listDevArg = passedArguments.Where (a => a is ListDevicesArgument).FirstOrDefault ();
			Assert.IsNotNull (listDevArg, "list devices arg missing");

			MlaunchArgument outputFormatArg = passedArguments.Where (a => a is XmlOutputFormatArgument).FirstOrDefault ();
			Assert.IsNotNull (outputFormatArg, "output format arg missing");

			if (extraData) {
				MlaunchArgument listExtraDataArg = passedArguments.Where (a => a is ListExtraDataArgument).FirstOrDefault ();
				Assert.IsNotNull (listExtraDataArg, "list extra data arg missing");
			}

			Assert.AreEqual (2, devices.Connected64BitIOS.Count ());
			Assert.AreEqual (1, devices.Connected32BitIOS.Count ());
			Assert.AreEqual (0, devices.ConnectedTV.Count ());
		}
		public void Ingredient_WhenUpdated_ShouldPublishIngredientUpdatedEvent()
		{
			_systemUnderTest.Update(
				IngredientName, Allergen.Wheat, Requirement.None, _systemUnderTest.MacroNutrientsSharesCollection);
			_eventPublisherMock.Verify(x => x.Publish(It.IsAny<IngredientUpdatedEventMessage>()), Times.Once);
		}
Beispiel #5
0
        private Mock <IIPYarnTypeService> GetGlobalDefaulExceptionMock()
        {
            var serviceMock = new Mock <IIPYarnTypeService>();

            serviceMock.Setup(s => s.ReadAll())
            .Throws(new Exception());
            serviceMock.Setup(s => s.ReadById(It.IsAny <int>()))
            .Throws(new Exception());
            serviceMock.Setup(s => s.ReadByPage(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .Throws(new Exception());
            serviceMock.Setup(s => s.Create(It.IsAny <IPYarnTypeViewModel>()))
            .Throws(new Exception());
            serviceMock.Setup(s => s.Update(It.IsAny <int>(), It.IsAny <IPYarnTypeViewModel>()))
            .Throws(new Exception());
            serviceMock.Setup(s => s.Delete(It.IsAny <int>()))
            .Throws(new Exception());
            return(serviceMock);
        }
        public async Task CanEnsureConfigureForDeploymentPool()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                trace.Info("Preparing command line arguments");
                var command = new CommandSettings(
                    tc,
                    new[]
                {
                    "configure",
#if !OS_WINDOWS
                    "--acceptteeeula",
#endif
                    "--url", _expectedServerUrl,
                    "--agent", _expectedAgentName,
                    "--deploymentpoolname", _expectedPoolName,
                    "--work", _expectedWorkFolder,
                    "--auth", _expectedAuthType,
                    "--token", _expectedToken,
                    "--deploymentpool"
                });
                trace.Info("Constructed.");
                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                _extnMgr.Setup(x => x.GetExtensions <IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                await configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);

                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.NotNull(s);
                Assert.True(s.ServerUrl.Equals(_expectedServerUrl));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolId.Equals(_expectedPoolId));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));

                // validate GetAgentPoolsAsync gets called once with deployment pool type
                _agentServer.Verify(x => x.GetAgentPoolsAsync(It.IsAny <string>(), It.Is <TaskAgentPoolType>(p => p == TaskAgentPoolType.Deployment)), Times.Once);

                // validate GetAgentPoolsAsync not called with Automation pool type
                _agentServer.Verify(x => x.GetAgentPoolsAsync(It.IsAny <string>(), It.Is <TaskAgentPoolType>(p => p == TaskAgentPoolType.Automation)), Times.Never);

                // For build and release agent / deployment pool, tags logic should not get trigger;
                _machineGroupServer.Verify(x =>
                                           x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <List <DeploymentMachine> >()), Times.Never);
            }
        }
        public async Task CanEnsureMachineGroupAgentConfigureVSTSScenarioWithTags()
        {
            Guid   receivedProjectId     = Guid.Empty;
            string expectedProcessedTags = string.Empty;
            string tags                      = "Tag3, ,, Tag4  , , ,  Tag1,  , tag3 ";
            string expectedTags              = "Tag3,Tag4,Tag1";
            int    receivedMachineId         = -1;
            int    expectedDeploymentGroupId = 7;
            int    receivedDeploymentGroupId = -1;

            _machineGroupServer.Setup(x =>
                                      x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(),
                                                                     It.IsAny <List <DeploymentMachine> >())).Callback((Guid project, int deploymentGroupId, List <DeploymentMachine> deploymentMachine) =>
            {
                receivedProjectId         = project;
                expectedProcessedTags     = string.Join(",", deploymentMachine.FirstOrDefault().Tags.ToArray());
                receivedMachineId         = deploymentMachine.FirstOrDefault().Id;
                receivedDeploymentGroupId = deploymentGroupId;
            }
                                                                                                                       );

            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                trace.Info("Preparing command line arguments for vsts scenario");
                var command = new CommandSettings(
                    tc,
                    new[]
                {
                    "configure",
#if !OS_WINDOWS
                    "--acceptteeeula",
#endif
                    "--machinegroup",
                    "--adddeploymentgrouptags",
                    "--url", _expectedVSTSServerUrl,
                    "--agent", _expectedAgentName,
                    "--projectname", _expectedProjectName,
                    "--deploymentgroupname", _expectedMachineGroupName,
                    "--work", _expectedWorkFolder,
                    "--auth", _expectedAuthType,
                    "--token", _expectedToken,
                    "--deploymentgrouptags", tags
                });
                trace.Info("Constructed.");

                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                _extnMgr.Setup(x => x.GetExtensions <IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));


                _machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(GetDeploymentGroups(expectedDeploymentGroupId, 3)));

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                await configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);

                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.NotNull(s);
                Assert.True(s.ServerUrl.Equals(_expectedVSTSServerUrl, StringComparison.CurrentCultureIgnoreCase));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolId.Equals(3));
                Assert.True(s.DeploymentGroupId.Equals(7));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
                Assert.True(s.MachineGroupId.Equals(0));
                Assert.Null(s.ProjectName);
                Assert.True(s.ProjectId.Equals(_expectedProjectId));

                Assert.True(receivedProjectId.Equals(new Guid(_expectedProjectId)), "UpdateDeploymentMachinesGroupAsync should get call with correct project name");
                Assert.True(expectedTags.Equals(expectedProcessedTags), "Before applying the tags, should get processed ( Trim, Remove duplicate)");
                Assert.True(receivedMachineId.Equals(_expectedDeploymentMachineId), "UpdateDeploymentMachinesGroupAsync should get call with correct machine id");
                Assert.True(receivedDeploymentGroupId.Equals(expectedDeploymentGroupId), "UpdateDeploymentMachinesGroupAsync should get call with correct deployment group id");
                // Tags logic should get trigger
                _machineGroupServer.Verify(x =>
                                           x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(),
                                                                          It.IsAny <List <DeploymentMachine> >()), Times.Once);
            }
        }
		public void Repeat_MustPerformForClientConfigurationWithCorrectUri()
		{
			var currentSettings = new Settings();
			var location = Path.GetDirectoryName(GetType().Assembly.Location);
			var resource = new Uri(Path.Combine(location, nameof(Operations), FILE_NAME));
			var settings = new Settings { ConfigurationMode = ConfigurationMode.ConfigureClient };

			currentSession.SetupGet(s => s.Settings).Returns(currentSettings);
			sessionContext.ReconfigurationFilePath = resource.LocalPath;
			repository.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			repository.Setup(r => r.ConfigureClientWith(It.Is<Uri>(u => u.Equals(resource)), It.IsAny<PasswordParameters>())).Returns(SaveStatus.Success);

			var sut = new ConfigurationOperation(null, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			var result = sut.Repeat();

			nextSession.VerifySet(s => s.Settings = settings, Times.Once);
			repository.Verify(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>()), Times.AtLeastOnce);
			repository.Verify(r => r.ConfigureClientWith(It.Is<Uri>(u => u.Equals(resource)), It.IsAny<PasswordParameters>()), Times.Once);

			Assert.AreEqual(OperationResult.Success, result);
		}
		public void Repeat_MustFailWithInvalidUri()
		{
			var resource = new Uri("file:///C:/does/not/exist.txt");
			var settings = default(Settings);

			sessionContext.ReconfigurationFilePath = null;
			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);

			var sut = new ConfigurationOperation(null, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			var result = sut.Repeat();

			repository.Verify(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>()), Times.Never);
			Assert.AreEqual(OperationResult.Failed, result);

			sessionContext.ReconfigurationFilePath = resource.LocalPath;
			result = sut.Repeat();

			repository.Verify(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>()), Times.Never);
			Assert.AreEqual(OperationResult.Failed, result);
		}
		public void Perform_MustUseCurrentPasswordIfAvailable()
		{
			var url = @"http://www.safeexambrowser.org/whatever.seb";
			var location = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);
			var settings = new Settings { AdminPasswordHash = "1234", ConfigurationMode = ConfigurationMode.Exam };

			appConfig.AppDataFilePath = location;

			repository
				.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.IsAny<PasswordParameters>()))
				.Returns(LoadStatus.PasswordNeeded);
			repository
				.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(new Uri(location))), out settings, It.IsAny<PasswordParameters>()))
				.Returns(LoadStatus.Success);
			repository
				.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.Is<PasswordParameters>(p => p.IsHash == true && p.Password == settings.AdminPasswordHash)))
				.Returns(LoadStatus.Success);

			var sut = new ConfigurationOperation(new[] { "blubb.exe", url }, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			var result = sut.Perform();

			repository.Verify(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.Is<PasswordParameters>(p => p.Password == settings.AdminPasswordHash)), Times.AtLeastOnce);

			Assert.AreEqual(OperationResult.Success, result);
		}
		public void Perform_MustAbortAskingForAdminPasswordIfDecidedByUser()
		{
			var password = "******";
			var currentSettings = new Settings { AdminPasswordHash = "1234", ConfigurationMode = ConfigurationMode.ConfigureClient };
			var nextSettings = new Settings { AdminPasswordHash = "9876", ConfigurationMode = ConfigurationMode.ConfigureClient };
			var url = @"http://www.safeexambrowser.org/whatever.seb";

			appConfig.AppDataFilePath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);
			nextSession.SetupGet(s => s.Settings).Returns(nextSettings);

			hashAlgorithm.Setup(h => h.GenerateHashFor(It.Is<string>(p => p == password))).Returns(currentSettings.AdminPasswordHash);
			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out currentSettings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			repository.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.AbsoluteUri == url), out nextSettings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);

			var sut = new ConfigurationOperation(new[] { "blubb.exe", url }, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			sut.ActionRequired += args =>
			{
				if (args is PasswordRequiredEventArgs p && p.Purpose == PasswordRequestPurpose.LocalAdministrator)
				{
					p.Success = false;
				}
			};

			var result = sut.Perform();

			repository.Verify(r => r.ConfigureClientWith(It.IsAny<Uri>(), It.IsAny<PasswordParameters>()), Times.Never);

			Assert.AreEqual(OperationResult.Aborted, result);
		}
		public void Perform_MustNotAuthenticateIfSameAdminPassword()
		{
			var currentSettings = new Settings { AdminPasswordHash = "1234", ConfigurationMode = ConfigurationMode.ConfigureClient };
			var nextSettings = new Settings { AdminPasswordHash = "1234", ConfigurationMode = ConfigurationMode.ConfigureClient };
			var url = @"http://www.safeexambrowser.org/whatever.seb";

			appConfig.AppDataFilePath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);
			nextSession.SetupGet(s => s.Settings).Returns(nextSettings);

			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out currentSettings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			repository.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.AbsoluteUri == url), out nextSettings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			repository.Setup(r => r.ConfigureClientWith(It.IsAny<Uri>(), It.IsAny<PasswordParameters>())).Returns(SaveStatus.Success);

			var sut = new ConfigurationOperation(new[] { "blubb.exe", url }, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			sut.ActionRequired += args =>
			{
				if (args is PasswordRequiredEventArgs)
				{
					Assert.Fail();
				}
			};

			var result = sut.Perform();

			hashAlgorithm.Verify(h => h.GenerateHashFor(It.IsAny<string>()), Times.Never);

			Assert.AreEqual(OperationResult.Success, result);
		}
		public void Perform_MustOnlyAllowToEnterAdminPasswordFiveTimes()
		{
			var count = 0;
			var localSettings = new Settings { AdminPasswordHash = "1234" };
			var settings = new Settings { AdminPasswordHash = "9876", ConfigurationMode = ConfigurationMode.ConfigureClient };
			var url = @"http://www.safeexambrowser.org/whatever.seb";

			appConfig.AppDataFilePath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);

			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			repository.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.LocalPath.Contains(FILE_NAME)), out localSettings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);
			nextSession.SetupGet(s => s.Settings).Returns(settings);

			var sut = new ConfigurationOperation(new[] { "blubb.exe", url }, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			sut.ActionRequired += args =>
			{
				if (args is PasswordRequiredEventArgs p && p.Purpose == PasswordRequestPurpose.LocalAdministrator)
				{
					count++;
					p.Success = true;
				}
			};

			var result = sut.Perform();

			Assert.AreEqual(5, count);
			Assert.AreEqual(OperationResult.Failed, result);
		}
Beispiel #14
0
#pragma warning disable IDE0060 // Remove unused parameter
        public static void Setup(TestContext context)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            var sendCommandResponse = new SendCommandResponse
            {
                StartSession = new StartSessionResult
                {
                    SessionToken = "testToken"
                },
                StartTransaction = new StartTransactionResult
                {
                    TransactionId = "testTransactionIdddddd"
                },
                ExecuteStatement = new ExecuteStatementResult
                {
                    FirstPage = new Page
                    {
                        NextPageToken = null,
                        Values        = new List <ValueHolder>()
                    }
                },
                CommitTransaction = new CommitTransactionResult
                {
                    CommitDigest = new MemoryStream(digest)
                },
                ResponseMetadata = new ResponseMetadata
                {
                    RequestId = "testId"
                }
            };

            mockClient.Setup(x => x.SendCommandAsync(It.IsAny <SendCommandRequest>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(sendCommandResponse));
        }
Beispiel #15
0
        public async Task ShouldProcessAlert()
        {
            const string appName = "TEST APP";

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(f => f.CreateClient(Options.DefaultName)).Returns(() => new HttpClient());

            var alertProcessorRepository = new Mock <IAlertProcessorRepository>();
            var queryResultFetcher       = new Mock <IAppInsightsQueryResultFetcher>();

            queryResultFetcher.Setup((f) => f.FetchLogQueryResultsAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(() => Task.FromResult(new ResultSet
            {
                Tables = new[]
                {
                    new ResultSetTable
                    {
                        Columns = new[]
                        {
                            new ResultSetColumn
                            {
                                Name = "appType",
                                Type = string.Empty
                            }
                        },
                        Name = "table",
                        Rows = new[]
                        {
                            new []
                            {
                                appName
                            }
                        }
                    }
                }
            }));

            var processor = new ApplicationInsightsAlertProcessor(new NullLogger <ApplicationInsightsAlertProcessor>(), queryResultFetcher.Object);

            alertProcessorRepository.Setup(r => r.GetAlertProcessor("Application Insights")).Returns(processor);

            var functionInstance = new AzureMonitorAlertToTeamFunction(
                httpClientFactory.Object,
                new NullLogger <AzureMonitorAlertToTeamFunction>(),
                alertProcessorRepository.Object);

            var alertJson = await File.ReadAllTextAsync(Path.Combine(TestContext.CurrentContext.TestDirectory, @"assets\ApplicationInsights\alert.json"));

            await using var configurationStream = File.OpenRead(Path.Combine(TestContext.CurrentContext.TestDirectory, @"assets\ApplicationInsights\configuration.json"));

            var(teamsMessage, _) = await functionInstance.ProcessAlertAsync(alertJson, configurationStream);

            Assert.IsTrue(teamsMessage.Contains(appName), "Application Insights processor not called correctly, or template is incorrect");
            Assert.IsTrue(teamsMessage.Contains("Alert fired for rule Exception"), "Generic alert values not parsed correctly, or template is incorrect");
        }
		public void Perform_MustUseCommandLineArgumentAs1stPrio()
		{
			var settings = new Settings { ConfigurationMode = ConfigurationMode.Exam };
			var url = @"http://www.safeexambrowser.org/whatever.seb";
			var location = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);

			appConfig.AppDataFilePath = location;
			appConfig.ProgramDataFilePath = location;

			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);

			var sut = new ConfigurationOperation(new[] { "blubb.exe", url }, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			var result = sut.Perform();
			var resource = new Uri(url);

			repository.Verify(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>()), Times.Once);
			Assert.AreEqual(OperationResult.Success, result);
		}
 private void GivenRssEnabled()
 {
     Mocker.GetMock<IIndexerFactory>()
           .Setup(s => s.RssEnabled(It.IsAny<bool>()))
           .Returns(new List<IIndexer> { _indexerMock.Object });
 }
		public void Repeat_MustAbortForSettingsPasswordIfWishedByUser()
		{
			var currentSettings = new Settings();
			var location = Path.GetDirectoryName(GetType().Assembly.Location);
			var resource = new Uri(Path.Combine(location, nameof(Operations), FILE_NAME));
			var settings = new Settings { ConfigurationMode = ConfigurationMode.ConfigureClient };

			currentSession.SetupGet(s => s.Settings).Returns(currentSettings);
			sessionContext.ReconfigurationFilePath = resource.LocalPath;
			repository.Setup(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(resource)), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.PasswordNeeded);

			var sut = new ConfigurationOperation(null, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			sut.ActionRequired += args =>
			{
				if (args is PasswordRequiredEventArgs p)
				{
					p.Success = false;
				}
			};

			var result = sut.Repeat();

			Assert.AreEqual(OperationResult.Aborted, result);
		}
        public async Task CanEnsureMachineGroupAgentConfigureOnPremScenario()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                var onPremTfsUrl = "http://localtfs:8080/tfs";

                trace.Info("Preparing command line arguments for vsts scenario");
                var command = new CommandSettings(
                    tc,
                    new[]
                {
                    "configure",
#if !OS_WINDOWS
                    "--acceptteeeula",
#endif
                    "--deploymentgroup",
                    "--url", onPremTfsUrl,
                    "--agent", _expectedAgentName,
                    "--collectionname", _expectedCollectionName,
                    "--projectname", _expectedProjectName,
                    "--deploymentgroupname", _expectedMachineGroupName,
                    "--work", _expectedWorkFolder,
                    "--auth", _expectedAuthType,
                    "--token", _expectedToken
                });
                trace.Info("Constructed.");

                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                _extnMgr.Setup(x => x.GetExtensions <IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));

                _machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(GetDeploymentGroups(3, 7)));

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                await configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);

                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.NotNull(s);
                Assert.True(s.ServerUrl.Equals(onPremTfsUrl));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolId.Equals(7));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
                Assert.True(s.MachineGroupId.Equals(0));
                Assert.True(s.DeploymentGroupId.Equals(3));
                Assert.Null(s.ProjectName);
                Assert.True(s.ProjectId.Equals(_expectedProjectId));

                // Tags logic should not get trigger
                _machineGroupServer.Verify(x =>
                                           x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <List <DeploymentMachine> >()), Times.Never);
            }
        }
		public void Perform_MustUseAppDataAs3rdPrio()
		{
			var location = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), nameof(Operations), FILE_NAME);
			var settings = default(Settings);

			appConfig.AppDataFilePath = location;
			repository.Setup(r => r.TryLoadSettings(It.IsAny<Uri>(), out settings, It.IsAny<PasswordParameters>())).Returns(LoadStatus.Success);

			var sut = new ConfigurationOperation(null, repository.Object, hashAlgorithm.Object, logger.Object, sessionContext);
			var result = sut.Perform();

			repository.Verify(r => r.TryLoadSettings(It.Is<Uri>(u => u.Equals(location)), out settings, It.IsAny<PasswordParameters>()), Times.Once);
			Assert.AreEqual(OperationResult.Success, result);
		}
        public ConfigurationManagerL0()
        {
            _agentServer        = new Mock <IAgentServer>();
            _locationServer     = new Mock <ILocationServer>();
            _credMgr            = new Mock <ICredentialManager>();
            _promptManager      = new Mock <IPromptManager>();
            _store              = new Mock <IConfigurationStore>();
            _extnMgr            = new Mock <IExtensionManager>();
            _rsaKeyManager      = new Mock <IRSAKeyManager>();
            _machineGroupServer = new Mock <IDeploymentGroupServer>();
            _vstsAgentWebProxy  = new Mock <IVstsAgentWebProxy>();
            _cert = new Mock <IAgentCertificateManager>();

#if OS_WINDOWS
            _serviceControlManager = new Mock <IWindowsServiceControlManager>();
#endif

#if !OS_WINDOWS
            _serviceControlManager = new Mock <ILinuxServiceControlManager>();
#endif

            _capabilitiesManager = new CapabilitiesManager();

            var expectedAgent = new TaskAgent(_expectedAgentName)
            {
                Id = 1
            };
            var expectedDeploymentMachine = new DeploymentMachine()
            {
                Agent = expectedAgent, Id = _expectedDeploymentMachineId
            };
            expectedAgent.Authorization = new TaskAgentAuthorization
            {
                ClientId         = Guid.NewGuid(),
                AuthorizationUrl = new Uri("http://localhost:8080/tfs"),
            };

            var connectionData = new ConnectionData()
            {
                InstanceId     = Guid.NewGuid(),
                DeploymentType = DeploymentFlags.Hosted,
                DeploymentId   = Guid.NewGuid()
            };
            _agentServer.Setup(x => x.ConnectAsync(It.IsAny <Uri>(), It.IsAny <VssCredentials>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.GetConnectionDataAsync()).Returns(Task.FromResult <ConnectionData>(connectionData));
            _machineGroupServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _machineGroupServer.Setup(x => x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <List <DeploymentMachine> >()));
            _machineGroupServer.Setup(x => x.AddDeploymentTargetAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
            _machineGroupServer.Setup(x => x.ReplaceDeploymentTargetAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
            _machineGroupServer.Setup(x => x.GetDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(new List <DeploymentMachine>()
            {
            }));
            _machineGroupServer.Setup(x => x.DeleteDeploymentTargetAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult <object>(null));

            _store.Setup(x => x.IsConfigured()).Returns(false);
            _store.Setup(x => x.HasCredentials()).Returns(false);
            _store.Setup(x => x.GetSettings()).Returns(() => _configMgrAgentSettings);

            _store.Setup(x => x.SaveSettings(It.IsAny <AgentSettings>()))
            .Callback((AgentSettings settings) =>
            {
                _configMgrAgentSettings = settings;
            });

            _credMgr.Setup(x => x.GetCredentialProvider(It.IsAny <string>())).Returns(new TestAgentCredential());

#if !OS_WINDOWS
            _serviceControlManager.Setup(x => x.GenerateScripts(It.IsAny <AgentSettings>()));
#endif

            var expectedPools = new List <TaskAgentPool>()
            {
                new TaskAgentPool(_expectedPoolName)
                {
                    Id = _expectedPoolId
                }
            };
            _agentServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny <string>(), It.IsAny <TaskAgentPoolType>())).Returns(Task.FromResult(expectedPools));

            var expectedAgents = new List <TaskAgent>();
            _agentServer.Setup(x => x.GetAgentsAsync(It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(expectedAgents));

            _agentServer.Setup(x => x.AddAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));
            _agentServer.Setup(x => x.UpdateAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));

            rsa = new RSACryptoServiceProvider(2048);

            _rsaKeyManager.Setup(x => x.CreateKey()).Returns(rsa);
        }
Beispiel #22
0
        private static IAuthenticationFilter CreateAuthenticationFilterChallenge(
            Action <HttpAuthenticationChallengeContext, CancellationToken> challenge)
        {
            Mock <IAuthenticationFilter> mock = new Mock <IAuthenticationFilter>();

            mock.Setup(f => f.AuthenticateAsync(It.IsAny <HttpAuthenticationContext>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <object>(null));
            mock.Setup(f => f.ChallengeAsync(It.IsAny <HttpAuthenticationChallengeContext>(),
                                             It.IsAny <CancellationToken>()))
            .Callback <HttpAuthenticationChallengeContext, CancellationToken>((c, t) =>
            {
                challenge.Invoke(c, t);
            })
            .Returns(() => Task.FromResult <object>(null));
            return(mock.Object);
        }
Beispiel #23
0
        private Mock <IIPYarnTypeService> GetGlobalDefaultMock()
        {
            var serviceMock = new Mock <IIPYarnTypeService>();

            serviceMock.Setup(s => s.ReadAll())
            .Returns(new ListResult <IPYarnTypeViewModel>(new List <IPYarnTypeViewModel> {
                ViewModel
            }, 1, 1, 1));
            serviceMock.Setup(s => s.ReadById(It.IsAny <int>()))
            .ReturnsAsync(ViewModel);
            serviceMock.Setup(s => s.ReadByPage(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .Returns(new ListResult <IPYarnTypeViewModel>(new List <IPYarnTypeViewModel> {
                ViewModel
            }, 1, 1, 1));
            serviceMock.Setup(s => s.Create(It.IsAny <IPYarnTypeViewModel>()))
            .ReturnsAsync(1);
            serviceMock.Setup(s => s.Update(It.IsAny <int>(), It.IsAny <IPYarnTypeViewModel>()))
            .ReturnsAsync(1);
            serviceMock.Setup(s => s.Delete(It.IsAny <int>()))
            .ReturnsAsync(1);
            return(serviceMock);
        }
Beispiel #24
0
        private static IAuthenticationFilter CreateStubFilter()
        {
            Mock <IAuthenticationFilter> mock = new Mock <IAuthenticationFilter>(MockBehavior.Strict);

            mock.Setup(f => f.AuthenticateAsync(It.IsAny <HttpAuthenticationContext>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <object>(null));
            mock.Setup(f => f.ChallengeAsync(It.IsAny <HttpAuthenticationChallengeContext>(),
                                             It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <object>(null));
            return(mock.Object);
        }
Beispiel #25
0
        //private IPWidthTypeController GetController(IIPWidthTypeService service, IIdentityProvider identityProvider)
        //{
        //    var claimPrincipal = new Mock<ClaimsPrincipal>();
        //    var claims = new Claim[]
        //    {
        //        new Claim("username", "unittestusername")
        //    };
        //    claimPrincipal.Setup(claim => claim.Claims).Returns(claims);

        //    var controller = new IPWidthTypeController(service, identityProvider)
        //    {
        //        ControllerContext = new ControllerContext()
        //        {
        //            HttpContext = new DefaultHttpContext()
        //            {
        //                User = claimPrincipal.Object

        //            }
        //        }
        //    };
        //    controller.ControllerContext.HttpContext.Request.Headers["Authorization"] = "Bearer unittesttoken";
        //    controller.ControllerContext.HttpContext.Request.Headers["x-timezone-offset"] = $"{It.IsAny<int>()}";
        //    controller.ControllerContext.HttpContext.Request.Path = new PathString("/v1/unit-test");

        //    return controller;
        //}

        public IPYarnTypeController GetController()
        {
            var claimPrincipal = new Mock <ClaimsPrincipal>();
            var claims         = new Claim[]
            {
                new Claim("username", "unittestusername")
            };

            claimPrincipal.Setup(claim => claim.Claims).Returns(claims);

            var controller = new IPYarnTypeController(_serviceMock, _identityProvider, _validateMock)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        User = claimPrincipal.Object
                    }
                }
            };

            controller.ControllerContext.HttpContext.Request.Headers["Authorization"]     = "Bearer unittesttoken";
            controller.ControllerContext.HttpContext.Request.Headers["x-timezone-offset"] = $"{It.IsAny<int>()}";
            controller.ControllerContext.HttpContext.Request.Path = new PathString("/v1/unit-test");

            return(controller);
        }
 private void GivenTheTemplateVariableAndNameFinderReturns(Response<List<UrlPathPlaceholderNameAndValue>> response)
 {
     _finder
         .Setup(x => x.Find(It.IsAny<string>(), It.IsAny<string>()))
         .Returns(response);
 }
Beispiel #27
0
		[TestCase (true)] // timeoout
		public void LoadAsyncProcessErrorTest (bool timeout)
		{
			string processPath = null;
			MlaunchArguments passedArguments = null;

			// moq It.Is is not working as nicelly as we would like it, we capture data and use asserts
			processManager.Setup (p => p.RunAsync (It.IsAny<Process> (), It.IsAny<MlaunchArguments> (), It.IsAny<ILog> (), It.IsAny<TimeSpan?> (), It.IsAny<Dictionary<string, string>> (), It.IsAny<CancellationToken?> (), It.IsAny<bool?> ()))
				.Returns<Process, MlaunchArguments, ILog, TimeSpan?, Dictionary<string, string>, CancellationToken?, bool?> ((p, args, log, t, env, token, d) => {
					// we are going set the used args to validate them later, will always return an error from this method
					processPath = p.StartInfo.FileName;
					passedArguments = args;
					if (!timeout)
						return Task.FromResult (new ProcessExecutionResult { ExitCode = 1, TimedOut = false });
					else
						return Task.FromResult (new ProcessExecutionResult { ExitCode = 0, TimedOut = true });
				});

			Assert.ThrowsAsync<Exception> (async () => {
				await devices.LoadDevices (executionLog.Object);
			});

			MlaunchArgument listDevArg = passedArguments.Where (a => a is ListDevicesArgument).FirstOrDefault ();
			Assert.IsNotNull (listDevArg, "list devices arg missing");

			MlaunchArgument outputFormatArg = passedArguments.Where (a => a is XmlOutputFormatArgument).FirstOrDefault ();
			Assert.IsNotNull (outputFormatArg, "output format arg missing");
		}
Beispiel #28
0
        public Task TestRevocableSession()
        {
            IObjectState state = new MutableObjectState {
                ServerData = new Dictionary <string, object>()
                {
                    { "sessionToken", "llaKcolnu" }
                }
            };
            IObjectState newState = new MutableObjectState {
                ServerData = new Dictionary <string, object>()
                {
                    { "sessionToken", "r:llaKcolnu" }
                }
            };
            ParseUser user = ParseObject.FromState <ParseUser>(state, "_User");
            var       mockSessionController = new Mock <IParseSessionController>();

            mockSessionController.Setup(obj => obj.UpgradeToRevocableSessionAsync("llaKcolnu",
                                                                                  It.IsAny <CancellationToken>())).Returns(Task.FromResult(newState));
            ParseCorePlugins.Instance.SessionController = mockSessionController.Object;

            return(user.UpgradeToRevocableSessionAsync().ContinueWith(t => {
                Assert.False(t.IsFaulted);
                Assert.False(t.IsCanceled);
                mockSessionController.Verify(obj => obj.UpgradeToRevocableSessionAsync("llaKcolnu",
                                                                                       It.IsAny <CancellationToken>()), Times.Exactly(1));
                Assert.AreEqual("r:llaKcolnu", user.SessionToken);
            }));
        }
 public void VerifyInspectSelectedDefaultScale()
 {
     var scale1 = new LogarithmicScale(Guid.NewGuid(), null, null);
     var vm = new SimpleQuantityKindDialogViewModel(this.simpleQuantityKind, this.transaction, this.session.Object, true, ThingDialogKind.Inspect, this.navigation.Object, this.rdl);
     Assert.IsFalse(vm.InspectSelectedScaleCommand.CanExecute(null));
     vm.SelectedDefaultScale = scale1;
     Assert.IsTrue(vm.InspectSelectedScaleCommand.CanExecute(null));
     vm.InspectSelectedScaleCommand.Execute(null);
     this.navigation.Verify(x => x.Navigate(It.IsAny<MeasurementScale>(), It.IsAny<ThingTransaction>(), this.session.Object, false, ThingDialogKind.Inspect, this.navigation.Object, It.IsAny<Thing>(), null));
 }
        private static ClientNotifierServiceBase CreateLanguageServer(CodeAction resolvedCodeAction = null)
        {
            var responseRouterReturns = new Mock<IResponseRouterReturns>(MockBehavior.Strict);
            responseRouterReturns
                .Setup(l => l.Returning<CodeAction>(It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(resolvedCodeAction ?? s_defaultResolvedCodeAction));

            var languageServer = new Mock<ClientNotifierServiceBase>(MockBehavior.Strict);
            languageServer
                .Setup(l => l.SendRequestAsync(LanguageServerConstants.RazorResolveCodeActionsEndpoint, It.IsAny<RazorResolveCodeActionParams>()))
                .Returns(Task.FromResult(responseRouterReturns.Object));

            return languageServer.Object;
        }