PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/ResourceManager/AzureBatch/Commands.Batch.Test/BatchTestHelpers.cs

https://gitlab.com/jslee1/azure-powershell
C# | 936 lines | 622 code | 158 blank | 156 comment | 27 complexity | 45be799c86b6665d0670907c50ce8de8 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.Batch;
  15. using Microsoft.Azure.Batch.Protocol;
  16. using Microsoft.Azure.Batch.Protocol.BatchRequests;
  17. using Microsoft.Azure.Management.Batch.Models;
  18. using Microsoft.Rest.Azure;
  19. using System;
  20. using System.Collections;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Net;
  25. using System.Net.Http;
  26. using System.Reflection;
  27. using System.Threading.Tasks;
  28. using Microsoft.Azure.Commands.Batch.Models;
  29. using Xunit;
  30. using ProxyModels = Microsoft.Azure.Batch.Protocol.Models;
  31. namespace Microsoft.Azure.Commands.Batch.Test
  32. {
  33. /// <summary>
  34. /// Helper methods for the Batch cmdlet tests
  35. /// </summary>
  36. public static class BatchTestHelpers
  37. {
  38. internal static readonly string TestCertificateFileName1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\BatchTestCert01.cer");
  39. internal static readonly string TestCertificateFileName2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\BatchTestCert02.cer");
  40. internal const string TestCertificateAlgorithm = "sha1";
  41. internal const string TestCertificatePassword = "Passw0rd";
  42. internal static readonly int DefaultQuotaCount = 20;
  43. /// <summary>
  44. /// Builds an AccountResource object using the specified parameters
  45. /// </summary>
  46. public static AccountResource CreateAccountResource(string accountName, string resourceGroupName, Hashtable[] tags = null, string storageId = null)
  47. {
  48. string tenantUrlEnding = "batch-test.windows-int.net";
  49. string endpoint = string.Format("{0}.{1}", accountName, tenantUrlEnding);
  50. string subscription = Guid.Empty.ToString();
  51. string resourceGroup = resourceGroupName;
  52. string id = string.Format("id/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Batch/batchAccounts/abc", subscription, resourceGroup);
  53. AccountResource resource = new AccountResource(
  54. coreQuota: DefaultQuotaCount,
  55. poolQuota: DefaultQuotaCount,
  56. activeJobAndJobScheduleQuota: DefaultQuotaCount,
  57. id: id,
  58. type: "type")
  59. {
  60. Location = "location",
  61. AccountEndpoint = endpoint,
  62. ProvisioningState = AccountProvisioningState.Succeeded,
  63. AutoStorage = new AutoStorageProperties() { StorageAccountId = storageId }
  64. };
  65. if (tags != null)
  66. {
  67. resource.Tags = Microsoft.Azure.Commands.Batch.Helpers.CreateTagDictionary(tags, true);
  68. }
  69. return resource;
  70. }
  71. /// <summary>
  72. /// Builds a BatchAccountContext object with the keys set for testing
  73. /// </summary>
  74. public static BatchAccountContext CreateBatchContextWithKeys()
  75. {
  76. AccountResource resource = CreateAccountResource("account", "resourceGroup");
  77. BatchAccountContext context = BatchAccountContext.ConvertAccountResourceToNewAccountContext(resource);
  78. string dummyKey = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
  79. SetProperty(context, "PrimaryAccountKey", dummyKey);
  80. SetProperty(context, "SecondaryAccountKey", dummyKey);
  81. return context;
  82. }
  83. /// <summary>
  84. /// Verifies that two BatchAccountContext objects are equal
  85. /// </summary>
  86. public static void AssertBatchAccountContextsAreEqual(BatchAccountContext context1, BatchAccountContext context2)
  87. {
  88. if (context1 == null)
  89. {
  90. Assert.Null(context2);
  91. return;
  92. }
  93. if (context2 == null)
  94. {
  95. Assert.Null(context1);
  96. return;
  97. }
  98. Assert.Equal<string>(context1.AccountEndpoint, context2.AccountEndpoint);
  99. Assert.Equal<string>(context1.AccountName, context2.AccountName);
  100. Assert.Equal<string>(context1.Id, context2.Id);
  101. Assert.Equal<string>(context1.Location, context2.Location);
  102. Assert.Equal<string>(context1.PrimaryAccountKey, context2.PrimaryAccountKey);
  103. Assert.Equal<string>(context1.ResourceGroupName, context2.ResourceGroupName);
  104. Assert.Equal<string>(context1.SecondaryAccountKey, context2.SecondaryAccountKey);
  105. Assert.Equal<string>(context1.State, context2.State);
  106. Assert.Equal<string>(context1.Subscription, context2.Subscription);
  107. Assert.Equal<string>(context1.TagsTable, context2.TagsTable);
  108. Assert.Equal<string>(context1.TaskTenantUrl, context2.TaskTenantUrl);
  109. Assert.Equal<string>(context1.AutoStorageProperties.StorageAccountId, context2.AutoStorageProperties.StorageAccountId);
  110. }
  111. /// <summary>
  112. /// Creates a RequestInterceptor that does not contact the Batch Service but instead uses the supplied response body.
  113. /// </summary>
  114. /// <param name="responseToUse">The response the interceptor should return. If none is specified, then a new instance of the response type is instantiated.</param>
  115. /// <param name="requestAction">An action to perform on the request.</param>
  116. /// <typeparam name="TOptions">The type of the request options.</typeparam>
  117. /// <typeparam name="TResponse">The type of the expected response.</typeparam>
  118. public static RequestInterceptor CreateFakeServiceResponseInterceptor<TOptions, TResponse>(TResponse responseToUse = default(TResponse),
  119. Action<BatchRequest<TOptions, TResponse>> requestAction = null)
  120. where TOptions : ProxyModels.IOptions, new()
  121. where TResponse : class, IAzureOperationResponse, new()
  122. {
  123. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  124. {
  125. BatchRequest<TOptions, TResponse> request = (BatchRequest<TOptions, TResponse>)baseRequest;
  126. request.ServiceRequestFunc = (cancellationToken) =>
  127. {
  128. responseToUse = responseToUse ?? new TResponse()
  129. {
  130. Response = new HttpResponseMessage()
  131. };
  132. if (requestAction != null)
  133. {
  134. requestAction(request);
  135. }
  136. Task<TResponse> task = Task.FromResult(responseToUse);
  137. return task;
  138. };
  139. });
  140. return interceptor;
  141. }
  142. /// <summary>
  143. /// Creates a RequestInterceptor that does not contact the Batch Service but instead uses the supplied response body.
  144. /// </summary>
  145. /// <param name="responseToUse">The response the interceptor should return. If none is specified, then a new instance of the response type is instantiated.</param>
  146. /// <param name="requestAction">An action to perform on the request.</param>
  147. /// <typeparam name="TBody">The type of the body parameters associated with the request.</typeparam>
  148. /// <typeparam name="TOptions">The type of the request options.</typeparam>
  149. /// <typeparam name="TResponse">The type of the expected response.</typeparam>
  150. public static RequestInterceptor CreateFakeServiceResponseInterceptor<TBody, TOptions, TResponse>(TResponse responseToUse = default(TResponse),
  151. Action<BatchRequest<TBody, TOptions, TResponse>> requestAction = null)
  152. where TOptions : ProxyModels.IOptions, new()
  153. where TResponse : class, IAzureOperationResponse, new()
  154. {
  155. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  156. {
  157. BatchRequest<TBody, TOptions, TResponse> request = (BatchRequest<TBody, TOptions, TResponse>)baseRequest;
  158. if (requestAction != null)
  159. {
  160. requestAction(request);
  161. }
  162. request.ServiceRequestFunc = (cancellationToken) =>
  163. {
  164. TResponse response = responseToUse ?? new TResponse()
  165. {
  166. Response = new HttpResponseMessage()
  167. };
  168. Task<TResponse> task = Task.FromResult(response);
  169. return task;
  170. };
  171. });
  172. return interceptor;
  173. }
  174. /// <summary>
  175. /// Builds a generic azure operation response object
  176. /// </summary>
  177. /// <typeparam name="TBody">The object that will be put in the response body</typeparam>
  178. /// <typeparam name="THeader">The type of header for the response</typeparam>
  179. /// <returns></returns>
  180. public static AzureOperationResponse<TBody, THeader> CreateGenericAzureOperationResponse<TBody, THeader>()
  181. where TBody : class, new()
  182. where THeader : class, new()
  183. {
  184. var response = new AzureOperationResponse<TBody, THeader>()
  185. {
  186. Body = new TBody(),
  187. Headers = new THeader()
  188. };
  189. return response;
  190. }
  191. /// <summary>
  192. /// Builds a generic azure operation response with a response body that contains a list of objects
  193. /// </summary>
  194. /// <typeparam name="TBody">The object that will be put in the response body as a list</typeparam>
  195. /// <typeparam name="THeader">The type of header for the response</typeparam>
  196. /// <returns></returns>
  197. public static AzureOperationResponse<IPage<TBody>, THeader> CreateGenericAzureOperationListResponse<TBody, THeader>()
  198. where TBody : class, new()
  199. where THeader : class, new()
  200. {
  201. var response = new AzureOperationResponse<IPage<TBody>, THeader>()
  202. {
  203. Body = new MockPagedEnumerable<TBody>(),
  204. Headers = new THeader()
  205. };
  206. return response;
  207. }
  208. /// <summary>
  209. /// Creates a RequestInterceptor that does not contact the Batch Service on a Get NodeFile or a Get NodeFile Properties call.
  210. /// The interceptor must handle both request types since it's possible for one OM node file method to perform both REST APIs.
  211. /// </summary>
  212. /// <param name="fileName">The name of the file to put in the response body.</param>
  213. public static RequestInterceptor CreateFakeGetFileAndPropertiesFromTaskResponseInterceptor(string fileName)
  214. {
  215. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  216. {
  217. FileGetFromTaskBatchRequest fileRequest = baseRequest as FileGetFromTaskBatchRequest;
  218. if (fileRequest != null)
  219. {
  220. fileRequest.ServiceRequestFunc = (cancellationToken) =>
  221. {
  222. var response = new AzureOperationResponse<Stream, ProxyModels.FileGetFromTaskHeaders>();
  223. response.Headers = new ProxyModels.FileGetFromTaskHeaders();
  224. response.Body = new MemoryStream();
  225. Task<AzureOperationResponse<Stream, ProxyModels.FileGetFromTaskHeaders>> task = Task.FromResult(response);
  226. return task;
  227. };
  228. }
  229. else
  230. {
  231. FileGetNodeFilePropertiesFromTaskBatchRequest propRequest = (FileGetNodeFilePropertiesFromTaskBatchRequest)baseRequest;
  232. propRequest.ServiceRequestFunc = (cancellationToken) =>
  233. {
  234. var response = new AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders>();
  235. response.Headers = new ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders();
  236. Task<AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders>> task = Task.FromResult(response);
  237. return task;
  238. };
  239. }
  240. });
  241. return interceptor;
  242. }
  243. /// <summary>
  244. /// Creates a RequestInterceptor that does not contact the Batch Service on a Get NodeFile or a Get NodeFile Properties call.
  245. /// The interceptor must handle both request types since it's possible for one OM node file method to perform both REST APIs.
  246. /// </summary>
  247. /// <param name="fileName">The name of the file to put in the response body.</param>
  248. public static RequestInterceptor CreateFakeGetFileAndPropertiesFromComputeNodeResponseInterceptor(string fileName)
  249. {
  250. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  251. {
  252. FileGetFromComputeNodeBatchRequest fileRequest = baseRequest as FileGetFromComputeNodeBatchRequest;
  253. if (fileRequest != null)
  254. {
  255. fileRequest.ServiceRequestFunc = (cancellationToken) =>
  256. {
  257. var response = new AzureOperationResponse<Stream, ProxyModels.FileGetFromComputeNodeHeaders>();
  258. response.Headers = new ProxyModels.FileGetFromComputeNodeHeaders();
  259. response.Body = new MemoryStream();
  260. Task<AzureOperationResponse<Stream, ProxyModels.FileGetFromComputeNodeHeaders>> task = Task.FromResult(response);
  261. return task;
  262. };
  263. }
  264. else
  265. {
  266. FileGetNodeFilePropertiesFromComputeNodeBatchRequest propRequest = (FileGetNodeFilePropertiesFromComputeNodeBatchRequest)baseRequest;
  267. propRequest.ServiceRequestFunc = (cancellationToken) =>
  268. {
  269. var response = new AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders>();
  270. response.Headers = new ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders();
  271. Task<AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders>> task = Task.FromResult(response);
  272. return task;
  273. };
  274. }
  275. });
  276. return interceptor;
  277. }
  278. /// <summary>
  279. /// Builds a CertificateGetResponse object
  280. /// </summary>
  281. public static AzureOperationResponse<ProxyModels.Certificate, ProxyModels.CertificateGetHeaders> CreateCertificateGetResponse(string thumbprint)
  282. {
  283. var response = new AzureOperationResponse<ProxyModels.Certificate, ProxyModels.CertificateGetHeaders>();
  284. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  285. ProxyModels.Certificate cert = new ProxyModels.Certificate();
  286. cert.Thumbprint = thumbprint;
  287. response.Body = cert;
  288. return response;
  289. }
  290. /// <summary>
  291. /// Builds a CertificateListResponse object
  292. /// </summary>
  293. public static AzureOperationResponse<IPage<ProxyModels.Certificate>, ProxyModels.CertificateListHeaders> CreateCertificateListResponse(IEnumerable<string> certThumbprints)
  294. {
  295. var response = new AzureOperationResponse<IPage<ProxyModels.Certificate>, ProxyModels.CertificateListHeaders>();
  296. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  297. List<ProxyModels.Certificate> certs = new List<ProxyModels.Certificate>();
  298. foreach (string t in certThumbprints)
  299. {
  300. ProxyModels.Certificate cert = new ProxyModels.Certificate();
  301. cert.Thumbprint = t;
  302. certs.Add(cert);
  303. }
  304. response.Body = new MockPagedEnumerable<ProxyModels.Certificate>(certs);
  305. return response;
  306. }
  307. /// <summary>
  308. /// Builds a CloudPoolGetResponse object
  309. /// </summary>
  310. public static AzureOperationResponse<ProxyModels.CloudPool, ProxyModels.PoolGetHeaders> CreateCloudPoolGetResponse(string poolId)
  311. {
  312. var response = new AzureOperationResponse<ProxyModels.CloudPool, ProxyModels.PoolGetHeaders>();
  313. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  314. ProxyModels.CloudPool pool = new ProxyModels.CloudPool();
  315. pool.Id = poolId;
  316. response.Body = pool;
  317. return response;
  318. }
  319. /// <summary>
  320. /// Builds a CloudPoolListResponse object
  321. /// </summary>
  322. public static AzureOperationResponse<IPage<ProxyModels.CloudPool>, ProxyModels.PoolListHeaders> CreateCloudPoolListResponse(IEnumerable<string> poolIds)
  323. {
  324. var response = new AzureOperationResponse<IPage<ProxyModels.CloudPool>, ProxyModels.PoolListHeaders>();
  325. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  326. List<ProxyModels.CloudPool> pools = new List<ProxyModels.CloudPool>();
  327. foreach (string id in poolIds)
  328. {
  329. ProxyModels.CloudPool pool = new ProxyModels.CloudPool();
  330. pool.Id = id;
  331. pools.Add(pool);
  332. }
  333. response.Body = new MockPagedEnumerable<ProxyModels.CloudPool>(pools);
  334. return response;
  335. }
  336. /// <summary>
  337. /// Builds a CloudPoolUsageMetricsResponse object. Note: The lengths of all three lists must be the same.
  338. /// </summary>
  339. public static AzureOperationResponse<IPage<ProxyModels.PoolUsageMetrics>, ProxyModels.PoolListPoolUsageMetricsHeaders> CreatePoolListUsageMetricsResponse(
  340. IEnumerable<string> poolIds,
  341. IEnumerable<DateTime> startTimes,
  342. IEnumerable<DateTime> endTimes)
  343. {
  344. var poolUsageList = new List<ProxyModels.PoolUsageMetrics>();
  345. // Validate the lengths of the lists are equal
  346. if (!(poolIds.Count() == startTimes.Count() && startTimes.Count() == endTimes.Count()))
  347. {
  348. throw new ArgumentException("The lists length are not equal.");
  349. }
  350. using (var startTimeEnumerator = startTimes.GetEnumerator())
  351. using (var endTimeEnumerator = endTimes.GetEnumerator())
  352. using (var poolIdEnumerator = poolIds.GetEnumerator())
  353. {
  354. while (startTimeEnumerator.MoveNext() && endTimeEnumerator.MoveNext() && poolIdEnumerator.MoveNext())
  355. {
  356. poolUsageList.Add(new ProxyModels.PoolUsageMetrics()
  357. {
  358. PoolId = poolIdEnumerator.Current,
  359. StartTime = startTimeEnumerator.Current,
  360. EndTime = endTimeEnumerator.Current
  361. });
  362. }
  363. }
  364. var response = new AzureOperationResponse
  365. <IPage<ProxyModels.PoolUsageMetrics>, ProxyModels.PoolListPoolUsageMetricsHeaders>()
  366. {
  367. Response = new HttpResponseMessage(HttpStatusCode.OK),
  368. Body = new MockPagedEnumerable<ProxyModels.PoolUsageMetrics>(poolUsageList)
  369. };
  370. return response;
  371. }
  372. /// <summary>
  373. /// Builds a CloudPoolStatisticsResponse object. Note: Using avgCPUPercentage and startTime for validating if the pipeline return the correct values
  374. /// </summary>
  375. public static AzureOperationResponse<ProxyModels.PoolStatistics, ProxyModels.PoolGetAllPoolsLifetimeStatisticsHeaders> CreatePoolStatisticsResponse(
  376. double avgCPUPercentage,
  377. DateTime startTime)
  378. {
  379. var stats = new ProxyModels.PoolStatistics()
  380. {
  381. ResourceStats = new ProxyModels.ResourceStatistics() { AvgCPUPercentage = avgCPUPercentage },
  382. UsageStats = new ProxyModels.UsageStatistics() { StartTime = startTime }
  383. };
  384. var response = new AzureOperationResponse
  385. <ProxyModels.PoolStatistics, ProxyModels.PoolGetAllPoolsLifetimeStatisticsHeaders>()
  386. {
  387. Body = stats,
  388. Response = new HttpResponseMessage(HttpStatusCode.Accepted)
  389. };
  390. return response;
  391. }
  392. /// <summary>
  393. /// Builds a CloudJobStatisticsResponse object.Note: Using startTime for validating if the pipeline return the correct values
  394. /// </summary>
  395. public static AzureOperationResponse<ProxyModels.JobStatistics, ProxyModels.JobGetAllJobsLifetimeStatisticsHeaders> CreateJobStatisticsResponse(DateTime startTime)
  396. {
  397. var stats = new ProxyModels.JobStatistics()
  398. {
  399. StartTime = startTime
  400. };
  401. var response = new AzureOperationResponse
  402. <ProxyModels.JobStatistics, ProxyModels.JobGetAllJobsLifetimeStatisticsHeaders>()
  403. {
  404. Body = stats,
  405. Response = new HttpResponseMessage(HttpStatusCode.Accepted)
  406. };
  407. return response;
  408. }
  409. /// <summary>
  410. /// Builds a GetRemoteLoginSettingsResponse object
  411. /// </summary>
  412. public static AzureOperationResponse<ProxyModels.ComputeNodeGetRemoteLoginSettingsResult, ProxyModels.ComputeNodeGetRemoteLoginSettingsHeaders> CreateRemoteLoginSettingsGetResponse(string ipAddress)
  413. {
  414. var settings = new ProxyModels.ComputeNodeGetRemoteLoginSettingsResult();
  415. settings.RemoteLoginIPAddress = ipAddress;
  416. var response = new AzureOperationResponse<ProxyModels.ComputeNodeGetRemoteLoginSettingsResult, ProxyModels.ComputeNodeGetRemoteLoginSettingsHeaders>()
  417. {
  418. Response = new HttpResponseMessage(HttpStatusCode.OK),
  419. Body = settings
  420. };
  421. return response;
  422. }
  423. /// <summary>
  424. /// Builds a ComputeNodeGetResponse object
  425. /// </summary>
  426. public static AzureOperationResponse<ProxyModels.ComputeNode, ProxyModels.ComputeNodeGetHeaders> CreateComputeNodeGetResponse(string computeNodeId)
  427. {
  428. var response = new AzureOperationResponse<ProxyModels.ComputeNode, ProxyModels.ComputeNodeGetHeaders>();
  429. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  430. ProxyModels.ComputeNode computeNode = new ProxyModels.ComputeNode();
  431. computeNode.Id = computeNodeId;
  432. response.Body = computeNode;
  433. return response;
  434. }
  435. /// <summary>
  436. /// Builds a ComputeNodeListResponse object
  437. /// </summary>
  438. public static AzureOperationResponse<IPage<ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> CreateComputeNodeListResponse(IEnumerable<string> computeNodeIds)
  439. {
  440. var response = new AzureOperationResponse<IPage<ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders>();
  441. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  442. List<ProxyModels.ComputeNode> computeNodes = new List<ProxyModels.ComputeNode>();
  443. foreach (string id in computeNodeIds)
  444. {
  445. ProxyModels.ComputeNode computeNode = new ProxyModels.ComputeNode();
  446. computeNode.Id = id;
  447. computeNodes.Add(computeNode);
  448. }
  449. response.Body = new MockPagedEnumerable<ProxyModels.ComputeNode>(computeNodes);
  450. return response;
  451. }
  452. /// <summary>
  453. /// Builds a CloudJobScheduleGetResponse object
  454. /// </summary>
  455. public static AzureOperationResponse<ProxyModels.CloudJobSchedule, ProxyModels.JobScheduleGetHeaders> CreateCloudJobScheduleGetResponse(string jobScheduleId)
  456. {
  457. var response = new AzureOperationResponse<ProxyModels.CloudJobSchedule, ProxyModels.JobScheduleGetHeaders>();
  458. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  459. ProxyModels.JobSpecification jobSpec = new ProxyModels.JobSpecification();
  460. ProxyModels.Schedule schedule = new ProxyModels.Schedule();
  461. ProxyModels.CloudJobSchedule jobSchedule = new ProxyModels.CloudJobSchedule(id: jobScheduleId, schedule: schedule, jobSpecification: jobSpec);
  462. response.Body = jobSchedule;
  463. return response;
  464. }
  465. /// <summary>
  466. /// Builds a CloudJobScheduleListResponse object
  467. /// </summary>
  468. public static AzureOperationResponse<IPage<ProxyModels.CloudJobSchedule>, ProxyModels.JobScheduleListHeaders> CreateCloudJobScheduleListResponse(IEnumerable<string> jobScheduleIds)
  469. {
  470. var response = new AzureOperationResponse<IPage<ProxyModels.CloudJobSchedule>, ProxyModels.JobScheduleListHeaders>();
  471. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  472. List<ProxyModels.CloudJobSchedule> jobSchedules = new List<ProxyModels.CloudJobSchedule>();
  473. ProxyModels.JobSpecification jobSpec = new ProxyModels.JobSpecification();
  474. ProxyModels.Schedule schedule = new ProxyModels.Schedule();
  475. foreach (string id in jobScheduleIds)
  476. {
  477. jobSchedules.Add(new ProxyModels.CloudJobSchedule(id: id, schedule: schedule, jobSpecification: jobSpec));
  478. }
  479. response.Body = new MockPagedEnumerable<ProxyModels.CloudJobSchedule>(jobSchedules);
  480. return response;
  481. }
  482. /// <summary>
  483. /// Builds a CloudJobGetResponse object
  484. /// </summary>
  485. public static AzureOperationResponse<ProxyModels.CloudJob, ProxyModels.JobGetHeaders> CreateCloudJobGetResponse(string jobId)
  486. {
  487. var response = new AzureOperationResponse<ProxyModels.CloudJob, ProxyModels.JobGetHeaders>();
  488. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  489. ProxyModels.CloudJob job = new ProxyModels.CloudJob();
  490. job.Id = jobId;
  491. response.Body = job;
  492. return response;
  493. }
  494. /// <summary>
  495. /// Builds a CloudJobListResponse object
  496. /// </summary>
  497. public static AzureOperationResponse<IPage<ProxyModels.CloudJob>, ProxyModels.JobListHeaders> CreateCloudJobListResponse(IEnumerable<string> jobIds)
  498. {
  499. var response = new AzureOperationResponse<IPage<ProxyModels.CloudJob>, ProxyModels.JobListHeaders>();
  500. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  501. List<ProxyModels.CloudJob> jobs = new List<ProxyModels.CloudJob>();
  502. foreach (string id in jobIds)
  503. {
  504. ProxyModels.CloudJob job = new ProxyModels.CloudJob();
  505. job.Id = id;
  506. jobs.Add(job);
  507. }
  508. response.Body = new MockPagedEnumerable<ProxyModels.CloudJob>(jobs);
  509. return response;
  510. }
  511. /// <summary>
  512. /// Builds a CloudTaskGetResponse object
  513. /// </summary>
  514. public static AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> CreateCloudTaskGetResponse(string taskId)
  515. {
  516. var response = new AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders>();
  517. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  518. ProxyModels.CloudTask task = new ProxyModels.CloudTask();
  519. task.Id = taskId;
  520. response.Body = task;
  521. return response;
  522. }
  523. /// <summary>
  524. /// Builds a CloudTaskListResponse object
  525. /// </summary>
  526. public static AzureOperationResponse<IPage<ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> CreateCloudTaskListResponse(IEnumerable<string> taskIds)
  527. {
  528. var response = new AzureOperationResponse<IPage<ProxyModels.CloudTask>, ProxyModels.TaskListHeaders>();
  529. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  530. List<ProxyModels.CloudTask> tasks = new List<ProxyModels.CloudTask>();
  531. foreach (string id in taskIds)
  532. {
  533. ProxyModels.CloudTask task = new ProxyModels.CloudTask();
  534. task.Id = id;
  535. tasks.Add(task);
  536. }
  537. response.Body = new MockPagedEnumerable<ProxyModels.CloudTask>(tasks);
  538. return response;
  539. }
  540. /// <summary>
  541. /// Builds a TaskAddCollectionResponse object
  542. /// </summary>
  543. public static AzureOperationResponse<ProxyModels.TaskAddCollectionResult, ProxyModels.TaskAddCollectionHeaders> CreateTaskCollectionResponse(PSCloudTask[] taskCollection)
  544. {
  545. Func<PSCloudTask, ProxyModels.TaskAddResult> mappingFunc =
  546. t => new ProxyModels.TaskAddResult(ProxyModels.TaskAddStatus.Success, t.Id);
  547. var taskAddResults = taskCollection.Select(mappingFunc);
  548. var response = new AzureOperationResponse
  549. <ProxyModels.TaskAddCollectionResult, ProxyModels.TaskAddCollectionHeaders>()
  550. {
  551. Response = new HttpResponseMessage(HttpStatusCode.Created),
  552. Body = new ProxyModels.TaskAddCollectionResult(taskAddResults.ToList())
  553. };
  554. return response;
  555. }
  556. /// <summary>
  557. /// Builds a CloudTaskListSubtasksResponse object
  558. /// </summary>
  559. public static AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> CreateCloudTaskListSubtasksResponse(IEnumerable<int> subtaskIds = default(IEnumerable<int>))
  560. {
  561. var response = new AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders>();
  562. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  563. List<ProxyModels.SubtaskInformation> subtasks = new List<ProxyModels.SubtaskInformation>();
  564. ProxyModels.CloudTaskListSubtasksResult subtasksResult = new ProxyModels.CloudTaskListSubtasksResult();
  565. if (subtaskIds != null)
  566. {
  567. foreach (int id in subtaskIds)
  568. {
  569. ProxyModels.SubtaskInformation subtask = new ProxyModels.SubtaskInformation();
  570. subtask.Id = id;
  571. subtasks.Add(subtask);
  572. }
  573. }
  574. subtasksResult.Value = subtasks;
  575. response.Body = subtasksResult;
  576. return response;
  577. }
  578. /// <summary>
  579. /// Builds a NodeAgentSKUResponse object
  580. /// </summary>
  581. public static AzureOperationResponse<IPage<ProxyModels.NodeAgentSku>, ProxyModels.AccountListNodeAgentSkusHeaders> CreateNodeAgentSkuResponse(IEnumerable<string> skuIds)
  582. {
  583. IEnumerable<ProxyModels.NodeAgentSku> nodeAgents =
  584. skuIds.Select(id => new ProxyModels.NodeAgentSku() { Id = id });
  585. var response = new AzureOperationResponse<IPage<ProxyModels.NodeAgentSku>, ProxyModels.AccountListNodeAgentSkusHeaders>()
  586. {
  587. Response = new HttpResponseMessage(HttpStatusCode.OK),
  588. Body = new MockPagedEnumerable<ProxyModels.NodeAgentSku>(nodeAgents)
  589. };
  590. return response;
  591. }
  592. /// <summary>
  593. /// Builds a NodeFileGetPropertiesResponse object
  594. /// </summary>
  595. public static AzureOperationResponse<Stream, ProxyModels.ComputeNodeGetRemoteDesktopHeaders> CreateGetRemoteDesktOperationResponse()
  596. {
  597. var response = new AzureOperationResponse<Stream, ProxyModels.ComputeNodeGetRemoteDesktopHeaders>();
  598. response.Headers = new ProxyModels.ComputeNodeGetRemoteDesktopHeaders();
  599. response.Body = new MemoryStream();
  600. return response;
  601. }
  602. /// <summary>
  603. /// Builds a NodeFileGetPropertiesFromTaskResponse object
  604. /// </summary>
  605. public static AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders> CreateNodeFileGetPropertiesByTaskResponse()
  606. {
  607. var response = new AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders>();
  608. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  609. response.Headers = new ProxyModels.FileGetNodeFilePropertiesFromTaskHeaders();
  610. return response;
  611. }
  612. /// <summary>
  613. /// Builds a NodeFileGetPropertiesFromComputeNodeResponse object
  614. /// </summary>
  615. public static AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders> CreateNodeFileGetPropertiesByComputeNodeResponse()
  616. {
  617. var response = new AzureOperationHeaderResponse<ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders>();
  618. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  619. response.Headers = new ProxyModels.FileGetNodeFilePropertiesFromComputeNodeHeaders();
  620. return response;
  621. }
  622. /// <summary>
  623. /// Builds a NodeFileGetPropertiesFromComputeNodeResponse object
  624. /// </summary>
  625. public static AzureOperationResponse<Stream, ProxyModels.FileGetFromComputeNodeHeaders> CreateNodeFileByComputeNodeResponse()
  626. {
  627. var response = new AzureOperationResponse<Stream, ProxyModels.FileGetFromComputeNodeHeaders>();
  628. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  629. response.Headers = new ProxyModels.FileGetFromComputeNodeHeaders();
  630. return response;
  631. }
  632. /// <summary>
  633. /// Builds a NodeFileListFromTaskResponse object
  634. /// </summary>
  635. public static AzureOperationResponse<IPage<ProxyModels.NodeFile>, ProxyModels.FileListFromTaskHeaders> CreateNodeFileListByTaskResponse(IEnumerable<string> fileNames)
  636. {
  637. var response = new AzureOperationResponse<IPage<ProxyModels.NodeFile>, ProxyModels.FileListFromTaskHeaders>();
  638. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  639. List<ProxyModels.NodeFile> files = new List<ProxyModels.NodeFile>();
  640. foreach (string name in fileNames)
  641. {
  642. ProxyModels.NodeFile file = new ProxyModels.NodeFile();
  643. file.Name = name;
  644. files.Add(file);
  645. }
  646. response.Body = new MockPagedEnumerable<ProxyModels.NodeFile>(files);
  647. return response;
  648. }
  649. /// <summary>
  650. /// Builds a NodeFileListFromComputeNodeResponse object
  651. /// </summary>
  652. public static AzureOperationResponse<IPage<ProxyModels.NodeFile>, ProxyModels.FileListFromComputeNodeHeaders> CreateNodeFileListByComputeNodeResponse(IEnumerable<string> fileNames)
  653. {
  654. var response = new AzureOperationResponse<IPage<ProxyModels.NodeFile>, ProxyModels.FileListFromComputeNodeHeaders>();
  655. response.Response = new HttpResponseMessage(HttpStatusCode.OK);
  656. List<ProxyModels.NodeFile> files = new List<ProxyModels.NodeFile>();
  657. foreach (string name in fileNames)
  658. {
  659. ProxyModels.NodeFile file = new ProxyModels.NodeFile();
  660. file.Name = name;
  661. files.Add(file);
  662. }
  663. response.Body = new MockPagedEnumerable<ProxyModels.NodeFile>(files);
  664. return response;
  665. }
  666. /// <summary>
  667. /// Fabricates a CloudJob that's in the bound state
  668. /// </summary>
  669. public static CloudJob CreateFakeBoundJob(BatchAccountContext context)
  670. {
  671. string jobId = "testJob";
  672. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  673. {
  674. JobGetBatchRequest request = (JobGetBatchRequest)baseRequest;
  675. request.ServiceRequestFunc = (cancellationToken) =>
  676. {
  677. var response = new AzureOperationResponse<ProxyModels.CloudJob, ProxyModels.JobGetHeaders>();
  678. response.Body = new ProxyModels.CloudJob(id: jobId, poolInfo: new ProxyModels.PoolInformation());
  679. Task<AzureOperationResponse<ProxyModels.CloudJob, ProxyModels.JobGetHeaders>> task = Task.FromResult(response);
  680. return task;
  681. };
  682. });
  683. return context.BatchOMClient.JobOperations.GetJob(jobId, additionalBehaviors: new BatchClientBehavior[] { interceptor });
  684. }
  685. /// <summary>
  686. /// Fabricates a CloudJobSchedule that's in the bound state
  687. /// </summary>
  688. public static CloudJobSchedule CreateFakeBoundJobSchedule(BatchAccountContext context)
  689. {
  690. string jobScheduleId = "testJobSchedule";
  691. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  692. {
  693. JobScheduleGetBatchRequest request = (JobScheduleGetBatchRequest)baseRequest;
  694. request.ServiceRequestFunc = (cancellationToken) =>
  695. {
  696. var response = new AzureOperationResponse<ProxyModels.CloudJobSchedule, ProxyModels.JobScheduleGetHeaders>();
  697. response.Body = new ProxyModels.CloudJobSchedule(id: jobScheduleId, schedule: new ProxyModels.Schedule(), jobSpecification: new ProxyModels.JobSpecification());
  698. Task<AzureOperationResponse<ProxyModels.CloudJobSchedule, ProxyModels.JobScheduleGetHeaders>> task = Task.FromResult(response);
  699. return task;
  700. };
  701. });
  702. return context.BatchOMClient.JobScheduleOperations.GetJobSchedule(jobScheduleId, additionalBehaviors: new BatchClientBehavior[] { interceptor });
  703. }
  704. /// <summary>
  705. /// Fabricates a CloudPool that's in the bound state
  706. /// </summary>
  707. public static CloudPool CreateFakeBoundPool(BatchAccountContext context)
  708. {
  709. string poolId = "testPool";
  710. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  711. {
  712. PoolGetBatchRequest request = (PoolGetBatchRequest)baseRequest;
  713. request.ServiceRequestFunc = (cancellationToken) =>
  714. {
  715. var response = new AzureOperationResponse<ProxyModels.CloudPool, ProxyModels.PoolGetHeaders>();
  716. response.Body = new ProxyModels.CloudPool(poolId, "small", "4");
  717. Task<AzureOperationResponse<ProxyModels.CloudPool, ProxyModels.PoolGetHeaders>> task = Task.FromResult(response);
  718. return task;
  719. };
  720. });
  721. return context.BatchOMClient.PoolOperations.GetPool(poolId, additionalBehaviors: new BatchClientBehavior[] { interceptor });
  722. }
  723. /// <summary>
  724. /// Fabricates a CloudTask that's in the bound state
  725. /// </summary>
  726. public static CloudTask CreateFakeBoundTask(BatchAccountContext context)
  727. {
  728. string taskId = "testTask";
  729. RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
  730. {
  731. TaskGetBatchRequest request = (TaskGetBatchRequest)baseRequest;
  732. request.ServiceRequestFunc = (cancellationToken) =>
  733. {
  734. var response = new AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders>();
  735. response.Body = new ProxyModels.CloudTask(taskId, "cmd /c dir /s");
  736. Task<AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders>> task = Task.FromResult(response);
  737. return task;
  738. };
  739. });
  740. return context.BatchOMClient.JobOperations.GetTask("jobId", taskId, additionalBehaviors: new BatchClientBehavior[] { interceptor });
  741. }
  742. /// <summary>
  743. /// Uses Reflection to set a property value on an object. Can be used to bypass restricted set accessors.
  744. /// </summary>
  745. internal static void SetProperty(object obj, string propertyName, object propertyValue)
  746. {
  747. Type t = obj.GetType();
  748. PropertyInfo propInfo = t.GetProperty(propertyName);
  749. propInfo.SetValue(obj, propertyValue);
  750. }
  751. /// <summary>
  752. /// Uses Reflection to set a property value on an object.
  753. /// </summary>
  754. internal static void SetField(object obj, string fieldName, object fieldValue)
  755. {
  756. Type t = obj.GetType();
  757. FieldInfo fieldInfo = t.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
  758. fieldInfo.SetValue(obj, fieldValue);
  759. }
  760. internal static T MapEnum<T>(Enum otherEnum) where T : struct
  761. {
  762. if (otherEnum == null)
  763. {
  764. throw new ArgumentNullException("otherEnum");
  765. }
  766. T result = (T)Enum.Parse(typeof(T), otherEnum.ToString(), ignoreCase: true);
  767. return result;
  768. }
  769. internal static T? MapNullableEnum<T>(Enum otherEnum) where T : struct
  770. {
  771. if (otherEnum == null)
  772. {
  773. return null;
  774. }
  775. return MapEnum<T>(otherEnum);
  776. }
  777. }
  778. }