PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ResourceManager/Profile/Commands.Profile.Test/AzureRMProfileTests.cs

https://gitlab.com/jslee1/azure-powershell
C# | 495 lines | 435 code | 45 blank | 15 comment | 2 complexity | 9781814e14155d445ca3426b66301b69 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 Hyak.Common;
  15. using Microsoft.Azure.Commands.Common.Authentication;
  16. using Microsoft.Azure.Commands.Common.Authentication.Models;
  17. using Microsoft.Azure.Commands.Profile;
  18. using Microsoft.Azure.Commands.Profile.Models;
  19. using Microsoft.Azure.ServiceManagemenet.Common.Models;
  20. using Microsoft.Azure.Subscriptions.Models;
  21. using Microsoft.IdentityModel.Clients.ActiveDirectory;
  22. using Microsoft.WindowsAzure.Commands.Common;
  23. using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
  24. using Microsoft.WindowsAzure.Commands.ScenarioTest;
  25. using Microsoft.WindowsAzure.Commands.Utilities.Common;
  26. using System;
  27. using System.Collections.Concurrent;
  28. using System.Collections.Generic;
  29. using System.Linq;
  30. using System.Management.Automation;
  31. using System.Threading.Tasks;
  32. using Xunit;
  33. using Xunit.Abstractions;
  34. namespace Microsoft.Azure.Commands.ResourceManager.Common.Test
  35. {
  36. public class AzureRMProfileTests
  37. {
  38. private const string DefaultAccount = "admin@contoso.com";
  39. private static Guid DefaultSubscription = Guid.NewGuid();
  40. private static string DefaultSubscriptionName = "Contoso Subscription";
  41. private static string DefaultDomain = "contoso.com";
  42. private static Guid DefaultTenant = Guid.NewGuid();
  43. private static AzureContext Context;
  44. private static RMProfileClient SetupTestEnvironment(List<string> tenants, params List<string>[] subscriptionLists)
  45. {
  46. AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(DefaultAccount,
  47. Guid.NewGuid().ToString(), DefaultTenant.ToString());
  48. var subscriptionList = new Queue<List<string>>(subscriptionLists);
  49. var clientFactory = new MockSubscriptionClientFactory(tenants, subscriptionList);
  50. var mock = new MockClientFactory(new List<object>
  51. {
  52. clientFactory.GetSubscriptionClient()
  53. }, true);
  54. mock.MoqClients = true;
  55. AzureSession.ClientFactory = mock;
  56. Context = new AzureContext(new AzureSubscription()
  57. {
  58. Account = DefaultAccount,
  59. Environment = EnvironmentName.AzureCloud,
  60. Id = DefaultSubscription,
  61. Name = DefaultSubscriptionName
  62. },
  63. new AzureAccount() { Id = DefaultAccount, Type = AzureAccount.AccountType.User },
  64. AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
  65. new AzureTenant() { Domain = DefaultDomain, Id = DefaultTenant });
  66. var profile = new AzureRMProfile();
  67. profile.Context = Context;
  68. return new RMProfileClient(profile);
  69. }
  70. public AzureRMProfileTests(ITestOutputHelper output)
  71. {
  72. XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
  73. }
  74. [Fact]
  75. [Trait(Category.AcceptanceType, Category.CheckIn)]
  76. public void SpecifyTenantAndSubscriptionIdSucceed()
  77. {
  78. var tenants = new List<string> { DefaultTenant.ToString() };
  79. var firstList = new List<string> { DefaultSubscription.ToString(), Guid.NewGuid().ToString() };
  80. var secondList = new List<string> { Guid.NewGuid().ToString() };
  81. var client = SetupTestEnvironment(tenants, firstList, secondList);
  82. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  83. new MockAccessToken
  84. {
  85. UserId = "aaa@contoso.com",
  86. LoginType = LoginType.OrgId,
  87. AccessToken = "bbb",
  88. TenantId = DefaultTenant.ToString()
  89. };
  90. var azureRmProfile = client.Login(
  91. Context.Account,
  92. Context.Environment,
  93. DefaultTenant.ToString(),
  94. DefaultSubscription.ToString(),
  95. null,
  96. null);
  97. }
  98. [Fact]
  99. [Trait(Category.AcceptanceType, Category.CheckIn)]
  100. public void SubscriptionIdNotExist()
  101. {
  102. var tenants = new List<string> { DefaultTenant.ToString() };
  103. var firstList = new List<string> { Guid.NewGuid().ToString() };
  104. var client = SetupTestEnvironment(tenants, firstList);
  105. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  106. new MockAccessToken
  107. {
  108. UserId = "aaa@contoso.com",
  109. LoginType = LoginType.OrgId,
  110. AccessToken = "bbb",
  111. TenantId = DefaultTenant.ToString()
  112. };
  113. var getAsyncResponses = new Queue<Func<GetSubscriptionResult>>();
  114. getAsyncResponses.Enqueue(() =>
  115. {
  116. throw new CloudException("InvalidAuthenticationTokenTenant: The access token is from the wrong issuer");
  117. });
  118. MockSubscriptionClientFactory.SetGetAsyncResponses(getAsyncResponses);
  119. Assert.Throws<PSInvalidOperationException>(() => client.Login(
  120. Context.Account,
  121. Context.Environment,
  122. null,
  123. DefaultSubscription.ToString(),
  124. null,
  125. null));
  126. }
  127. [Fact]
  128. [Trait(Category.AcceptanceType, Category.CheckIn)]
  129. public void SpecifyTenantAndNotExistingSubscriptionId()
  130. {
  131. var tenants = new List<string> { DefaultTenant.ToString() };
  132. var firstList = new List<string> { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() };
  133. var secondList = new List<string> { Guid.NewGuid().ToString() };
  134. var client = SetupTestEnvironment(tenants, firstList, secondList);
  135. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  136. new MockAccessToken
  137. {
  138. UserId = "aaa@contoso.com",
  139. LoginType = LoginType.OrgId,
  140. AccessToken = "bbb",
  141. TenantId = DefaultTenant.ToString()
  142. };
  143. Assert.Throws<PSInvalidOperationException>(() => client.Login(
  144. Context.Account,
  145. Context.Environment,
  146. DefaultTenant.ToString(),
  147. DefaultSubscription.ToString(),
  148. null,
  149. null));
  150. }
  151. [Fact]
  152. [Trait(Category.AcceptanceType, Category.CheckIn)]
  153. public void SubscriptionIdNotInFirstTenant()
  154. {
  155. var tenants = new List<string> { DefaultTenant.ToString(), Guid.NewGuid().ToString() };
  156. var subscriptionInSecondTenant = Guid.NewGuid().ToString();
  157. var firstList = new List<string> { DefaultSubscription.ToString() };
  158. var secondList = new List<string> { Guid.NewGuid().ToString(), subscriptionInSecondTenant };
  159. var client = SetupTestEnvironment(tenants, firstList, secondList);
  160. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  161. new MockAccessToken
  162. {
  163. UserId = "aaa@contoso.com",
  164. LoginType = LoginType.OrgId,
  165. AccessToken = "bbb",
  166. TenantId = DefaultTenant.ToString()
  167. };
  168. var getAsyncResponses = new Queue<Func<GetSubscriptionResult>>();
  169. getAsyncResponses.Enqueue(() =>
  170. {
  171. throw new CloudException("InvalidAuthenticationTokenTenant: The access token is from the wrong issuer");
  172. });
  173. MockSubscriptionClientFactory.SetGetAsyncResponses(getAsyncResponses);
  174. var azureRmProfile = client.Login(
  175. Context.Account,
  176. Context.Environment,
  177. null,
  178. subscriptionInSecondTenant,
  179. null,
  180. null);
  181. }
  182. [Fact]
  183. [Trait(Category.AcceptanceType, Category.CheckIn)]
  184. public void SubscriptionNameNotInFirstTenant()
  185. {
  186. var tenants = new List<string> { DefaultTenant.ToString(), Guid.NewGuid().ToString() };
  187. var subscriptionInSecondTenant = Guid.NewGuid().ToString();
  188. var firstList = new List<string> { DefaultSubscription.ToString() };
  189. var secondList = new List<string> { Guid.NewGuid().ToString(), subscriptionInSecondTenant };
  190. var client = SetupTestEnvironment(tenants, firstList, secondList);
  191. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  192. new MockAccessToken
  193. {
  194. UserId = "aaa@contoso.com",
  195. LoginType = LoginType.OrgId,
  196. AccessToken = "bbb",
  197. TenantId = DefaultTenant.ToString()
  198. };
  199. var listAsyncResponses = new Queue<Func<SubscriptionListResult>>();
  200. listAsyncResponses.Enqueue(() =>
  201. {
  202. var sub1 = new Subscription
  203. {
  204. Id = DefaultSubscription.ToString(),
  205. SubscriptionId = DefaultSubscription.ToString(),
  206. DisplayName = DefaultSubscriptionName,
  207. State = "enabled"
  208. };
  209. var sub2 = new Subscription
  210. {
  211. Id = subscriptionInSecondTenant,
  212. SubscriptionId = subscriptionInSecondTenant,
  213. DisplayName = MockSubscriptionClientFactory.GetSubscriptionNameFromId(subscriptionInSecondTenant),
  214. State = "enabled"
  215. };
  216. return new SubscriptionListResult
  217. {
  218. Subscriptions = new List<Subscription> { sub1, sub2 }
  219. };
  220. });
  221. MockSubscriptionClientFactory.SetListAsyncResponses(listAsyncResponses);
  222. var azureRmProfile = client.Login(
  223. Context.Account,
  224. Context.Environment,
  225. null,
  226. null,
  227. MockSubscriptionClientFactory.GetSubscriptionNameFromId(subscriptionInSecondTenant),
  228. null);
  229. }
  230. [Fact]
  231. [Trait(Category.AcceptanceType, Category.CheckIn)]
  232. public void TokenIdAndAccountIdMismatch()
  233. {
  234. var tenants = new List<string> { Guid.NewGuid().ToString(), DefaultTenant.ToString() };
  235. var secondsubscriptionInTheFirstTenant = Guid.NewGuid().ToString();
  236. var firstList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  237. var secondList = new List<string> { Guid.NewGuid().ToString() };
  238. var thirdList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  239. var fourthList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  240. var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList, fourthList);
  241. var tokens = new Queue<MockAccessToken>();
  242. tokens.Enqueue(new MockAccessToken
  243. {
  244. UserId = "aaa@contoso.com",
  245. LoginType = LoginType.OrgId,
  246. AccessToken = "bbb"
  247. });
  248. tokens.Enqueue(new MockAccessToken
  249. {
  250. UserId = "bbb@contoso.com",
  251. LoginType = LoginType.OrgId,
  252. AccessToken = "bbb",
  253. TenantId = tenants.First()
  254. });
  255. tokens.Enqueue(new MockAccessToken
  256. {
  257. UserId = "ccc@notcontoso.com",
  258. LoginType = LoginType.OrgId,
  259. AccessToken = "bbb",
  260. TenantId = tenants.Last()
  261. });
  262. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  263. {
  264. var token = tokens.Dequeue();
  265. account.Id = token.UserId;
  266. return token;
  267. };
  268. var azureRmProfile = client.Login(
  269. Context.Account,
  270. Context.Environment,
  271. null,
  272. secondsubscriptionInTheFirstTenant,
  273. null,
  274. null);
  275. var tenantsInAccount = azureRmProfile.Context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants);
  276. Assert.Equal(1, tenantsInAccount.Length);
  277. Assert.Equal(tenants.First(), tenantsInAccount[0]);
  278. }
  279. [Fact]
  280. [Trait(Category.AcceptanceType, Category.CheckIn)]
  281. public void AdalExceptionsArePropagatedToCaller()
  282. {
  283. var tenants = new List<string> { Guid.NewGuid().ToString(), DefaultTenant.ToString() };
  284. var secondsubscriptionInTheFirstTenant = Guid.NewGuid().ToString();
  285. var firstList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  286. var secondList = new List<string> { Guid.NewGuid().ToString() };
  287. var thirdList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  288. var fourthList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  289. var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList, fourthList);
  290. var tokens = new Queue<MockAccessToken>();
  291. tokens.Enqueue(new MockAccessToken
  292. {
  293. UserId = "aaa@contoso.com",
  294. LoginType = LoginType.OrgId,
  295. AccessToken = "bbb"
  296. });
  297. ((MockTokenAuthenticationFactory)AzureSession.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
  298. {
  299. throw new AadAuthenticationCanceledException("Login window was closed", null);
  300. };
  301. Assert.Throws<AadAuthenticationCanceledException>(() => client.Login(
  302. Context.Account,
  303. Context.Environment,
  304. null,
  305. secondsubscriptionInTheFirstTenant,
  306. null,
  307. null));
  308. }
  309. [Fact]
  310. [Trait(Category.AcceptanceType, Category.CheckIn)]
  311. public void MultipleTenantsAndSubscriptionsSucceed()
  312. {
  313. var tenants = new List<string> { Guid.NewGuid().ToString(), DefaultTenant.ToString() };
  314. var secondsubscriptionInTheFirstTenant = Guid.NewGuid().ToString();
  315. var firstList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  316. var secondList = new List<string> { Guid.NewGuid().ToString() };
  317. var thirdList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  318. var fourthList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  319. var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList, fourthList);
  320. var subResults = new List<AzureSubscription>(client.ListSubscriptions());
  321. Assert.Equal(3, subResults.Count);
  322. var tenantResults = client.ListTenants();
  323. Assert.Equal(2, tenantResults.Count());
  324. tenantResults = client.ListTenants(DefaultTenant.ToString());
  325. Assert.Equal(1, tenantResults.Count());
  326. AzureSubscription subValue;
  327. Assert.True(client.TryGetSubscriptionById(DefaultTenant.ToString(), DefaultSubscription.ToString(), out subValue));
  328. Assert.Equal(DefaultSubscription.ToString(), subValue.Id.ToString());
  329. Assert.True(client.TryGetSubscriptionByName(DefaultTenant.ToString(),
  330. MockSubscriptionClientFactory.GetSubscriptionNameFromId(DefaultSubscription.ToString()),
  331. out subValue));
  332. Assert.Equal(DefaultSubscription.ToString(), subValue.Id.ToString());
  333. }
  334. [Fact]
  335. [Trait(Category.AcceptanceType, Category.CheckIn)]
  336. public void SingleTenantAndSubscriptionSucceeds()
  337. {
  338. var tenants = new List<string> { DefaultTenant.ToString() };
  339. var firstList = new List<string> { DefaultSubscription.ToString() };
  340. var secondList = firstList;
  341. var thirdList = firstList;
  342. var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList);
  343. var subResults = new List<AzureSubscription>(client.ListSubscriptions());
  344. Assert.Equal(1, subResults.Count);
  345. var tenantResults = client.ListTenants();
  346. Assert.Equal(1, tenantResults.Count());
  347. tenantResults = client.ListTenants(DefaultTenant.ToString());
  348. Assert.Equal(1, tenantResults.Count());
  349. AzureSubscription subValue;
  350. Assert.True(client.TryGetSubscriptionById(DefaultTenant.ToString(), DefaultSubscription.ToString(), out subValue));
  351. Assert.Equal(DefaultSubscription.ToString(), subValue.Id.ToString());
  352. Assert.True(client.TryGetSubscriptionByName(DefaultTenant.ToString(),
  353. MockSubscriptionClientFactory.GetSubscriptionNameFromId(DefaultSubscription.ToString()),
  354. out subValue));
  355. Assert.Equal(DefaultSubscription.ToString(), subValue.Id.ToString());
  356. }
  357. [Fact]
  358. [Trait(Category.AcceptanceType, Category.CheckIn)]
  359. public void SubscriptionNotFoundDoesNotThrow()
  360. {
  361. var tenants = new List<string> { DefaultTenant.ToString() };
  362. string randomSubscriptionId = Guid.NewGuid().ToString();
  363. var firstList = new List<string> { randomSubscriptionId };
  364. var secondList = firstList;
  365. var client = SetupTestEnvironment(tenants, firstList, secondList);
  366. var subResults = new List<AzureSubscription>(client.ListSubscriptions());
  367. Assert.Equal(1, subResults.Count);
  368. AzureSubscription subValue;
  369. Assert.False(client.TryGetSubscriptionById(DefaultTenant.ToString(), DefaultSubscription.ToString(), out subValue));
  370. Assert.False(client.TryGetSubscriptionByName("random-tenant", "random-subscription", out subValue));
  371. }
  372. [Fact]
  373. [Trait(Category.AcceptanceType, Category.CheckIn)]
  374. public void NoTenantsDoesNotThrow()
  375. {
  376. var tenants = new List<string> { };
  377. var subscriptions = new List<string> { Guid.NewGuid().ToString() };
  378. var client = SetupTestEnvironment(tenants, subscriptions);
  379. Assert.Equal(0, client.ListSubscriptions().Count());
  380. Assert.Equal(0, client.ListTenants().Count());
  381. }
  382. [Fact]
  383. [Trait(Category.AcceptanceType, Category.CheckIn)]
  384. public void NoSubscriptionsInListDoesNotThrow()
  385. {
  386. var tenants = new List<string> { DefaultTenant.ToString() };
  387. var subscriptions = new List<string>();
  388. var client = SetupTestEnvironment(tenants, subscriptions, subscriptions);
  389. Assert.Equal(0, client.ListSubscriptions().Count());
  390. AzureSubscription subValue;
  391. Assert.False(client.TryGetSubscriptionById(DefaultTenant.ToString(), DefaultSubscription.ToString(), out subValue));
  392. Assert.False(client.TryGetSubscriptionByName(DefaultTenant.ToString(), "random-name", out subValue));
  393. }
  394. [Fact]
  395. [Trait(Category.AcceptanceType, Category.CheckIn)]
  396. public void SetContextPreservesTokenCache()
  397. {
  398. AzureRMProfile profile = null;
  399. AzureContext context = new AzureContext(null, null, null, null);
  400. Assert.Throws<ArgumentNullException>(() => profile.SetContextWithCache(context));
  401. profile = new AzureRMProfile();
  402. Assert.Throws<ArgumentNullException>(() => profile.SetContextWithCache(null));
  403. profile.SetContextWithCache(context);
  404. Assert.Equal(TokenCache.DefaultShared.Serialize(), profile.Context.TokenCache);
  405. }
  406. [Fact]
  407. public void AzurePSComletMessageQueue()
  408. {
  409. ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
  410. Parallel.For(0, 5, i =>
  411. {
  412. for (int j = 0; j < 300; j++)
  413. {
  414. queue.CheckAndEnqueue(j.ToString());
  415. }
  416. });
  417. Assert.Equal(500, queue.Count);
  418. }
  419. [Fact]
  420. [Trait(Category.AcceptanceType, Category.CheckIn)]
  421. public void GetAzureRmSubscriptionPaginatedResult()
  422. {
  423. var tenants = new List<string> { Guid.NewGuid().ToString(), DefaultTenant.ToString() };
  424. var secondsubscriptionInTheFirstTenant = Guid.NewGuid().ToString();
  425. var firstList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  426. var secondList = new List<string> { Guid.NewGuid().ToString() };
  427. var thirdList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  428. var fourthList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
  429. var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList, fourthList);
  430. var dataStore = new MemoryDataStore();
  431. AzureSession.DataStore = dataStore;
  432. var commandRuntimeMock = new MockCommandRuntime();
  433. AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
  434. var profile = new AzureRMProfile();
  435. profile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
  436. profile.Context = Context;
  437. var cmdlt = new GetAzureRMSubscriptionCommand();
  438. // Setup
  439. cmdlt.DefaultProfile = profile;
  440. cmdlt.CommandRuntime = commandRuntimeMock;
  441. // Act
  442. cmdlt.InvokeBeginProcessing();
  443. cmdlt.ExecuteCmdlet();
  444. cmdlt.InvokeEndProcessing();
  445. Assert.True(commandRuntimeMock.OutputPipeline.Count == 7);
  446. Assert.Equal("Disabled", ((PSAzureSubscription)commandRuntimeMock.OutputPipeline[2]).State);
  447. Assert.Equal("LinkToNextPage", ((PSAzureSubscription)commandRuntimeMock.OutputPipeline[2]).SubscriptionName);
  448. }
  449. }
  450. }