public async Task NavigateToAuthPage_SetsPageNumberTo2_AndSetsSsoEnabledOnTargetToFalse_WhenSsoPromptAbsentFromResponse() { var fakeCertValidationResult = new DetailedResult { Succeeded = true, }; var fakeSsoPromptResult = new DetailedResult <string> { Succeeded = false, FailureType = FailureType.MissingSsoPrompt, }; MockCloudFoundryService.Setup(m => m.TargetApi(_sut.Target, _sut.ProceedWithInvalidCertificate)) .Returns(fakeCertValidationResult); MockCloudFoundryService.Setup(m => m.GetSsoPrompt(_sut.Target, false)) .ReturnsAsync(fakeSsoPromptResult); Assert.AreEqual(1, _sut.PageNum); await _sut.NavigateToAuthPage(); Assert.AreEqual(2, _sut.PageNum); Assert.IsFalse(_sut.SsoEnabledOnTarget); }
public async Task NavigateToAuthPage_DoesNotChangePageNumber_AndSetsApiAddressError_WhenSsoPromptRequestFails() { var fakeCertValidationResult = new DetailedResult { Succeeded = true, }; var fakeSsoPromptResult = new DetailedResult <string> { Succeeded = false, FailureType = FailureType.None, }; MockCloudFoundryService.Setup(m => m.TargetApi(_sut.Target, _sut.ProceedWithInvalidCertificate)) .Returns(fakeCertValidationResult); MockCloudFoundryService.Setup(m => m.GetSsoPrompt(_sut.Target, false)) .ReturnsAsync(fakeSsoPromptResult); Assert.AreEqual(1, _sut.PageNum); await _sut.NavigateToAuthPage(); Assert.AreEqual(1, _sut.PageNum); Assert.IsFalse(_sut.ApiAddressIsValid); Assert.AreEqual($"Unable to establish a connection with {_sut.Target}", _sut.ApiAddressError); }
public async Task RefreshChildren_RemovesPlaceholder_WhenEmptyCfGainsChildren() { // simulate cf initially having no org children _sut.Children = new ObservableCollection <TreeViewItemViewModel> { _sut.EmptyPlaceholder }; _sut.HasEmptyPlaceholder = true; var fakeNewOrg = new CloudFoundryOrganization("fake org name", "fake org id", _sut.CloudFoundryInstance); var fakeSuccessfulOrgsResult = new DetailedResult <List <CloudFoundryOrganization> >( succeeded: true, content: new List <CloudFoundryOrganization> { fakeNewOrg, // simulate cf having gained an org child before refresh }, explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(_sut.CloudFoundryInstance, true, It.IsAny <int>())) .ReturnsAsync(fakeSuccessfulOrgsResult); Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); Assert.AreEqual(CfInstanceViewModel._emptyOrgsPlaceholderMsg, _sut.Children[0].DisplayText); await _sut.RefreshChildren(); Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(OrgViewModel), _sut.Children[0].GetType()); }
private static void ThrowIfResultIndicatesInvalidRefreshToken(DetailedResult result) { if (result != null && result.CmdResult != null && result.CmdResult.StdErr != null && result.CmdResult.StdErr.Contains(_invalidRefreshTokenError)) { throw new InvalidRefreshTokenException(); } }
public async Task DeployAppAsync_ReturnsTrueResult_WhenCfTargetAndPushCommandsSucceed() { var cfTargetArgs = $"target -o {fakeOrg.OrgName} -s {fakeSpace.SpaceName}"; var cfPushArgs = $"push {fakeApp.AppName}"; var fakeCfTargetResponse = new DetailedResult(true); var fakeCfPushResponse = new DetailedResult(true); mockCfCliService.Setup(mock => mock.ExecuteCfCliCommandAsync(cfTargetArgs, It.IsAny <StdOutDelegate>(), It.IsAny <string>())) .ReturnsAsync(fakeCfTargetResponse); mockCfCliService.Setup(mock => mock.ExecuteCfCliCommandAsync(cfPushArgs, It.IsAny <StdOutDelegate>(), It.IsAny <string>())) .ReturnsAsync(fakeCfPushResponse); mockFileLocatorService.Setup(mock => mock.DirContainsFiles(It.IsAny <string>())).Returns(true); DetailedResult result = await cfService.DeployAppAsync(fakeCfInstance, fakeOrg, fakeSpace, fakeApp.AppName, fakeProjectPath, stdOutHandler : null); Assert.IsTrue(result.Succeeded); mockCfCliService.Verify(mock => mock.ExecuteCfCliCommandAsync(cfTargetArgs, null, null), Times.Once); mockCfCliService.Verify(mock => mock.ExecuteCfCliCommandAsync(cfPushArgs, null, fakeProjectPath), Times.Once); }
public async Task LoadChildren_CollapsesTreeViewItem_WhenOrgsRequestFails() { var expandedViewModel = new CfInstanceViewModel(FakeCfInstance, null, Services) { IsExpanded = true, }; expandedViewModel.PropertyChanged += (sender, e) => { _receivedEvents.Add(e.PropertyName); }; var fakeFailedResult = new DetailedResult <List <CloudFoundryOrganization> >( succeeded: false, content: null, explanation: "junk", cmdDetails: FakeFailureCmdResult); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(expandedViewModel.CloudFoundryInstance, true, 1)) .ReturnsAsync(fakeFailedResult); Assert.IsTrue(expandedViewModel.IsExpanded); await expandedViewModel.LoadChildren(); Assert.IsFalse(expandedViewModel.IsLoading); Assert.IsFalse(expandedViewModel.IsExpanded); Assert.IsTrue(_receivedEvents.Contains("IsExpanded")); MockErrorDialogService.Verify(mock => mock. DisplayErrorDialog(CfInstanceViewModel._getOrgsFailureMsg, fakeFailedResult.Explanation), Times.Once); }
void OnWorkshopError(SteamworksError error, DetailedResult result) { if (onError != null) { onError(error, result); } }
public async Task FetchChildren_ReturnsListOfApps_WithoutUpdatingChildren() { var fakeAppsList = new List <CloudFoundryApp> { new CloudFoundryApp("fake app name 1", "fake app id 1", FakeCfSpace, null), new CloudFoundryApp("fake app name 2", "fake app id 2", FakeCfSpace, null), }; var fakeAppsResult = new DetailedResult <List <CloudFoundryApp> >( succeeded: true, content: fakeAppsList, explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetAppsForSpaceAsync(_sut.Space, true, It.IsAny <int>())) .ReturnsAsync(fakeAppsResult); /* pre-check presence of placeholder */ Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); var apps = await _sut.FetchChildren(); Assert.AreEqual(2, apps.Count); /* confirm presence of placeholder */ Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); // property changed events should not be raised Assert.AreEqual(0, _receivedEvents.Count); }
public async Task RefreshChildren_AddsPlaceholder_WhenAllAppsAreRemoved() { var fakeInitialApp = new CloudFoundryApp("fake app name", "fake app id", _sut.Space, null); var avm = new AppViewModel(fakeInitialApp, Services); var fakeNoAppsResult = new DetailedResult <List <CloudFoundryApp> >( succeeded: true, content: new List <CloudFoundryApp>(), // simulate space having lost all apps before refresh explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetAppsForSpaceAsync(_sut.Space, true, It.IsAny <int>())) .ReturnsAsync(fakeNoAppsResult); _sut.Children = new ObservableCollection <TreeViewItemViewModel> { avm }; // simulate space initially having 1 app child Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(AppViewModel), _sut.Children[0].GetType()); await _sut.RefreshChildren(); Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); Assert.AreEqual(SpaceViewModel.EmptyAppsPlaceholderMsg, _sut.Children[0].DisplayText); }
public async Task FetchChildren_ReturnsListOfOrgs_WithoutUpdatingChildren() { var fakeOrgsList = new List <CloudFoundryOrganization> { new CloudFoundryOrganization("fake org name 1", "fake org id 1", FakeCfInstance), new CloudFoundryOrganization("fake org name 2", "fake org id 2", FakeCfInstance), }; var fakeSuccessResult = new DetailedResult <List <CloudFoundryOrganization> >(succeeded: true, content: fakeOrgsList); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(_sut.CloudFoundryInstance, true, It.IsAny <int>())) .ReturnsAsync(fakeSuccessResult); /* pre-check presence of placeholder */ Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); var orgs = await _sut.FetchChildren(); Assert.AreEqual(2, orgs.Count); foreach (TreeViewItemViewModel child in orgs) { Assert.AreEqual(_sut, child.Parent); } /* confirm presence of placeholder */ Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); // property changed events should not be raised Assert.AreEqual(0, _receivedEvents.Count); }
public async Task RefreshChildren_AddsPlaceholder_WhenAllSpacesAreRemoved() { var fakeInitialSpace = new CloudFoundrySpace("fake space name", "fake space id", _sut.Org); var svm = new SpaceViewModel(fakeInitialSpace, null, null, Services); var fakeNoSpacesResult = new DetailedResult <List <CloudFoundrySpace> >( succeeded: true, content: new List <CloudFoundrySpace>(), // simulate org having lost all spaces before refresh explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetSpacesForOrgAsync(_sut.Org, true, It.IsAny <int>())) .ReturnsAsync(fakeNoSpacesResult); _sut.Children = new ObservableCollection <TreeViewItemViewModel> { svm }; // simulate org initially having 1 space child Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(SpaceViewModel), _sut.Children[0].GetType()); await _sut.RefreshChildren(); Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); Assert.AreEqual(OrgViewModel._emptySpacesPlaceholderMsg, _sut.Children[0].DisplayText); }
/// <summary> /// Invokes the `cf api` command to access the currently-running version of the Cloud Controller API. /// </summary> /// <returns> /// <code>int[] versionNumbers</code>Array of integers: versionNumbers[0] = major version, versionNumbers[1] = minor, etc. /// </returns> public async Task <Version> GetApiVersion() { DetailedResult result = await RunCfCommandAsync(_getApiVersionCmd); if (!result.Succeeded) { return(null); } try { const string versionLabel = "api version:"; var content = result.CmdResult.StdOut.ToLower(); var versionString = content.Substring(content.IndexOf(versionLabel)) .Replace("\n", string.Empty) .Replace(versionLabel, string.Empty) .Replace(" ", string.Empty); var version = new Version(versionString); return(version); } catch { return(null); } }
public async Task RefreshChildren_AddsPlaceholder_WhenAllOrgsAreRemoved() { var fakeInitialOrg = new CloudFoundryOrganization("fake org name", "fake org id", parentCf: _sut.CloudFoundryInstance); var ovm = new OrgViewModel(fakeInitialOrg, null, null, Services); var fakeEmptyOrgsResult = new DetailedResult <List <CloudFoundryOrganization> >( succeeded: true, content: new List <CloudFoundryOrganization>(), // simulate cf having lost all orgs before refresh explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(_sut.CloudFoundryInstance, true, It.IsAny <int>())) .ReturnsAsync(fakeEmptyOrgsResult); _sut.Children = new ObservableCollection <TreeViewItemViewModel> { ovm }; // simulate cf initially having 1 org child Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(OrgViewModel), _sut.Children[0].GetType()); await _sut.RefreshChildren(); Assert.AreEqual(1, _sut.Children.Count); Assert.AreEqual(typeof(PlaceholderViewModel), _sut.Children[0].GetType()); Assert.AreEqual(CfInstanceViewModel._emptyOrgsPlaceholderMsg, _sut.Children[0].DisplayText); }
public void GetDetailed_GivenUniqueIdReturnsResultWithSameId() { var api = Global.ApiFactory(); string uniqueId = "190227-BSF_10-GC95"; DetailedResult detailedResult = api.GetDetailed(uniqueId); Assert.Equal(uniqueId, detailedResult.Id); }
public async Task ExecuteCfCliCommandAsync_ReturnsFalseResult_WhenCfExeCouldNotBeFound() { mockFileLocatorService.SetupGet(mock => mock.FullPathToCfExe).Returns((string)null); DetailedResult result = await _sut.ExecuteCfCliCommandAsync(_fakeArguments, stdOutHandler : null); Assert.IsFalse(result.Succeeded); Assert.IsTrue(result.Explanation.Contains("Unable to locate cf.exe")); }
public async Task ExecuteCfCliCommandAsync_ReturnsFalseResult_WhenProcessFails() { mockFileLocatorService.SetupGet(mock => mock.FullPathToCfExe).Returns(_fakePathToCfExe); mockCmdProcessService.Setup(mock => mock.ExecuteWindowlessCommandAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <StdOutDelegate>())) .ReturnsAsync(false); DetailedResult result = await _sut.ExecuteCfCliCommandAsync(_fakeArguments, stdOutHandler : null); Assert.IsFalse(result.Succeeded); }
public void GetDetailed_GivenDataGetDetailedUniqueIdReturnsResultWithSameId() { var config = Global.GetConfig; var api = new AbouRestApi(config); var data = new DataGetDetailed(config) { UniqueId = "190227-BSF_10-GC95" }; DetailedResult detailedResult = api.GetDetailed(data); Assert.Equal(data.UniqueId, detailedResult.Id); }
public async Task <DetailedResult> DeleteAppByNameAsync(string appName, bool removeMappedRoutes = true) { string args = $"{_deleteAppCmd} \"{appName}\"{(removeMappedRoutes ? " -r" : string.Empty)}"; DetailedResult result = await RunCfCommandAsync(args); if (!result.Succeeded) { _logger.Error($"DeleteAppByNameAsync({appName}, {removeMappedRoutes}) failed during InvokeCfCliAsync: {result}"); } return(result); }
public async Task <DetailedResult> StartAppByNameAsync(string appName) { string args = $"{_startAppCmd} \"{appName}\""; DetailedResult result = await RunCfCommandAsync(args); if (!result.Succeeded) { _logger.Error($"StartAppByNameAsync({appName}) failed during InvokeCfCliAsync: {result}"); } return(result); }
/// <summary> /// Retrieves an access token to be used for authentication with Cloud Foundry UAA. /// <para> /// A cached value of the access token will be returned as long as the expiration time of the token has not yet been reached. /// If there is no cached value for the access token or the expiration time of the cached token has been reached, this method /// will invoke the CF CLI oauth-token command to acquire a new access token. Invoking the CF CLI oauth-token command will /// attempt to renew the access token using the refresh token stored by the CF CLI. /// </para> /// <para> /// The cached value for the access token can be cleared using <see cref="ClearCachedAccessToken"/>; this will force a fresh /// access token to be obtained using the refresh token via the CF CLI oauth-token command. /// </para> /// <exception cref="InvalidRefreshTokenException">Throws <see cref="InvalidRefreshTokenException"/> if a fresh access token /// is unobtainable to due an invalid refresh token (this would occur once the refresh token reaches the end of its /// prescribed lifetime).</exception> /// </summary> /// <returns><see cref="string"/> accessToken on success.<para>null on failure.</para></returns> public string GetOAuthToken() { if (_cachedAccessToken == null || _accessTokenExpiration == null || DateTime.Compare(DateTime.Now, _accessTokenExpiration) >= 0) { lock (_cfEnvironmentLock) { // double-check just in case the last thread to access this block changed these values // (prevents scenario where many threads wait for lock once token expires, then *all* try to refresh token) if (_cachedAccessToken == null || _accessTokenExpiration == null || DateTime.Compare(DateTime.Now, _accessTokenExpiration) >= 0) { try { DetailedResult result = ExecuteCfCliCommand(_getOAuthTokenCmd); if (result == null) { return(null); } ThrowIfResultIndicatesInvalidRefreshToken(result); if (result.CmdResult.ExitCode != 0) { _logger.Error($"GetOAuthToken failed: {result}"); return(null); } var accessToken = FormatToken(result.CmdResult.StdOut); var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(accessToken); var token = jsonToken as JwtSecurityToken; _cachedAccessToken = accessToken; _accessTokenExpiration = token.ValidTo; } catch (Exception ex) { if (ex is InvalidRefreshTokenException) { throw ex; } _logger.Error("Something went wrong while attempting to renew access token {TokenException}", ex); } } } } return(_cachedAccessToken); }
/// <summary> /// Invokes a `cf target -s` command using the CF CLI. /// <para>This method is not thread-safe; if two threads invoke it simultaneously, the /// first one to change the targeted space may have its efforts undone when the second /// one changes the targeted space. </para> /// <para>To avoid race conditions around the "targeted space" value, make sure to invoke /// this method only after acquiring the <see cref="_cfEnvironmentLock"/>.</para> /// <exception cref="InvalidRefreshTokenException">Throws <see cref="InvalidRefreshTokenException"/> if a fresh access token /// is unobtainable to due an invalid refresh token (this would occur once the refresh token reaches the end of its /// prescribed lifetime).</exception> /// </summary> /// <param name="spaceName"></param> /// <returns></returns> public DetailedResult TargetSpace(string spaceName) { string args = $"{_targetSpaceCmd} \"{spaceName}\""; DetailedResult result = ExecuteCfCliCommand(args); ThrowIfResultIndicatesInvalidRefreshToken(result); if (result == null || !result.Succeeded) { _logger.Error("TargetSpace({SpaceName}) failed: {TargetSpaceResult}", spaceName, result); } return(result); }
public async Task ExecuteCfCliCommandAsync_UsesDefaultDir_WhenNotSpecified() { mockFileLocatorService.SetupGet(mock => mock.FullPathToCfExe).Returns(_fakePathToCfExe); mockCmdProcessService.Setup(mock => mock.ExecuteWindowlessCommandAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <StdOutDelegate>())) .ReturnsAsync(true); DetailedResult result = await _sut.ExecuteCfCliCommandAsync(_fakeArguments, stdOutHandler : null); string expectedCmdStr = $"\"{_fakePathToCfExe}\" {_fakeArguments}"; string expectedWorkingDir = null; mockCmdProcessService.Verify(mock => mock.ExecuteWindowlessCommandAsync(expectedCmdStr, expectedWorkingDir, null), Times.Once()); }
public async Task LoadChildren_SetsIsLoadingToFalse_WhenOrgsRequestFails() { var fakeFailedResult = new DetailedResult <List <CloudFoundryOrganization> >(succeeded: false, content: null); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(_sut.CloudFoundryInstance, true, It.IsAny <int>())) .ReturnsAsync(fakeFailedResult); _sut.IsLoading = true; await _sut.LoadChildren(); Assert.IsFalse(_sut.IsLoading); }
private static void GetDetailed(string CaseUniqueId, string comment, string actor, bool writeToFile) { using (var client = new HttpClient()) { string data = string.Format("{{\"UniqueId\":\"{0}\",\"DiaryNumber\":\"{1}\",\"Comment\":\"{2}\",\"Actor\":\"{3}\",\"XmlGeneratorType\":\"{4}\",\"IncludeAllFields\":\"{5}\",\"IncludeAllAttachements\":\"{6}\",\"OmitXmlDeclaration\":\"{7}\"}}", CaseUniqueId, "", comment, actor, "Abou.Calamare.Framework.Integration.Xml.Default.DefaultXmlCaseGenerator", true, true, true); var stringContent = new StringContent(data); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var request = client.PostAsync(string.Format("{0}/{1}/cases/GetDetailed?username={2}&apikey={3}", ApiUrl, ServiceShortName, ApiUserName, ApiKey), stringContent); var httpResponse = request.Result; var statusCode = httpResponse.StatusCode; if (httpResponse.Content == null) { return; } var stringContentsTask = httpResponse.Content.ReadAsStringAsync(); var stringContents = stringContentsTask.Result; if (!writeToFile) { return; } File.WriteAllText(string.Format(@"C:\Temp\{0}.json", CaseUniqueId), stringContents); DetailedResult detailedResult = Helper.FromJson <DetailedResult>(stringContents); var antal = detailedResult.Attachments.Count; string path = $"\\\\intra.lund.se\\GroupData\\309150\\abou2w3d3\\{detailedResult.Id}"; Directory.CreateDirectory(path); Directory.CreateDirectory($"{path}\\ansokan"); Directory.CreateDirectory($"{path}\\bilagor"); Directory.CreateDirectory($"{path}\\beslut"); foreach (var attachment in detailedResult.Attachments) { if (attachment.SystemFileName.Length > 0) { CaseAttachmentDownload(CaseUniqueId, attachment.SystemFileName, path, true); } } CasePdfDownload(CaseUniqueId, path, true); } }
public async Task NavigateToAuthPage_SetsCertificateInvalidToTrue_WhenCertValidationFails() { var fakeCertValidationResult = new DetailedResult { Succeeded = false, FailureType = FailureType.InvalidCertificate, }; MockCloudFoundryService.Setup(m => m.TargetApi(_sut.Target, _sut.ProceedWithInvalidCertificate)) .Returns(fakeCertValidationResult); Assert.AreEqual(1, _sut.PageNum); await _sut.NavigateToAuthPage(); Assert.AreEqual(1, _sut.PageNum); Assert.IsTrue(_sut.CertificateInvalid); }
public async Task LoadChildren_SetsIsLoadingToFalse_WhenComplete() { var fakeNoSpacesResponse = new DetailedResult <List <CloudFoundrySpace> >( content: EmptyListOfSpaces, succeeded: true, explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetSpacesForOrgAsync(_sut.Org, true, It.IsAny <int>())) .ReturnsAsync(fakeNoSpacesResponse); _sut.IsLoading = true; await _sut.LoadChildren(); Assert.IsFalse(_sut.IsLoading); }
public async Task LoadChildren_UpdatesAllSpaces() { var initialSpacesList = new System.Collections.ObjectModel.ObservableCollection <TreeViewItemViewModel> { new SpaceViewModel(new CloudFoundrySpace("initial space 1", "initial space 1 guid", null), null, null, Services), new SpaceViewModel(new CloudFoundrySpace("initial space 2", "initial space 2 guid", null), null, null, Services), new SpaceViewModel(new CloudFoundrySpace("initial space 3", "initial space 3 guid", null), null, null, Services), }; var newSpacesList = new List <CloudFoundrySpace> { new CloudFoundrySpace("initial space 1", "initial space 1 guid", null), new CloudFoundrySpace("initial space 2", "initial space 2 guid", null), }; var fakeSucccessResponse = new DetailedResult <List <CloudFoundrySpace> >( content: newSpacesList, succeeded: true, explanation: null, cmdDetails: FakeSuccessCmdResult); _sut.Children = initialSpacesList; /* erase record of initial "Children" event */ _receivedEvents.Clear(); MockCloudFoundryService.Setup(mock => mock. GetSpacesForOrgAsync(It.IsAny <CloudFoundryOrganization>(), true, It.IsAny <int>())) .ReturnsAsync(fakeSucccessResponse); Assert.AreEqual(initialSpacesList.Count, _sut.Children.Count); await _sut.LoadChildren(); Assert.AreEqual(newSpacesList.Count, _sut.Children.Count); foreach (TreeViewItemViewModel child in _sut.Children) { Assert.AreEqual(_sut, child.Parent); } Assert.AreEqual(1, _receivedEvents.Count); Assert.AreEqual("Children", _receivedEvents[0]); Assert.IsFalse(_sut.HasEmptyPlaceholder); }
public async Task <DetailedResult> AuthenticateAsync(string username, SecureString password) { string passwordStr = new System.Net.NetworkCredential(string.Empty, password).Password; string args = $"{_authenticateCmd} {username} {passwordStr}"; DetailedResult result = await RunCfCommandAsync(args); /* Erase pw from memory */ passwordStr = null; password.Clear(); password.Dispose(); if (!result.Succeeded) { _logger.Error($"AuthenticateAsync({username}, ***) failed: {result}"); } return(result); }
public async Task LoadChildren_UpdatesAllOrgs() { var initialOrgsList = new System.Collections.ObjectModel.ObservableCollection <TreeViewItemViewModel> { new OrgViewModel(new CloudFoundryOrganization("initial org 1", "initial org 1 guid", null), null, null, Services), new OrgViewModel(new CloudFoundryOrganization("initial org 2", "initial org 2 guid", null), null, null, Services), new OrgViewModel(new CloudFoundryOrganization("initial org 3", "initial org 3 guid", null), null, null, Services), }; var newOrgsList = new List <CloudFoundryOrganization> { new CloudFoundryOrganization("initial org 1", "initial org 1 guid", null), new CloudFoundryOrganization("initial org 2", "initial org 2 guid", null), }; var fakeSuccessResult = new DetailedResult <List <CloudFoundryOrganization> >(succeeded: true, content: newOrgsList); _sut.Children = initialOrgsList; /* erase record of initial "Children" event */ _receivedEvents.Clear(); MockCloudFoundryService.Setup(mock => mock. GetOrgsForCfInstanceAsync(_sut.CloudFoundryInstance, true, It.IsAny <int>())) .ReturnsAsync(fakeSuccessResult); Assert.AreEqual(initialOrgsList.Count, _sut.Children.Count); await _sut.LoadChildren(); Assert.AreEqual(newOrgsList.Count, _sut.Children.Count); foreach (TreeViewItemViewModel child in _sut.Children) { Assert.AreEqual(_sut, child.Parent); } Assert.AreEqual(1, _receivedEvents.Count); Assert.AreEqual("Children", _receivedEvents[0]); Assert.IsFalse(_sut.HasEmptyPlaceholder); }
public async Task RefreshChildren_UpdatesAppState_ForAllChildren() { var initialState1 = "INITIAL_FAKE_STATE"; var initialState2 = "INITIAL_JUNK_STATE"; var initialState3 = "INITIAL_BOGUS_STATE"; var fakeInitialApp1 = new CloudFoundryApp("fakeApp1", "junk", _sut.Space, initialState1); var fakeInitialApp2 = new CloudFoundryApp("fakeApp2", "junk", _sut.Space, initialState2); var fakeInitialApp3 = new CloudFoundryApp("fakeApp3", "junk", _sut.Space, initialState3); var fakeFreshApp1 = new CloudFoundryApp("fakeApp1", "junk", _sut.Space, initialState1); var fakeFreshApp2 = new CloudFoundryApp("fakeApp2", "junk", _sut.Space, "NEW_FRESH_STATE"); // simulate state change var fakeFreshApp3 = new CloudFoundryApp("fakeApp3", "junk", _sut.Space, "NEW_COOL_STATE"); // simulate state change _sut.Children = new ObservableCollection <TreeViewItemViewModel> { new AppViewModel(fakeInitialApp1, Services), new AppViewModel(fakeInitialApp2, Services), new AppViewModel(fakeInitialApp3, Services), }; var fakeSuccessfulAppsResult = new DetailedResult <List <CloudFoundryApp> >( succeeded: true, content: new List <CloudFoundryApp> { fakeFreshApp1, fakeFreshApp2, fakeFreshApp3, }, explanation: null, cmdDetails: FakeSuccessCmdResult); MockCloudFoundryService.Setup(mock => mock. GetAppsForSpaceAsync(_sut.Space, true, It.IsAny <int>())) .ReturnsAsync(fakeSuccessfulAppsResult); await _sut.RefreshChildren(); Assert.AreEqual(fakeInitialApp1.State, fakeFreshApp1.State); Assert.AreNotEqual(fakeInitialApp2.State, fakeFreshApp2.State); Assert.AreNotEqual(fakeInitialApp3.State, fakeFreshApp3.State); }