PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ResourceManager/Resources/Commands.Resources.Test/Models.ResourceGroups/ResourceClientTests.cs

https://gitlab.com/jslee1/azure-powershell
C# | 978 lines | 868 code | 97 blank | 13 comment | 8 complexity | a14b680ddaaa4a0238be3a1d6e639365 MD5 | raw file
  1. // ----------------------------------------------------------------------------------
  2. //
  3. // Copyright Microsoft Corporation
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // ----------------------------------------------------------------------------------
  14. using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkClient;
  15. using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
  16. using Microsoft.Azure.Commands.Resources.Models;
  17. using Microsoft.Azure.Management.Authorization;
  18. using Microsoft.Azure.Management.ResourceManager;
  19. using Microsoft.Azure.Management.ResourceManager.Models;
  20. using Microsoft.Rest.Azure;
  21. using Microsoft.WindowsAzure.Commands.ScenarioTest;
  22. using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
  23. using Moq;
  24. using Newtonsoft.Json;
  25. using System;
  26. using System.Collections;
  27. using System.Collections.Generic;
  28. using System.IO;
  29. using System.Linq;
  30. using System.Net;
  31. using System.Runtime.Serialization.Formatters;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using System.Threading.Tasks;
  35. using Xunit;
  36. namespace Microsoft.Azure.Commands.Resources.Test.Models
  37. {
  38. public class ResourceClientTests : RMTestBase
  39. {
  40. private Mock<IResourceManagementClient> resourceManagementClientMock;
  41. private Mock<IAuthorizationManagementClient> authorizationManagementClientMock;
  42. private Mock<IDeploymentsOperations> deploymentsMock;
  43. private Mock<IResourceGroupsOperations> resourceGroupMock;
  44. private Mock<IResourcesOperations> resourceOperationsMock;
  45. private Mock<IDeploymentOperationsOperations> deploymentOperationsMock;
  46. private Mock<IProvidersOperations> providersMock;
  47. private Mock<Action<string>> progressLoggerMock;
  48. private Mock<Action<string>> errorLoggerMock;
  49. private ResourceManagerSdkClient resourcesClient;
  50. private string resourceGroupName = "myResourceGroup";
  51. private string resourceGroupLocation = "West US";
  52. private string deploymentName = "fooDeployment";
  53. private string templateFile = string.Empty;
  54. private string storageAccountName = "myStorageAccount";
  55. private string requestId = "1234567890";
  56. private string resourceName = "myResource";
  57. private ResourceIdentifier resourceIdentity;
  58. private Dictionary<string, object> properties;
  59. private string serializedProperties;
  60. private int ConfirmActionCounter = 0;
  61. private static GenericResource CreateGenericResource(string location = null, string id = null, string name = null, string type = null)
  62. {
  63. GenericResource resource = new GenericResource();
  64. if (id != null)
  65. {
  66. typeof(Resource).GetProperty("Id").SetValue(resource, id);
  67. }
  68. if (name != null)
  69. {
  70. typeof(Resource).GetProperty("Name").SetValue(resource, name);
  71. }
  72. if (type != null)
  73. {
  74. typeof(Resource).GetProperty("Type").SetValue(resource, type);
  75. }
  76. if (location != null)
  77. {
  78. resource.Location = location;
  79. }
  80. return resource;
  81. }
  82. private static AzureOperationResponse<T> CreateAzureOperationResponse<T>(T type)
  83. {
  84. return new AzureOperationResponse<T>()
  85. {
  86. Body = type
  87. };
  88. }
  89. private void ConfirmAction(bool force, string actionMessage, string processMessage, string target, Action action)
  90. {
  91. ConfirmActionCounter++;
  92. action();
  93. }
  94. private int RejectActionCounter = 0;
  95. private void RejectAction(bool force, string actionMessage, string processMessage, string target, Action action)
  96. {
  97. RejectActionCounter++;
  98. }
  99. private IPage<T> GetPagableType<T>(List<T> collection)
  100. {
  101. var pagableResult = new Page<T>();
  102. pagableResult.SetItemValue<T>(collection);
  103. return pagableResult;
  104. }
  105. private void SetupListForResourceGroupAsync(string name, List<GenericResource> result)
  106. {
  107. resourceOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(
  108. null,
  109. null,
  110. new CancellationToken()))
  111. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<IPage<GenericResource>>()
  112. {
  113. Body = GetPagableType(result)
  114. }));
  115. }
  116. private void SetupListForResourceGroupAsync(string name, IPage<GenericResource> result)
  117. {
  118. resourceOperationsMock.Setup(f => f.ListAsync(
  119. null,
  120. new CancellationToken()))
  121. .Returns(Task.Factory.StartNew(() => result));
  122. }
  123. private void EqualsIgnoreWhitespace(string left, string right)
  124. {
  125. string normalized1 = Regex.Replace(left, @"\s", "");
  126. string normalized2 = Regex.Replace(right, @"\s", "");
  127. Assert.Equal(
  128. normalized1.ToLowerInvariant(),
  129. normalized2.ToLowerInvariant());
  130. }
  131. public ResourceClientTests()
  132. {
  133. resourceManagementClientMock = new Mock<IResourceManagementClient>();
  134. authorizationManagementClientMock = new Mock<IAuthorizationManagementClient>();
  135. deploymentsMock = new Mock<IDeploymentsOperations>();
  136. resourceGroupMock = new Mock<IResourceGroupsOperations>();
  137. resourceOperationsMock = new Mock<IResourcesOperations>();
  138. deploymentOperationsMock = new Mock<IDeploymentOperationsOperations>();
  139. providersMock = new Mock<IProvidersOperations>();
  140. providersMock.Setup(f => f.ListWithHttpMessagesAsync(null, null, new CancellationToken()))
  141. .Returns(Task.Factory.StartNew(() =>
  142. new AzureOperationResponse<IPage<Provider>>()
  143. {
  144. Body = new Page<Provider>()
  145. }));
  146. progressLoggerMock = new Mock<Action<string>>();
  147. errorLoggerMock = new Mock<Action<string>>();
  148. resourceManagementClientMock.Setup(f => f.Deployments).Returns(deploymentsMock.Object);
  149. resourceManagementClientMock.Setup(f => f.ResourceGroups).Returns(resourceGroupMock.Object);
  150. resourceManagementClientMock.Setup(f => f.Resources).Returns(resourceOperationsMock.Object);
  151. resourceManagementClientMock.Setup(f => f.DeploymentOperations).Returns(deploymentOperationsMock.Object);
  152. resourceManagementClientMock.Setup(f => f.Providers).Returns(providersMock.Object);
  153. resourceManagementClientMock.Setup(f => f.ApiVersion).Returns("11-01-2015");
  154. resourcesClient = new ResourceManagerSdkClient(
  155. resourceManagementClientMock.Object)
  156. {
  157. VerboseLogger = progressLoggerMock.Object,
  158. ErrorLogger = errorLoggerMock.Object,
  159. };
  160. resourceIdentity = new ResourceIdentifier
  161. {
  162. ParentResource = "sites/siteA",
  163. ResourceName = "myResource",
  164. ResourceGroupName = "Microsoft.Web", // ResourceProviderNamespace
  165. ResourceType = "sites"
  166. };
  167. properties = new Dictionary<string, object>
  168. {
  169. {"name", "site1"},
  170. {"siteMode", "Standard"},
  171. {"computeMode", "Dedicated"},
  172. {"misc", new Dictionary<string, object>
  173. {
  174. {"key1", "value1"},
  175. {"key2", "value2"}
  176. }}
  177. };
  178. serializedProperties = JsonConvert.SerializeObject(properties, new JsonSerializerSettings
  179. {
  180. TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
  181. TypeNameHandling = TypeNameHandling.None
  182. });
  183. templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\sampleTemplateFile.json");
  184. }
  185. [Fact]
  186. [Trait(Category.AcceptanceType, Category.CheckIn)]
  187. public void NewResourceGroupChecksForPermissionForExistingResource()
  188. {
  189. RejectActionCounter = 0;
  190. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters() { ResourceGroupName = resourceGroupName, ConfirmAction = RejectAction };
  191. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  192. .Returns(Task.Factory.StartNew(() =>
  193. new AzureOperationResponse<bool?>()
  194. {
  195. Body = (bool?)true
  196. }));
  197. resourceGroupMock.Setup(f => f.GetWithHttpMessagesAsync(
  198. parameters.ResourceGroupName,
  199. null,
  200. new CancellationToken()))
  201. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<ResourceGroup>()
  202. {
  203. Body = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
  204. }));
  205. resourceOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(null, null, It.IsAny<CancellationToken>()))
  206. .Returns(() => Task.Factory.StartNew(() =>
  207. {
  208. var resources = new List<GenericResource>()
  209. {
  210. CreateGenericResource(location: "West US", id: null, name: "foo", type: null),
  211. CreateGenericResource(location: "West US", id: null, name: "bar", type: null)
  212. };
  213. var result = new Page<GenericResource>();
  214. result.SetItemValue(resources);
  215. return new AzureOperationResponse<IPage<GenericResource>>() { Body = result };
  216. }));
  217. resourcesClient.CreatePSResourceGroup(parameters);
  218. Assert.Equal(1, RejectActionCounter);
  219. }
  220. [Fact]
  221. [Trait(Category.AcceptanceType, Category.CheckIn)]
  222. public void NewResourceGroupWithoutDeploymentSucceeds()
  223. {
  224. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters()
  225. {
  226. ResourceGroupName = resourceGroupName,
  227. Location = resourceGroupLocation,
  228. ConfirmAction = ConfirmAction
  229. };
  230. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  231. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse((bool?)false)));
  232. resourceGroupMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  233. parameters.ResourceGroupName,
  234. It.IsAny<ResourceGroup>(),
  235. null,
  236. new CancellationToken()))
  237. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location })));
  238. SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResource>());
  239. PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);
  240. Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
  241. Assert.Equal(parameters.Location, result.Location);
  242. }
  243. [Fact]
  244. [Trait(Category.AcceptanceType, Category.CheckIn)]
  245. public void TestTemplateShowsErrorMessage()
  246. {
  247. Uri templateUri = new Uri("http://templateuri.microsoft.com");
  248. Deployment deploymentFromValidate = new Deployment();
  249. PSValidateResourceGroupDeploymentParameters parameters = new PSValidateResourceGroupDeploymentParameters()
  250. {
  251. ResourceGroupName = resourceGroupName,
  252. TemplateFile = templateFile,
  253. };
  254. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  255. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse((bool?)true)));
  256. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<Deployment>(), null, new CancellationToken()))
  257. .Returns(Task.Factory.StartNew(() =>
  258. {
  259. var result = CreateAzureOperationResponse(new DeploymentValidateResult
  260. {
  261. Error = new ResourceManagementErrorWithDetails()
  262. {
  263. Code = "404",
  264. Message = "Awesome error message",
  265. Details = new List<ResourceManagementErrorWithDetails>(new[] { new ResourceManagementErrorWithDetails
  266. {
  267. Code = "SubError",
  268. Message = "Sub error message"
  269. }})
  270. }
  271. });
  272. result.Response = new System.Net.Http.HttpResponseMessage();
  273. result.Response.StatusCode = HttpStatusCode.NotFound;
  274. return result;
  275. }))
  276. .Callback((string rg, string dn, Deployment d, Dictionary<string, List<string>> customHeaders, CancellationToken c) => { deploymentFromValidate = d; });
  277. IEnumerable<PSResourceManagerError> error = resourcesClient.ValidatePSResourceGroupDeployment(parameters, DeploymentMode.Incremental);
  278. Assert.Equal(1, error.Count());
  279. Assert.Equal(1, error.ElementAtOrDefault(0).Details.Count);
  280. }
  281. [Fact]
  282. [Trait(Category.AcceptanceType, Category.CheckIn)]
  283. public void TestTemplateShowsSuccessMessage()
  284. {
  285. Uri templateUri = new Uri("http://templateuri.microsoft.com");
  286. Deployment deploymentFromValidate = new Deployment();
  287. PSValidateResourceGroupDeploymentParameters parameters = new PSValidateResourceGroupDeploymentParameters()
  288. {
  289. ResourceGroupName = resourceGroupName,
  290. TemplateFile = templateFile,
  291. };
  292. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  293. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse((bool?)true)));
  294. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<Deployment>(), null, new CancellationToken()))
  295. .Returns(Task.Factory.StartNew(() =>
  296. {
  297. var result = CreateAzureOperationResponse(new DeploymentValidateResult
  298. {
  299. Error = null
  300. });
  301. result.Response = new System.Net.Http.HttpResponseMessage();
  302. result.Response.StatusCode = HttpStatusCode.OK;
  303. return result;
  304. }))
  305. .Callback((string rg, string dn, Deployment d, Dictionary<string, List<string>> customHeaders, CancellationToken c) => { deploymentFromValidate = d; });
  306. IEnumerable<PSResourceManagerError> error = resourcesClient.ValidatePSResourceGroupDeployment(parameters, DeploymentMode.Incremental);
  307. Assert.Equal(0, error.Count());
  308. progressLoggerMock.Verify(f => f("Template is valid."), Times.Once());
  309. }
  310. [Fact]
  311. public void NewResourceGroupUsesDeploymentNameForDeploymentName()
  312. {
  313. string deploymentName = "abc123";
  314. Deployment deploymentFromGet = new Deployment();
  315. Deployment deploymentFromValidate = new Deployment();
  316. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters()
  317. {
  318. ResourceGroupName = resourceGroupName,
  319. Location = resourceGroupLocation,
  320. DeploymentName = deploymentName,
  321. ConfirmAction = ConfirmAction,
  322. TemplateFile = "http://path/file.html"
  323. };
  324. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(
  325. It.IsAny<string>(),
  326. It.IsAny<string>(),
  327. It.IsAny<Deployment>(),
  328. null,
  329. new CancellationToken()))
  330. .Returns(Task.Factory.StartNew(() =>
  331. new AzureOperationResponse<DeploymentValidateResult>()
  332. {
  333. Body = new DeploymentValidateResult
  334. {
  335. }
  336. }))
  337. .Callback((string rg, string dn, Deployment d, Dictionary<string, List<string>> customHeaders, CancellationToken c) => { deploymentFromValidate = d; });
  338. deploymentsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  339. It.IsAny<string>(),
  340. It.IsAny<string>(),
  341. It.IsAny<Deployment>(),
  342. null,
  343. new CancellationToken()))
  344. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>()
  345. {
  346. Body = new DeploymentExtended
  347. {
  348. Id = requestId
  349. }
  350. }))
  351. .Callback((string name, string dName, Deployment bDeploy, Dictionary<string, List<string>> customHeaders, CancellationToken token) =>
  352. { deploymentFromGet = bDeploy; deploymentName = dName; });
  353. SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResource>
  354. {
  355. CreateGenericResource(null, null, "website")
  356. });
  357. var operationId = Guid.NewGuid().ToString();
  358. var operationQueue = new Queue<DeploymentOperation>();
  359. operationQueue.Enqueue(
  360. new DeploymentOperation()
  361. {
  362. OperationId = operationId,
  363. Properties = new DeploymentOperationProperties()
  364. {
  365. ProvisioningState = "Accepted",
  366. TargetResource = new TargetResource()
  367. {
  368. ResourceType = "Microsoft.Website",
  369. ResourceName = resourceName
  370. }
  371. }
  372. }
  373. );
  374. operationQueue.Enqueue(
  375. new DeploymentOperation()
  376. {
  377. OperationId = operationId,
  378. Properties = new DeploymentOperationProperties()
  379. {
  380. ProvisioningState = "Running",
  381. TargetResource = new TargetResource()
  382. {
  383. ResourceType = "Microsoft.Website",
  384. ResourceName = resourceName
  385. }
  386. }
  387. }
  388. );
  389. operationQueue.Enqueue(
  390. new DeploymentOperation()
  391. {
  392. OperationId = operationId,
  393. Properties = new DeploymentOperationProperties()
  394. {
  395. ProvisioningState = "Succeeded",
  396. TargetResource = new TargetResource()
  397. {
  398. ResourceType = "Microsoft.Website",
  399. ResourceName = resourceName
  400. }
  401. }
  402. }
  403. );
  404. deploymentOperationsMock.SetupSequence(f => f.ListWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), null, null, new CancellationToken()))
  405. .Returns(Task.Factory.StartNew(() =>
  406. new AzureOperationResponse<IPage<DeploymentOperation>>()
  407. {
  408. Body = GetPagableType(
  409. new List<DeploymentOperation>()
  410. {
  411. operationQueue.Dequeue()
  412. })
  413. }))
  414. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<IPage<DeploymentOperation>>()
  415. {
  416. Body = GetPagableType(
  417. new List<DeploymentOperation>()
  418. {
  419. operationQueue.Dequeue()
  420. })
  421. }))
  422. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<IPage<DeploymentOperation>>()
  423. {
  424. Body = GetPagableType(
  425. new List<DeploymentOperation>()
  426. {
  427. operationQueue.Dequeue()
  428. })
  429. }));
  430. var deploymentQueue = new Queue<DeploymentExtended>();
  431. deploymentQueue.Enqueue(new DeploymentExtended()
  432. {
  433. Name = deploymentName,
  434. Properties = new DeploymentPropertiesExtended()
  435. {
  436. Mode = DeploymentMode.Incremental,
  437. CorrelationId = "123",
  438. ProvisioningState = "Accepted"
  439. }
  440. });
  441. deploymentQueue.Enqueue(new DeploymentExtended
  442. {
  443. Name = deploymentName,
  444. Properties = new DeploymentPropertiesExtended()
  445. {
  446. Mode = DeploymentMode.Incremental,
  447. CorrelationId = "123",
  448. ProvisioningState = "Running"
  449. }
  450. });
  451. deploymentQueue.Enqueue(new DeploymentExtended
  452. {
  453. Name = deploymentName,
  454. Properties = new DeploymentPropertiesExtended()
  455. {
  456. Mode = DeploymentMode.Incremental,
  457. CorrelationId = "123",
  458. ProvisioningState = "Succeeded"
  459. }
  460. });
  461. deploymentsMock.SetupSequence(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), null, new CancellationToken()))
  462. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>() { Body = deploymentQueue.Dequeue() }))
  463. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>() { Body = deploymentQueue.Dequeue() }))
  464. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>() { Body = deploymentQueue.Dequeue() }));
  465. Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroupDeployment result = resourcesClient.ExecuteDeployment(parameters);
  466. Assert.Equal(deploymentName, deploymentName);
  467. Assert.Equal("Succeeded", result.ProvisioningState);
  468. progressLoggerMock.Verify(
  469. f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, "Accepted".ToLower())),
  470. Times.Once());
  471. progressLoggerMock.Verify(
  472. f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, "Running".ToLower())),
  473. Times.Once());
  474. progressLoggerMock.Verify(
  475. f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, "Succeeded".ToLower())),
  476. Times.Once());
  477. }
  478. [Fact]
  479. [Trait(Category.AcceptanceType, Category.CheckIn)]
  480. public void NewResourceGroupWithDeploymentSucceeds()
  481. {
  482. Uri templateUri = new Uri("http://templateuri.microsoft.com");
  483. Deployment deploymentFromGet = new Deployment();
  484. Deployment deploymentFromValidate = new Deployment();
  485. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters()
  486. {
  487. ResourceGroupName = resourceGroupName,
  488. Location = resourceGroupLocation,
  489. DeploymentName = deploymentName,
  490. TemplateFile = templateFile,
  491. ConfirmAction = ConfirmAction
  492. };
  493. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  494. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<bool?>() { Body = (bool?)false }));
  495. resourceGroupMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  496. parameters.ResourceGroupName,
  497. It.IsAny<ResourceGroup>(),
  498. null,
  499. new CancellationToken()))
  500. .Returns(Task.Factory.StartNew(() =>
  501. new AzureOperationResponse<ResourceGroup>()
  502. {
  503. Body = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
  504. }));
  505. resourceGroupMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, null, new CancellationToken()))
  506. .Returns(Task.Factory.StartNew(() =>
  507. new AzureOperationResponse<ResourceGroup>()
  508. {
  509. Body = new ResourceGroup() { Location = resourceGroupLocation }
  510. }));
  511. deploymentsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, It.IsAny<Deployment>(), null, new CancellationToken()))
  512. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>()
  513. {
  514. Body = new DeploymentExtended
  515. {
  516. Id = requestId
  517. }
  518. }))
  519. .Callback((string name, string dName, Deployment bDeploy, Dictionary<string, List<string>> customHeaders, CancellationToken token) =>
  520. { deploymentFromGet = bDeploy; });
  521. deploymentsMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
  522. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>()
  523. {
  524. Body = new DeploymentExtended()
  525. {
  526. Name = deploymentName,
  527. Properties = new DeploymentPropertiesExtended()
  528. {
  529. Mode = DeploymentMode.Incremental,
  530. CorrelationId = "123",
  531. ProvisioningState = "Succeeded"
  532. },
  533. }
  534. }
  535. ));
  536. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<Deployment>(), null, new CancellationToken()))
  537. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new DeploymentValidateResult
  538. {
  539. })))
  540. .Callback((string rg, string dn, Deployment d, Dictionary<string, List<string>> customHeaders, CancellationToken c) => { deploymentFromValidate = d; });
  541. SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResource>() { CreateGenericResource(null, null, "website") });
  542. deploymentOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(resourceGroupName, deploymentName, null, null, new CancellationToken()))
  543. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(GetPagableType(new List<DeploymentOperation>()
  544. {
  545. new DeploymentOperation()
  546. {
  547. OperationId = Guid.NewGuid().ToString(),
  548. Properties = new DeploymentOperationProperties()
  549. {
  550. ProvisioningState = "Succeeded",
  551. TargetResource = new TargetResource()
  552. {
  553. ResourceType = "Microsoft.Website",
  554. ResourceName = resourceName
  555. }
  556. }
  557. }
  558. }))));
  559. PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);
  560. Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroupDeployment deploymentResult = resourcesClient.ExecuteDeployment(parameters);
  561. deploymentsMock.Verify((f => f.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, deploymentFromGet, null, new CancellationToken())), Times.Once());
  562. Assert.Equal(parameters.ResourceGroupName, deploymentResult.ResourceGroupName);
  563. Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Properties.Mode);
  564. Assert.NotNull(deploymentFromGet.Properties.Template);
  565. progressLoggerMock.Verify(
  566. f => f(string.Format("Resource {0} '{1}' provisioning status is {2}",
  567. "Microsoft.Website",
  568. resourceName,
  569. "Succeeded".ToLower())),
  570. Times.Once());
  571. }
  572. [Fact(Skip = "TODO: Fix the test to fit the new client post migration")]
  573. [Trait(Category.AcceptanceType, Category.CheckIn)]
  574. public void ShowsFailureErrorWhenResourceGroupWithDeploymentFails()
  575. {
  576. Uri templateUri = new Uri("http://templateuri.microsoft.com");
  577. Deployment deploymentFromGet = new Deployment();
  578. Deployment deploymentFromValidate = new Deployment();
  579. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters()
  580. {
  581. ResourceGroupName = resourceGroupName,
  582. Location = resourceGroupLocation,
  583. DeploymentName = deploymentName,
  584. TemplateFile = templateFile,
  585. ConfirmAction = ConfirmAction
  586. };
  587. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  588. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse((bool?)false)));
  589. resourceGroupMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  590. parameters.ResourceGroupName,
  591. It.IsAny<ResourceGroup>(),
  592. null,
  593. new CancellationToken()))
  594. .Returns(Task.Factory.StartNew(() =>
  595. CreateAzureOperationResponse(new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location })
  596. ));
  597. resourceGroupMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, null, new CancellationToken()))
  598. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new ResourceGroup() { Location = resourceGroupLocation })
  599. ));
  600. deploymentsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, It.IsAny<Deployment>(), null, new CancellationToken()))
  601. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new DeploymentExtended
  602. {
  603. Id = requestId
  604. })))
  605. .Callback((string name, string dName, Deployment bDeploy, Dictionary<string, List<string>> customHeaders, CancellationToken token) => { deploymentFromGet = bDeploy; });
  606. deploymentsMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
  607. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new DeploymentExtended()
  608. {
  609. Name = deploymentName,
  610. Properties = new DeploymentPropertiesExtended()
  611. {
  612. Mode = DeploymentMode.Incremental,
  613. ProvisioningState = "Succeeded"
  614. },
  615. })
  616. ));
  617. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<Deployment>(), null, new CancellationToken()))
  618. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse(new DeploymentValidateResult
  619. {
  620. Error = new ResourceManagementErrorWithDetails()
  621. })))
  622. .Callback((string resourceGroup, string deployment, Deployment d, Dictionary<string, List<string>> customHeaders, CancellationToken c) => { deploymentFromValidate = d; });
  623. SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResource>() {
  624. CreateGenericResource(null, null, "website") });
  625. var listOperations = new List<DeploymentOperation>() {
  626. new DeploymentOperation()
  627. {
  628. OperationId = Guid.NewGuid().ToString(),
  629. Properties = new DeploymentOperationProperties()
  630. {
  631. ProvisioningState = "Failed",
  632. StatusMessage = "{\"Code\":\"Conflict\"}",
  633. TargetResource = new TargetResource()
  634. {
  635. ResourceType = "Microsoft.Website",
  636. ResourceName = resourceName
  637. }
  638. }
  639. }
  640. };
  641. var pageableOperations = new Page<DeploymentOperation>();
  642. pageableOperations.SetItemValue(listOperations);
  643. deploymentOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(resourceGroupName, deploymentName, null, null, new CancellationToken()))
  644. .Returns(Task.Factory.StartNew(() => CreateAzureOperationResponse((IPage<DeploymentOperation>)pageableOperations)));
  645. PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);
  646. deploymentsMock.Verify((f => f.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, deploymentFromGet, null, new CancellationToken())), Times.Once());
  647. Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
  648. Assert.Equal(parameters.Location, result.Location);
  649. Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Properties.Mode);
  650. Assert.NotNull(deploymentFromGet.Properties.Template);
  651. errorLoggerMock.Verify(
  652. f => f(string.Format("Resource {0} '{1}' failed with message '{2}'",
  653. "Microsoft.Website",
  654. resourceName,
  655. "{\"Code\":\"Conflict\"}")),
  656. Times.Once());
  657. }
  658. [Fact(Skip = "TODO: Fix the test to fit the new client post migration")]
  659. [Trait(Category.AcceptanceType, Category.CheckIn)]
  660. public void ExtractsErrorMessageFromFailedDeploymentOperation()
  661. {
  662. Uri templateUri = new Uri("http://templateuri.microsoft.com");
  663. Deployment deploymentFromGet = new Deployment();
  664. Deployment deploymentFromValidate = new Deployment();
  665. PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters()
  666. {
  667. ResourceGroupName = resourceGroupName,
  668. Location = resourceGroupLocation,
  669. DeploymentName = deploymentName,
  670. TemplateFile = templateFile,
  671. ConfirmAction = ConfirmAction
  672. };
  673. resourceGroupMock.Setup(f => f.CheckExistenceWithHttpMessagesAsync(parameters.ResourceGroupName, null, new CancellationToken()))
  674. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<bool?>()
  675. {
  676. Body = (bool?)false
  677. }));
  678. resourceGroupMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  679. parameters.ResourceGroupName,
  680. It.IsAny<ResourceGroup>(),
  681. null,
  682. new CancellationToken()))
  683. .Returns(Task.Factory.StartNew(() =>
  684. new AzureOperationResponse<ResourceGroup>()
  685. {
  686. Body = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
  687. }
  688. ));
  689. resourceGroupMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, null, new CancellationToken()))
  690. .Returns(Task.Factory.StartNew(() =>
  691. new AzureOperationResponse<ResourceGroup>() { Body = new ResourceGroup() { Location = resourceGroupLocation } }
  692. ));
  693. deploymentsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
  694. resourceGroupName,
  695. deploymentName,
  696. It.IsAny<Deployment>(),
  697. null,
  698. new CancellationToken()))
  699. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<DeploymentExtended>()
  700. {
  701. Body = new DeploymentExtended
  702. {
  703. Id = requestId
  704. }
  705. }))
  706. .Callback((string name, string dName, Deployment bDeploy, Dictionary<string, List<string>> customHeaders,
  707. CancellationToken token) => { deploymentFromGet = bDeploy; });
  708. deploymentsMock.Setup(f => f.GetWithHttpMessagesAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
  709. .Returns(Task.Factory.StartNew(() =>
  710. new AzureOperationResponse<DeploymentExtended>()
  711. {
  712. Body = new DeploymentExtended()
  713. {
  714. Name = deploymentName,
  715. Properties = new DeploymentPropertiesExtended()
  716. {
  717. Mode = DeploymentMode.Incremental,
  718. ProvisioningState = "Succeeded"
  719. }
  720. }
  721. }
  722. ));
  723. deploymentsMock.Setup(f => f.ValidateWithHttpMessagesAsync(
  724. resourceGroupName,
  725. It.IsAny<string>(),
  726. It.IsAny<Deployment>(),
  727. null,
  728. new CancellationToken()))
  729. .Returns(Task.Factory.StartNew(() =>
  730. new AzureOperationResponse<DeploymentValidateResult>()
  731. {
  732. Body = new DeploymentValidateResult
  733. {
  734. Error = new ResourceManagementErrorWithDetails()
  735. }
  736. }
  737. ))
  738. .Callback((string rg, string dn, Deployment d, Dictionary<string, List<string>> customHeaders,
  739. CancellationToken c) => { deploymentFromValidate = d; });
  740. SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResource>() {
  741. CreateGenericResource(location: null, id: null, name: "website", type: null)});
  742. var listOperations = new List<DeploymentOperation>() {
  743. new DeploymentOperation()
  744. {
  745. OperationId = Guid.NewGuid().ToString(),
  746. Properties = new DeploymentOperationProperties()
  747. {
  748. ProvisioningState = "Failed",
  749. StatusMessage = JsonConvert.SerializeObject(new ResourceManagementErrorWithDetails()
  750. {
  751. Message = "A really bad error occured"
  752. }),
  753. TargetResource = new TargetResource()
  754. {
  755. ResourceType = "Microsoft.Website",
  756. ResourceName = resourceName
  757. }
  758. }
  759. }
  760. };
  761. deploymentOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(
  762. resourceGroupName,
  763. deploymentName,
  764. null,
  765. null,
  766. new CancellationToken()))
  767. .Returns(Task.Factory.StartNew(() =>
  768. new AzureOperationResponse<IPage<DeploymentOperation>>()
  769. {
  770. Body = GetPagableType<DeploymentOperation>(listOperations)
  771. }
  772. ));
  773. PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);
  774. Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroupDeployment deploymentResult = resourcesClient.ExecuteDeployment(parameters);
  775. deploymentsMock.Verify((f => f.CreateOrUpdateWithHttpMessagesAsync(
  776. resourceGroupName,
  777. deploymentName,
  778. deploymentFromGet,
  779. null,
  780. new CancellationToken())),
  781. Times.Never);
  782. Assert.Equal(parameters.ResourceGroupName, deploymentResult.ResourceGroupName);
  783. Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Properties.Mode);
  784. Assert.NotNull(deploymentFromGet.Properties.Template);
  785. errorLoggerMock.Verify(
  786. f => f("A really bad error occured"),
  787. Times.Once());
  788. }
  789. [Fact]
  790. [Trait(Category.AcceptanceType, Category.CheckIn)]
  791. public void GetsSpecificResourceGroup()
  792. {
  793. string name = resourceGroupName;
  794. GenericResource resource1 = CreateGenericResource(
  795. resourceGroupLocation,
  796. "/subscriptions/abc123/resourceGroups/group1/providers/Microsoft.Test/servers/r12345sql/db/r45678db",
  797. resourceName);
  798. GenericResource resource2 = CreateGenericResource(
  799. resourceGroupLocation,
  800. "/subscriptions/abc123/resourceGroups/group1/providers/Microsoft.Test/servers/r12345sql/db/r45678db",
  801. resourceName + "2");
  802. ResourceGroup resourceGroup = new ResourceGroup()
  803. {
  804. Name = name,
  805. Location = resourceGroupLocation,
  806. Properties = new ResourceGroupProperties("Succeeded")
  807. };
  808. resourceGroupMock.Setup(f => f.GetWithHttpMessagesAsync(name, null, new CancellationToken()))
  809. .Returns(Task.Factory.StartNew(() =>
  810. new AzureOperationResponse<ResourceGroup>()
  811. {
  812. Body = resourceGroup
  813. }));
  814. SetupListForResourceGroupAsync(name, new List<GenericResource>() { resource1, resource2 });
  815. List<PSResourceGroup> actual = resourcesClient.FilterResourceGroups(name, null, true);
  816. Assert.Equal(1, actual.Count);
  817. Assert.Equal(name, actual[0].ResourceGroupName);
  818. Assert.Equal(resourceGroupLocation, actual[0].Location);
  819. Assert.Equal("Succeeded", actual[0].ProvisioningState);
  820. }
  821. [Fact]
  822. [Trait(Category.AcceptanceType, Category.CheckIn)]
  823. public void GetsAllResourceGroups()
  824. {
  825. ResourceGroup resourceGroup1 = new ResourceGroup() { Name = resourceGroupName + 1, Location = resourceGroupLocation };
  826. ResourceGroup resourceGroup2 = new ResourceGroup() { Name = resourceGroupName + 2, Location = resourceGroupLocation };
  827. ResourceGroup resourceGroup3 = new ResourceGroup() { Name = resourceGroupName + 3, Location = resourceGroupLocation };
  828. ResourceGroup resourceGroup4 = new ResourceGroup() { Name = resourceGroupName + 4, Location = resourceGroupLocation };
  829. var listResult = new List<ResourceGroup>() { resourceGroup1, resourceGroup2, resourceGroup3, resourceGroup4 };
  830. var pagableResult = new Page<ResourceGroup>();
  831. pagableResult.SetItemValue(listResult);
  832. resourceGroupMock.Setup(f => f.ListWithHttpMessagesAsync(null, null, new CancellationToken()))
  833. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<IPage<ResourceGroup>>()
  834. {
  835. Body = pagableResult
  836. }));
  837. SetupListForResourceGroupAsync(resourceGroup1.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  838. SetupListForResourceGroupAsync(resourceGroup2.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  839. SetupListForResourceGroupAsync(resourceGroup3.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  840. SetupListForResourceGroupAsync(resourceGroup4.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  841. List<PSResourceGroup> actual = resourcesClient.FilterResourceGroups(null, null, false);
  842. Assert.Equal(4, actual.Count);
  843. Assert.Equal(resourceGroup1.Name, actual[0].ResourceGroupName);
  844. Assert.Equal(resourceGroup2.Name, actual[1].ResourceGroupName);
  845. Assert.Equal(resourceGroup3.Name, actual[2].ResourceGroupName);
  846. Assert.Equal(resourceGroup4.Name, actual[3].ResourceGroupName);
  847. }
  848. [Fact]
  849. [Trait(Category.AcceptanceType, Category.CheckIn)]
  850. public void GetsAllResourceGroupsWithDetails()
  851. {
  852. ResourceGroup resourceGroup1 = new ResourceGroup() { Name = resourceGroupName + 1, Location = resourceGroupLocation };
  853. ResourceGroup resourceGroup2 = new ResourceGroup() { Name = resourceGroupName + 2, Location = resourceGroupLocation };
  854. ResourceGroup resourceGroup3 = new ResourceGroup() { Name = resourceGroupName + 3, Location = resourceGroupLocation };
  855. ResourceGroup resourceGroup4 = new ResourceGroup() { Name = resourceGroupName + 4, Location = resourceGroupLocation };
  856. var listResult = new List<ResourceGroup>() { resourceGroup1, resourceGroup2, resourceGroup3, resourceGroup4 };
  857. var pagableResult = new Page<ResourceGroup>();
  858. pagableResult.SetItemValue(listResult);
  859. resourceGroupMock.Setup(f => f.ListWithHttpMessagesAsync(null, null, new CancellationToken()))
  860. .Returns(Task.Factory.StartNew(() => new AzureOperationResponse<IPage<ResourceGroup>>()
  861. {
  862. Body = pagableResult
  863. }));
  864. SetupListForResourceGroupAsync(resourceGroup1.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  865. SetupListForResourceGroupAsync(resourceGroup2.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  866. SetupListForResourceGroupAsync(resourceGroup3.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  867. SetupListForResourceGroupAsync(resourceGroup4.Name, new List<GenericResource>() { CreateGenericResource(null, null, "resource") });
  868. List<PSResourceGroup> actual = resourcesClient.FilterResourceGroups(null, null, true);
  869. Assert.Equal(4, actual.Count);
  870. Assert.Equal(resourceGroup1.Name, actual[0].ResourceGroupName);
  871. Assert.Equal(resourceGroup2.Name, actual[1].ResourceGroupName);
  872. Assert.Equal(resourceGroup3.Name, actual[2].ResourceGroupName);
  873. Assert.Equal(resourceGroup4.Name, actual[3].ResourceGroupName);
  874. }
  875. [Fact]
  876. [Trait(Category.AcceptanceType, Category.CheckIn)]
  877. public void GetsResourceGroupsFilteredByTags()
  878. {
  879. Dictionary<string, string> tag1 = new Dictionary<string, string> { { "tag1", "val1" }, { "tag2", "val2" } };
  880. Dictionary<string, string> tag2 = new Dictionary<string, string> { { "tag1", "valx" } };
  881. Dictionary<string, string> tag3 = new Dictionary<string, str