public void GetBatchTaskParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.Job = null; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a List CloudTask call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudTaskListParameters, CloudTaskListResponse> request = (BatchRequest<CloudTaskListParameters, CloudTaskListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudTaskListResponse response = BatchTestHelpers.CreateCloudTaskListResponse(new string[] {cmdlet.Id}); Task<CloudTaskListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobId = "job-1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); }
public void NewBatchComputeNodeUserParametersTest() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.PoolId = "testPool"; cmdlet.ComputeNodeId = "computeNode1"; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Name = "testUser"; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Password = "******"; // Don't go to the service on an Add ComputeNodeUser call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<ComputeNodeAddUserParameters, ComputeNodeAddUserResponse> request = (BatchRequest<ComputeNodeAddUserParameters, ComputeNodeAddUserResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { ComputeNodeAddUserResponse response = new ComputeNodeAddUserResponse(); Task<ComputeNodeAddUserResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameters are set cmdlet.ExecuteCmdlet(); }
public void NewBatchJobScheduleParametersTest() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Id = "testJobSchedule"; // Don't go to the service on an Add CloudJobSchedule call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobScheduleAddParameters, CloudJobScheduleAddResponse> request = (BatchRequest<CloudJobScheduleAddParameters, CloudJobScheduleAddResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudJobScheduleAddResponse response = new CloudJobScheduleAddResponse(); Task<CloudJobScheduleAddResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameters are set cmdlet.ExecuteCmdlet(); }
public void GetBatchJobScheduleTest() { // Setup cmdlet to get a job schedule by id BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = "testJobSchedule"; cmdlet.Filter = null; // Build a CloudJobSchedule instead of querying the service on a Get CloudJobSchedule call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobScheduleGetParameters, CloudJobScheduleGetResponse> request = (BatchRequest<CloudJobScheduleGetParameters, CloudJobScheduleGetResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudJobScheduleGetResponse response = BatchTestHelpers.CreateCloudJobScheduleGetResponse(cmdlet.Id); Task<CloudJobScheduleGetResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSCloudJobSchedule> pipeline = new List<PSCloudJobSchedule>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSCloudJobSchedule>())).Callback<object>(j => pipeline.Add((PSCloudJobSchedule)j)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the job schedule returned from the OM to the pipeline Assert.Equal(1, pipeline.Count); Assert.Equal(cmdlet.Id, pipeline[0].Id); }
public void TestAutoScaleParametersTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = null; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Id = "testPool"; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.AutoScaleFormula = "formula"; // Don't go to the service on an Evaluate AutoScale call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudPoolEvaluateAutoScaleParameters, CloudPoolEvaluateAutoScaleResponse> request = (BatchRequest<CloudPoolEvaluateAutoScaleParameters, CloudPoolEvaluateAutoScaleResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudPoolEvaluateAutoScaleResponse response = new CloudPoolEvaluateAutoScaleResponse(); Task<CloudPoolEvaluateAutoScaleResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameter is set cmdlet.ExecuteCmdlet(); }
public void RemoveBatchJobScheduleParametersTest() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; // Setup cmdlet to skip confirmation popup cmdlet.Force = true; commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true); Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Id = "testJobSchedule"; // Don't go to the service on a Delete CloudJobSchedule call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobScheduleDeleteParameters, CloudJobScheduleDeleteResponse> request = (BatchRequest<CloudJobScheduleDeleteParameters, CloudJobScheduleDeleteResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudJobScheduleDeleteResponse response = new CloudJobScheduleDeleteResponse(); Task<CloudJobScheduleDeleteResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameters are set cmdlet.ExecuteCmdlet(); }
public void ListTasksMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list tasks without filters and a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] idsOfConstructedTasks = new[] { "testTask1", "testTask2", "testTask3" }; // Build some CloudTasks instead of querying the service on a List CloudTasks call AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateCloudTaskListResponse(idsOfConstructedTasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())) .Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(idsOfConstructedTasks.Length, pipeline.Count); }
public void ListBatchSubtasksMaxCountTest() { // Verify default max count Assert.Equal(Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list Subtasks with a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.TaskId = "task1"; int maxCount = 2; cmdlet.MaxCount = maxCount; int[] idsOfConstructedSubtasks = new[] { 1, 2, 3 }; // Build some SubtaskInformation objects instead of querying the service on a List Subtasks call AzureOperationResponse <ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> response = BatchTestHelpers.CreateCloudTaskListSubtasksResponse(idsOfConstructedSubtasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListSubtasksOptions, AzureOperationResponse <ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSSubtaskInformation> pipeline = new List <PSSubtaskInformation>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSSubtaskInformation>())) .Callback <object>(s => pipeline.Add((PSSubtaskInformation)s)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(idsOfConstructedSubtasks.Length, pipeline.Count); }
/// <summary> /// Gets the CurrentDedicated count from a pool /// </summary> public static int GetPoolCurrentDedicated(BatchController controller, BatchAccountContext context, string poolId) { RequestInterceptor interceptor = CreateHttpRecordingInterceptor(); BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor }; BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient); ListPoolOptions options = new ListPoolOptions(context, behaviors) { PoolId = poolId }; PSCloudPool pool = client.ListPools(options).First(); return(pool.CurrentDedicated.Value); }
public async Task <NethereumContract> GetContract(RequestInterceptor inte, MetamaskService metamaskService) { if (contract == null) { var web3 = new Web3(); web3.Client.OverridingRequestInterceptor = inte; var address = await metamaskService.GetSelectedAccount(); contract = new NethereumContract(web3, Constants.ContractAddress, address); await contract.InitializeAsync(); } return(contract); }
public void SetBatchJobParametersGetPassedToRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Job = new PSCloudJob(BatchTestHelpers.CreateFakeBoundJob(context, new CloudJob(id: "testJob"))); // Update job cmdlet.Job.Constraints = new PSJobConstraints(TimeSpan.FromHours(1), 5); cmdlet.Job.PoolInformation = new PSPoolInformation() { PoolId = "myPool" }; cmdlet.Job.Priority = 2; cmdlet.Job.Metadata = new Dictionary <string, string>() { { "meta1", "value1" }, { "meta2", "value2" } }; JobUpdateParameter requestParameters = null; // Store the request parameters RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < JobUpdateParameter, JobUpdateOptions, AzureOperationHeaderResponse <JobUpdateHeaders> >(requestAction: (r) => { requestParameters = r.Parameters; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify the request parameters match the cmdlet parameters Assert.Equal(cmdlet.Job.Constraints.MaxTaskRetryCount, requestParameters.Constraints.MaxTaskRetryCount); Assert.Equal(cmdlet.Job.Constraints.MaxWallClockTime, requestParameters.Constraints.MaxWallClockTime); Assert.Equal(cmdlet.Job.PoolInformation.PoolId, requestParameters.PoolInfo.PoolId); Assert.Equal(cmdlet.Job.Priority, requestParameters.Priority); Assert.Equal(cmdlet.Job.Metadata.Count, requestParameters.Metadata.Count); Assert.Contains(requestParameters.Metadata, p => p.Name == "meta1" && p.Value == cmdlet.Job.Metadata["meta1"].ToString()); Assert.Contains(requestParameters.Metadata, p => p.Name == "meta2" && p.Value == cmdlet.Job.Metadata["meta2"].ToString()); }
public void ListNodeFilesByComputeNodeMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list vm files and a max count. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; cmdlet.Name = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] namesOfConstructedNodeFiles = new[] { "startup", "workitems", "shared" }; // Build some NodeFiles instead of querying the service on a List NodeFiles call NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(namesOfConstructedNodeFiles); RequestInterceptor interceptor = BatchTestHelpers.CreateNoOpInterceptor <NodeFileListParameters, NodeFileListResponse>(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSNodeFile> pipeline = new List <PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSNodeFile>())) .Callback <object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(namesOfConstructedNodeFiles.Length, pipeline.Count); }
public void ListBatchNodeFilesByComputeNodeWithoutFiltersTest() { // Setup cmdlet to list vm files without filters. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; cmdlet.Path = null; cmdlet.Filter = null; string[] namesOfConstructedNodeFiles = new[] { "startup", "workitems", "shared" }; // Build some NodeFiles instead of querying the service on a List NodeFiles call AzureOperationResponse <IPage <ProxyModels.NodeFile>, ProxyModels.FileListFromComputeNodeHeaders> response = BatchTestHelpers.CreateNodeFileListByComputeNodeResponse(namesOfConstructedNodeFiles); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < bool?, ProxyModels.FileListFromComputeNodeOptions, AzureOperationResponse <IPage <ProxyModels.NodeFile>, ProxyModels.FileListFromComputeNodeHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSNodeFile> pipeline = new List <PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSNodeFile>())) .Callback <object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed node files to the pipeline Assert.Equal(3, pipeline.Count); int taskCount = 0; foreach (PSNodeFile f in pipeline) { Assert.Contains(f.Path, namesOfConstructedNodeFiles); taskCount++; } Assert.Equal(namesOfConstructedNodeFiles.Length, taskCount); }
public void ListBatchNodeFilesByTaskByODataFilterTest() { // Setup cmdlet to list node files using an OData filter. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; cmdlet.Name = null; cmdlet.Filter = "startswith(name,'std')"; string[] namesOfConstructedNodeFiles = new[] { "stdout.txt", "stderr.txt" }; // Build some NodeFiles instead of querying the service on a List NodeFiles call AzureOperationResponse <IPage <ProxyModels.NodeFile>, ProxyModels.FileListFromTaskHeaders> response = BatchTestHelpers.CreateNodeFileListByTaskResponse(namesOfConstructedNodeFiles); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < bool?, ProxyModels.FileListFromTaskOptions, AzureOperationResponse <IPage <ProxyModels.NodeFile>, ProxyModels.FileListFromTaskHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSNodeFile> pipeline = new List <PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSNodeFile>())) .Callback <object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed node files to the pipeline Assert.Equal(2, pipeline.Count); int taskCount = 0; foreach (PSNodeFile f in pipeline) { Assert.True(namesOfConstructedNodeFiles.Contains(f.Name)); taskCount++; } Assert.Equal(namesOfConstructedNodeFiles.Length, taskCount); }
static void Main(string[] args) { try { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); myServerId = args[0]; Console.WriteLine($"ServerId: {myServerId}"); string[] protocolAndHostnameAndPort = args[1].Split("://"); string[] hotnameAndPort = protocolAndHostnameAndPort[1].Split(":"); int port = int.Parse(hotnameAndPort[1]); int minDelay = int.Parse(args[2]); int maxDelay = int.Parse(args[3]); ConnectionManager connectionManager = CreateServerConnectionManager(args[4]); GStore gStore = new GStore(connectionManager); connectionManager.AddGStore(gStore); Console.WriteLine(connectionManager); ManualResetEventSlim freezeLock = new ManualResetEventSlim(true); RequestInterceptor requestInterceptor = new RequestInterceptor(freezeLock, minDelay, maxDelay); Grpc.Core.Server server = new Grpc.Core.Server { Services = { GStoreService.BindService(new ServerServiceImpl(gStore)).Intercept(requestInterceptor), MasterReplicaService.BindService(new MasterReplicaServiceImpl(gStore)).Intercept(requestInterceptor), PuppetMasterServerService.BindService(new PuppetMasterServerServiceImpl(freezeLock, connectionManager)) }, Ports = { new ServerPort(hotnameAndPort[0], port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("GStore server listening on port " + port); Console.WriteLine("Press any key to stop the server..."); PressToExit(); Console.WriteLine("\nShutting down..."); server.ShutdownAsync().Wait(); } catch (Exception e) { Console.WriteLine(e); PressToExit(); } }
public void GetBatchNodeFileByTaskParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Name = null; cmdlet.Task = null; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a List NodeFile call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest <NodeFileListParameters, NodeFileListResponse> request = (BatchRequest <NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(new string[] { cmdlet.Name }); Task <NodeFileListResponse> task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Task = new PSCloudTask("task", "cmd /c dir /s"); // Verify that we don't get an argument exception. We should get an InvalidOperationException though since the task is unbound Assert.Throws <InvalidOperationException>(() => cmdlet.ExecuteCmdlet()); }
public void ListCertificatesMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list pools without filters and a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.ThumbprintAlgorithm = null; cmdlet.Thumbprint = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] thumbprintsOfConstructedCerts = new[] { "12345", "67890", "ABCDE" }; // Build some Certificates instead of querying the service on a List Certificates call CertificateListResponse response = BatchTestHelpers.CreateCertificateListResponse(thumbprintsOfConstructedCerts); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CertificateListParameters, CertificateListResponse>(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCertificate> pipeline = new List <PSCertificate>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCertificate>())) .Callback <object>(c => pipeline.Add((PSCertificate)c)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(thumbprintsOfConstructedCerts.Length, pipeline.Count); }
public void ListJobsMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list jobs without filters and a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobScheduleId = "jobSchedule"; cmdlet.Id = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] idsOfConstructedJobs = new[] { "job-1", "job-2", "job-3" }; // Build some CloudJobs instead of querying the service on a List CloudJobs call CloudJobListResponse response = BatchTestHelpers.CreateCloudJobListResponse(idsOfConstructedJobs); RequestInterceptor interceptor = BatchTestHelpers.CreateNoOpInterceptor <CloudJobListParameters, CloudJobListResponse>(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudJob> pipeline = new List <PSCloudJob>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudJob>())) .Callback <object>(j => pipeline.Add((PSCloudJob)j)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(idsOfConstructedJobs.Length, pipeline.Count); }
public void GetBatchNodeFileByteRangeSet_IsPopulatedInRequest(long?rangeStart, long?rangeEnd) { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Path = null; cmdlet.InputObject = null; cmdlet.DestinationPath = null; cmdlet.ByteRangeStart = rangeStart; cmdlet.ByteRangeEnd = rangeEnd; string fileName = "stdout.txt"; bool hit = false; // Don't go to the service on a Get NodeFile call or Get NodeFile Properties call RequestInterceptor interceptor = BatchTestHelpers.CreateFakeGetFileAndPropertiesFromTaskResponseInterceptor(cmdlet.Path); RequestInterceptor examiner = BatchTestHelpers.ExamineRequestInterceptor <FileGetFromTaskBatchRequest>(req => { hit = true; Assert.Equal($"bytes={cmdlet.ByteRangeStart}-{cmdlet.ByteRangeEnd}", req.Options.OcpRange); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior> { examiner, interceptor }; using (MemoryStream memStream = new MemoryStream()) { // Don't hit the file system during unit tests cmdlet.DestinationStream = memStream; Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet()); // Fill required task details cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; cmdlet.Path = fileName; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); Assert.True(hit); } }
/// <summary> /// Creates a test pool for use in Scenario tests. /// </summary> public static void CreateTestPool(BatchController controller, BatchAccountContext context, string poolId, int targetDedicated) { RequestInterceptor interceptor = CreateHttpRecordingInterceptor(); BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor }; BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient); NewPoolParameters parameters = new NewPoolParameters(context, poolId, behaviors) { VirtualMachineSize = "small", OSFamily = "4", TargetOSVersion = "*", TargetDedicated = targetDedicated, }; client.CreatePool(parameters); }
public void ListBatchComputeNodesWithoutFiltersTest() { // Setup cmdlet to list compute nodes without filters. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Id = null; cmdlet.Filter = null; string[] idsOfConstructedComputeNodes = new[] { "computeNode1", "computeNode2", "computeNode3" }; // Build some compute nodes instead of querying the service on a List ComputeNodes call AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> response = BatchTestHelpers.CreateComputeNodeListResponse(idsOfConstructedComputeNodes); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.ComputeNodeListOptions, AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSComputeNode> pipeline = new List <PSComputeNode>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSComputeNode>())) .Callback <object>(c => pipeline.Add((PSComputeNode)c)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed compute nodes to the pipeline Assert.Equal(3, pipeline.Count); int computeNodeCount = 0; foreach (PSComputeNode c in pipeline) { Assert.Contains(c.Id, idsOfConstructedComputeNodes); computeNodeCount++; } Assert.Equal(idsOfConstructedComputeNodes.Length, computeNodeCount); }
public void GetBatchRemoteDesktopProtocolFileParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = null; cmdlet.ComputeNodeId = null; cmdlet.ComputeNode = null; cmdlet.DestinationPath = null; // Don't go to the service on a Get ComputeNode Remote Desktop call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest <ComputeNodeGetRemoteDesktopParameters, ComputeNodeGetRemoteDesktopResponse> request = (BatchRequest <ComputeNodeGetRemoteDesktopParameters, ComputeNodeGetRemoteDesktopResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { ComputeNodeGetRemoteDesktopResponse response = new ComputeNodeGetRemoteDesktopResponse(); Task <ComputeNodeGetRemoteDesktopResponse> task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; using (MemoryStream memStream = new MemoryStream()) { // Don't hit the file system during unit tests cmdlet.DestinationStream = memStream; Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); // Fill required compute node details cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); } }
public void SetBatchJobScheduleParametersTest() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobSchedule = new PSCloudJobSchedule(BatchTestHelpers.CreateFakeBoundJobSchedule(context)); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CloudJobScheduleUpdateParameters, CloudJobScheduleUpdateResponse>(); cmdlet.AdditionalBehaviors = new BatchClientBehavior[] { interceptor }; // Verify that no exceptions occur cmdlet.ExecuteCmdlet(); }
public static IList <BatchClientBehavior> SimulateServiceResponse <TParameters, TOptions, TResponse>(Func <TParameters, TOptions, TResponse> simulator) where TOptions : IOptions, new() where TResponse : class, IAzureOperationResponse { var interceptor = new RequestInterceptor(baseRequest => { BatchRequest <TParameters, TOptions, TResponse> request = (BatchRequest <TParameters, TOptions, TResponse>)baseRequest; request.ServiceRequestFunc = token => { return(Task.FromResult(simulator(request.Parameters, request.Options))); }; }); return(new List <BatchClientBehavior> { interceptor }); }
/// <summary> /// Creates a test job for use in Scenario tests. /// </summary> public static void CreateTestJob(BatchController controller, BatchAccountContext context, string jobId) { RequestInterceptor interceptor = CreateHttpRecordingInterceptor(); BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor }; BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient); PSPoolInformation poolInfo = new PSPoolInformation(); poolInfo.PoolId = SharedPool; NewJobParameters parameters = new NewJobParameters(context, jobId, behaviors) { PoolInformation = poolInfo }; client.CreateJob(parameters); }
public void GetBatchTaskCountsTest() { // Setup cmdlet to get task counts by job id BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; const int requiredSlots = 2; const int active = 3; const int running = 5; const int succeeded = 2; const int failed = 1; // Build a TaskCounts instead of querying the service on a Get TaskCounts call AzureOperationResponse <ProxyModels.TaskCountsResult, ProxyModels.JobGetTaskCountsHeaders> response = BatchTestHelpers.CreateTaskCountsGetResponse(requiredSlots, active, running, succeeded, failed); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.JobGetTaskCountsOptions, AzureOperationResponse <ProxyModels.TaskCountsResult, ProxyModels.JobGetTaskCountsHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later PSTaskCounts taskCounts = null; commandRuntimeMock .Setup(r => r.WriteObject(It.IsAny <PSTaskCounts>())) .Callback <object>(p => { taskCounts = (PSTaskCounts)p; }); cmdlet.ExecuteCmdlet(); Assert.Equal(3, taskCounts.Active); Assert.Equal(5, taskCounts.Running); Assert.Equal(3, taskCounts.Completed); Assert.Equal(2, taskCounts.Succeeded); Assert.Equal(1, taskCounts.Failed); }
public void GetBatchComputeNodeExtensionTest() { string extensionName = "testExtension"; string publisher = "testPublisher"; string type = "testType"; // Setup cmdlet to get a compute node by id BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.ComputeNodeId = "testComputeNode"; cmdlet.Name = extensionName; VMExtension extension = new VMExtension(extensionName, publisher, type); // Build an extension instead of querying the service on a Get ComputeNodeExtension call AzureOperationResponse <ProxyModels.NodeVMExtension, ProxyModels.ComputeNodeExtensionGetHeaders> response = BatchTestHelpers.CreateComputeNodeExtensionGetResponse(extension); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.ComputeNodeExtensionGetOptions, AzureOperationResponse <ProxyModels.NodeVMExtension, ProxyModels.ComputeNodeExtensionGetHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSNodeVMExtension> pipeline = new List <PSNodeVMExtension>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSNodeVMExtension>())).Callback <object>(c => pipeline.Add((PSNodeVMExtension)c)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the compute node returned from the OM to the pipeline Assert.Single(pipeline); PSVMExtension pipelineExtension = pipeline[0].VmExtension; Assert.NotNull(pipelineExtension); Assert.Equal("testExtension", pipelineExtension.Name); Assert.Equal("testPublisher", pipelineExtension.Publisher); Assert.Equal("testType", pipelineExtension.Type); }
public void WhenGettingATaskFromTheService_ApplicationPackageReferencesAreMapped() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = "task-1"; cmdlet.JobId = "job-1"; cmdlet.Filter = null; // Build a CloudTask instead of querying the service on a Get CloudTask call string applicationId = "foo"; string applicationVersion = "beta"; ProxyModels.CloudTask cloudTask = new ProxyModels.CloudTask { Id = "task-1", ApplicationPackageReferences = new[] { new ProxyModels.ApplicationPackageReference(applicationId, applicationVersion) } }; AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(cloudTask); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <ProxyModels.TaskGetOptions, AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior> { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later var pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the task returned from the OM to the pipeline Assert.Single(pipeline); Assert.Equal(cmdlet.Id, pipeline[0].Id); var psApplicationPackageReference = pipeline[0].ApplicationPackageReferences.First(); Assert.Equal(applicationId, psApplicationPackageReference.ApplicationId); Assert.Equal(applicationVersion, psApplicationPackageReference.Version); }
public void ListBatchTasksODataTest() { // Setup cmdlet to list tasks using an OData filter BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "testJob"; cmdlet.Id = null; cmdlet.Filter = "startswith(id,'test')"; cmdlet.Select = "id,state"; cmdlet.Expand = "stats"; string requestFilter = null; string requestSelect = null; string requestExpand = null; AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateGenericAzureOperationListResponse <ProxyModels.CloudTask, ProxyModels.TaskListHeaders>(); Action <BatchRequest <ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> > > extractTaskListAction = (request) => { ProxyModels.TaskListOptions options = request.Options; requestFilter = options.Filter; requestSelect = options.Select; requestExpand = options.Expand; }; RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor(responseToUse: response, requestAction: extractTaskListAction); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor }; cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor }; cmdlet.ExecuteCmdlet(); Assert.Equal(cmdlet.Filter, requestFilter); Assert.Equal(cmdlet.Select, requestSelect); Assert.Equal(cmdlet.Expand, requestExpand); }
public void ListBatchSubtasksWithoutFiltersTest() { // Setup cmdlet to list Subtasks without filters. Use WorkItemName and JobName. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.TaskId = "task1"; int[] idsOfConstructedSubtasks = new[] { 1, 2, 3 }; // Build some SubtaskInformation objects instead of querying the service on a List Subtasks call AzureOperationResponse <ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> response = BatchTestHelpers.CreateCloudTaskListSubtasksResponse(idsOfConstructedSubtasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListSubtasksOptions, AzureOperationResponse <ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSSubtaskInformation> pipeline = new List <PSSubtaskInformation>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSSubtaskInformation>())) .Callback <object>(s => pipeline.Add((PSSubtaskInformation)s)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed Subtasks to the pipeline Assert.Equal(3, pipeline.Count); int SubtaskCount = 0; foreach (PSSubtaskInformation s in pipeline) { Assert.Contains(s.Id.Value, idsOfConstructedSubtasks); SubtaskCount++; } Assert.Equal(idsOfConstructedSubtasks.Length, SubtaskCount); }
public void ListBatchCertificatesWithoutFiltersTest() { // Setup cmdlet to list certs without filters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.ThumbprintAlgorithm = null; cmdlet.Thumbprint = null; cmdlet.Filter = null; string[] thumbprintsOfConstructedCerts = new[] { "12345", "67890", "ABCDE" }; // Build some Certificates instead of querying the service on a List Certificates call AzureOperationResponse <IPage <ProxyModels.Certificate>, ProxyModels.CertificateListHeaders> response = BatchTestHelpers.CreateCertificateListResponse(thumbprintsOfConstructedCerts); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.CertificateListOptions, AzureOperationResponse <IPage <ProxyModels.Certificate>, ProxyModels.CertificateListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCertificate> pipeline = new List <PSCertificate>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCertificate>())) .Callback <object>(c => pipeline.Add((PSCertificate)c)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed certs to the pipeline Assert.Equal(3, pipeline.Count); int poolCount = 0; foreach (PSCertificate c in pipeline) { Assert.True(thumbprintsOfConstructedCerts.Contains(c.Thumbprint)); poolCount++; } Assert.Equal(thumbprintsOfConstructedCerts.Length, poolCount); }
public void ApplicationPackageReferencesAreSentOnATask() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.Id = "task-id"; Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobId = "job-id"; string applicationId = "foo"; string applicationVersion = "beta"; cmdlet.ApplicationPackageReferences = new[] { new PSApplicationPackageReference { ApplicationId = applicationId, Version = applicationVersion }, }; // Don't go to the service on an Add CloudJob call RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <TaskAddParameter, TaskAddOptions, AzureOperationHeaderResponse <TaskAddHeaders> >( new AzureOperationHeaderResponse <TaskAddHeaders>(), request => { var applicationPackageReference = request.Parameters.ApplicationPackageReferences.First(); Assert.Equal(applicationId, applicationPackageReference.ApplicationId); Assert.Equal(applicationVersion, applicationPackageReference.Version); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameters are set cmdlet.ExecuteCmdlet(); }
public void OutputFilesAreSentToService() { // Setup cmdlet without the required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = "task-id"; cmdlet.JobId = "job-id"; const string pattern = @"**\*.txt"; const string containerUrl = "containerUrl"; const string path = "path"; const OutputFileUploadCondition uploadCondition = OutputFileUploadCondition.TaskCompletion; cmdlet.OutputFile = new[] { new PSOutputFile( pattern, new PSOutputFileDestination(new PSOutputFileBlobContainerDestination(containerUrl, path)), new PSOutputFileUploadOptions(uploadCondition)) }; // Don't go to the service on an Add CloudJob call RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <TaskAddParameter, TaskAddOptions, AzureOperationHeaderResponse <TaskAddHeaders> >( new AzureOperationHeaderResponse <TaskAddHeaders>(), request => { var outputFile = request.Parameters.OutputFiles.Single(); Assert.Equal(pattern, outputFile.FilePattern); Assert.Equal(containerUrl, outputFile.Destination.Container.ContainerUrl); Assert.Equal(path, outputFile.Destination.Container.Path); Assert.Equal(uploadCondition.ToString().ToLowerInvariant(), outputFile.UploadOptions.UploadCondition.ToString().ToLowerInvariant()); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Verify no exceptions when required parameters are set cmdlet.ExecuteCmdlet(); }
public void ListBatchTasksWithoutFiltersTest() { // Setup cmdlet to list tasks without filters. Use WorkItemName and JobName. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.Id = null; cmdlet.Filter = null; string[] idsOfConstructedTasks = new[] { "testTask1", "testTask2", "testTask3" }; // Build some CloudTasks instead of querying the service on a List CloudTasks call AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> response = BatchTestHelpers.CreateCloudTaskListResponse(idsOfConstructedTasks); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.TaskListOptions, AzureOperationResponse <IPage <ProxyModels.CloudTask>, ProxyModels.TaskListHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCloudTask> pipeline = new List <PSCloudTask>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())) .Callback <object>(t => pipeline.Add((PSCloudTask)t)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed tasks to the pipeline Assert.Equal(3, pipeline.Count); int taskCount = 0; foreach (PSCloudTask t in pipeline) { Assert.True(idsOfConstructedTasks.Contains(t.Id)); taskCount++; } Assert.Equal(idsOfConstructedTasks.Length, taskCount); }
/// <summary> /// Fabricates a CloudJob that's in the bound state /// </summary> public static CloudJob CreateFakeBoundJob(BatchAccountContext context, ProxyModels.CloudJob cloudJob) { RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { JobGetBatchRequest request = (JobGetBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationResponse <ProxyModels.CloudJob, ProxyModels.JobGetHeaders> { Body = cloudJob }; Task <AzureOperationResponse <ProxyModels.CloudJob, ProxyModels.JobGetHeaders> > task = Task.FromResult(response); return(task); }; }); return(context.BatchOMClient.JobOperations.GetJob(cloudJob.Id, additionalBehaviors: new BatchClientBehavior[] { interceptor })); }
public void GetBatchPoolUsageWithFilter() { int year = 2013; int month = 4; int day = 1; BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Filter = "poolId lt 'p2'"; string requestFilter = null; string[] poolIds = new[] { "p1" }; DateTime[] startTimes = new[] { new DateTime(year, month, day, 0, 0, 0) }; DateTime[] endTimes = new[] { new DateTime(year, month, day, 0, 30, 0) }; AzureOperationResponse <IPage <ProxyModels.PoolUsageMetrics>, ProxyModels.PoolListUsageMetricsHeaders> response = BatchTestHelpers.CreatePoolListUsageMetricsResponse(poolIds, startTimes, endTimes); // Don't go to the service on an Get PoolUsageMetrics call RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.PoolListUsageMetricsOptions, AzureOperationResponse <IPage <ProxyModels.PoolUsageMetrics>, ProxyModels.PoolListUsageMetricsHeaders> >(responseToUse: response); ResponseInterceptor responseInterceptor = new ResponseInterceptor((responseToUse, request) => { ProxyModels.PoolListUsageMetricsOptions options = (ProxyModels.PoolListUsageMetricsOptions)request.Options; requestFilter = options.Filter; return(Task.FromResult(responseToUse)); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor, responseInterceptor }; // Verify no exceptions when required parameter is set cmdlet.ExecuteCmdlet(); Assert.Equal(cmdlet.Filter, requestFilter); }
public void GetBatchNodeFileByTaskParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Name = null; cmdlet.Task = null; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a List NodeFile call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileListParameters, NodeFileListResponse> request = (BatchRequest<NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(new string[] {cmdlet.Name}); Task<NodeFileListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Task = new PSCloudTask("task", "cmd /c dir /s"); // Verify that we don't get an argument exception. We should get an InvalidOperationException though since the task is unbound Assert.Throws<InvalidOperationException>(() => cmdlet.ExecuteCmdlet()); }
public void GetBatchRemoteDesktopProtocolFileParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = null; cmdlet.ComputeNodeId = null; cmdlet.ComputeNode = null; cmdlet.DestinationPath = null; // Don't go to the service on a Get ComputeNode Remote Desktop call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<ComputeNodeGetRemoteDesktopParameters, ComputeNodeGetRemoteDesktopResponse> request = (BatchRequest<ComputeNodeGetRemoteDesktopParameters, ComputeNodeGetRemoteDesktopResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { ComputeNodeGetRemoteDesktopResponse response = new ComputeNodeGetRemoteDesktopResponse(); Task<ComputeNodeGetRemoteDesktopResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; using (MemoryStream memStream = new MemoryStream()) { // Don't hit the file system during unit tests cmdlet.DestinationStream = memStream; Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet()); // Fill required compute node details cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); } }
public void ListBatchNodeFilesByComputeNodeWithoutFiltersTest() { // Setup cmdlet to list vm files without filters. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; cmdlet.Name = null; cmdlet.Filter = null; string[] namesOfConstructedNodeFiles = new[] { "startup", "workitems", "shared" }; // Build some NodeFiles instead of querying the service on a List NodeFiles call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileListParameters, NodeFileListResponse> request = (BatchRequest<NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(namesOfConstructedNodeFiles); Task<NodeFileListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSNodeFile> pipeline = new List<PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSNodeFile>())) .Callback<object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed node files to the pipeline Assert.Equal(3, pipeline.Count); int taskCount = 0; foreach (PSNodeFile f in pipeline) { Assert.True(namesOfConstructedNodeFiles.Contains(f.Name)); taskCount++; } Assert.Equal(namesOfConstructedNodeFiles.Length, taskCount); }
public void ListJobSchedulesMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list job schedules without filters and a max count BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] idsOfConstructedJobSchedules = new[] { "id1", "id2", "id3" }; // Build some CloudJobSchedules instead of querying the service on a List CloudJobSchedules call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobScheduleListParameters, CloudJobScheduleListResponse> request = (BatchRequest<CloudJobScheduleListParameters, CloudJobScheduleListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudJobScheduleListResponse response = BatchTestHelpers.CreateCloudJobScheduleListResponse(idsOfConstructedJobSchedules); Task<CloudJobScheduleListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSCloudJobSchedule> pipeline = new List<PSCloudJobSchedule>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSCloudJobSchedule>())) .Callback<object>(j => pipeline.Add((PSCloudJobSchedule)j)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(idsOfConstructedJobSchedules.Length, pipeline.Count); }
public void NewBatchCertificateRequestBodyTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; X509Certificate2 cert = new X509Certificate2(BatchTestHelpers.TestCertificateFileName); string certDataBase64String = Convert.ToBase64String(cert.RawData); CertificateAddParameter requestParameters = null; // Don't go to the service on an Add Certificate call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { CertificateAddBatchRequest request = (CertificateAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse<CertificateAddHeaders>(); Task<AzureOperationHeaderResponse<CertificateAddHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify that when just the raw data is specified, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when the raw data is specified with a password, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when just a file path is specified, the request body matches expectations cmdlet.RawData = null; cmdlet.Password = null; cmdlet.FilePath = BatchTestHelpers.TestCertificateFileName; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when a file path is specified with a password, the request body matches expectations cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); }
public void GetBatchNodeFileByTaskParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = null; cmdlet.TaskId = null; cmdlet.Name = null; cmdlet.InputObject = null; cmdlet.DestinationPath = null; string fileName = "stdout.txt"; // Don't go to the service on a Get NodeFile call or Get NodeFile Properties call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileGetParameters, NodeFileGetResponse> fileRequest = baseRequest as BatchRequest<NodeFileGetParameters, NodeFileGetResponse>; if (fileRequest != null) { fileRequest.ServiceRequestFunc = (cancellationToken) => { NodeFileGetResponse response = new NodeFileGetResponse(); Task<NodeFileGetResponse> task = Task.FromResult(response); return task; }; } else { BatchRequest<NodeFileGetPropertiesParameters, NodeFileGetPropertiesResponse> propRequest = (BatchRequest<NodeFileGetPropertiesParameters, NodeFileGetPropertiesResponse>)baseRequest; propRequest.ServiceRequestFunc = (cancellationToken) => { NodeFileGetPropertiesResponse response = BatchTestHelpers.CreateNodeFileGetPropertiesResponse(cmdlet.Name); Task<NodeFileGetPropertiesResponse> task = Task.FromResult(response); return task; }; } }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; using (MemoryStream memStream = new MemoryStream()) { // Don't hit the file system during unit tests cmdlet.DestinationStream = memStream; Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); // Fill required task details cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; cmdlet.Name = fileName; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); } }
public void GetBatchNodeFileByComputeNodeParametersTest() { // Setup cmdlet without required parameters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = null; cmdlet.ComputeNodeId = null; cmdlet.Name = null; cmdlet.ComputeNode = null; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a List NodeFile call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileListParameters, NodeFileListResponse> request = (BatchRequest<NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(new string[] {cmdlet.Name}); Task<NodeFileListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; Assert.Throws<ArgumentException>(() => cmdlet.ExecuteCmdlet()); cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; // Verify no exceptions occur cmdlet.ExecuteCmdlet(); }
public void ResetComputeNodeRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.ReimageOption = BatchCommon.ComputeNodeReimageOption.Terminate; ComputeNodeReimageOption? requestReimageOption = null; // Don't go to the service on a Reimage ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeReimageBatchRequest request = (ComputeNodeReimageBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the reimage option from the outgoing request. requestReimageOption = request.Parameters; var response = new AzureOperationHeaderResponse<ComputeNodeReimageHeaders>(); Task<AzureOperationHeaderResponse<ComputeNodeReimageHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the reimage option was properly set on the outgoing request Assert.Equal(cmdlet.ReimageOption, BatchTestHelpers.MapEnum<BatchCommon.ComputeNodeReimageOption>(requestReimageOption)); }
public void GetBatchNodeFileByTaskTest() { // Setup cmdlet to get a Task file by name BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; cmdlet.Name = "stdout.txt"; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a Get NodeFile Properties call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileGetPropertiesParameters, NodeFileGetPropertiesResponse> request = (BatchRequest<NodeFileGetPropertiesParameters, NodeFileGetPropertiesResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileGetPropertiesResponse response = BatchTestHelpers.CreateNodeFileGetPropertiesResponse(cmdlet.Name); Task<NodeFileGetPropertiesResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSNodeFile> pipeline = new List<PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSNodeFile>())).Callback<object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the node file returned from the OM to the pipeline Assert.Equal(1, pipeline.Count); Assert.Equal(cmdlet.Name, pipeline[0].Name); }
public void RemoveComputeNodeRequestTest() { // Setup cmdlet to skip confirmation popup cmdlet.Force = true; commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true); BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Ids = new string[] { "computeNode1", "computeNode2" }; cmdlet.DeallocationOption = Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption.Terminate; cmdlet.ResizeTimeout = TimeSpan.FromMinutes(8); Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption? requestDeallocationOption = null; TimeSpan? requestResizeTimeout = null; IList<string> requestComputeNodeIds = null; // Don't go to the service on a Remove ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { PoolRemoveNodesBatchRequest request = (PoolRemoveNodesBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the parameters from the outgoing request. requestDeallocationOption = BatchTestHelpers.MapEnum<Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption>(request.Parameters.NodeDeallocationOption); requestResizeTimeout = request.Parameters.ResizeTimeout; requestComputeNodeIds = request.Parameters.NodeList; var response = new AzureOperationHeaderResponse<PoolRemoveNodesHeaders>(); Task<AzureOperationHeaderResponse<PoolRemoveNodesHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(cmdlet.DeallocationOption, requestDeallocationOption); Assert.Equal(cmdlet.ResizeTimeout, requestResizeTimeout); Assert.Equal(cmdlet.Ids.Length, requestComputeNodeIds.Count); foreach (string id in cmdlet.Ids) { Assert.True(requestComputeNodeIds.Contains(id)); } }
public void ExitConditionsAreSentToService() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; TaskAddParameter requestParameters = null; RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { TaskAddBatchRequest request = (TaskAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse<TaskAddHeaders>(); Task<AzureOperationHeaderResponse<TaskAddHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior> { interceptor }; var none = new PSExitOptions { omObject = new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.None } }; var terminate = new PSExitOptions { omObject = new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.Terminate } }; cmdlet.ExitConditions = new PSExitConditions { ExitCodes = new List<PSExitCodeMapping> { new PSExitCodeMapping(0, none) }, SchedulingError = terminate, ExitCodeRanges = new List<PSExitCodeRangeMapping> { new PSExitCodeRangeMapping(1, 5, terminate) }, Default = none, }; cmdlet.JobId = "job-Id"; cmdlet.Id = "task-id"; cmdlet.ExecuteCmdlet(); var exitConditions = requestParameters.ExitConditions; Assert.Equal(1, exitConditions.ExitCodeRanges.First().Start); Assert.Equal(5, exitConditions.ExitCodeRanges.First().End); Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.ExitCodeRanges.First().ExitOptions.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.ExitCodes.First().ExitOptions.JobAction); Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.SchedulingError.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.DefaultProperty.JobAction); }
public void ListBatchJobScheduleByODataFilterTest() { // Setup cmdlet to list job schedules using an OData filter BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = null; cmdlet.Filter = "startswith(id,'test')"; string[] idsOfConstructedJobSchedules = new[] { "test1", "test2" }; // Build some CloudJobSchedules instead of querying the service on a List CloudJobSchedules call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobScheduleListParameters, CloudJobScheduleListResponse> request = (BatchRequest<CloudJobScheduleListParameters, CloudJobScheduleListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudJobScheduleListResponse response = BatchTestHelpers.CreateCloudJobScheduleListResponse(idsOfConstructedJobSchedules); Task<CloudJobScheduleListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSCloudJobSchedule> pipeline = new List<PSCloudJobSchedule>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSCloudJobSchedule>())) .Callback<object>(j => pipeline.Add((PSCloudJobSchedule)j)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed job schedules to the pipeline Assert.Equal(2, pipeline.Count); int jobScheduleCount = 0; foreach (PSCloudJobSchedule j in pipeline) { Assert.True(idsOfConstructedJobSchedules.Contains(j.Id)); jobScheduleCount++; } Assert.Equal(idsOfConstructedJobSchedules.Length, jobScheduleCount); }
public void ListNodeFilesByComputeNodeMaxCountTest() { // Verify default max count Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount); // Setup cmdlet to list vm files and a max count. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "pool"; cmdlet.ComputeNodeId = "computeNode1"; cmdlet.Name = null; cmdlet.Filter = null; int maxCount = 2; cmdlet.MaxCount = maxCount; string[] namesOfConstructedNodeFiles = new[] { "startup", "workitems", "shared" }; // Build some NodeFiles instead of querying the service on a List NodeFiles call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<NodeFileListParameters, NodeFileListResponse> request = (BatchRequest<NodeFileListParameters, NodeFileListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { NodeFileListResponse response = BatchTestHelpers.CreateNodeFileListResponse(namesOfConstructedNodeFiles); Task<NodeFileListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSNodeFile> pipeline = new List<PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSNodeFile>())) .Callback<object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the max count was respected Assert.Equal(maxCount, pipeline.Count); // Verify setting max count <= 0 doesn't return nothing cmdlet.MaxCount = -5; pipeline.Clear(); cmdlet.ExecuteCmdlet(); Assert.Equal(namesOfConstructedNodeFiles.Length, pipeline.Count); }
/// <summary> /// Creates an interceptor that can be used to support the HTTP recorder scenario tests. /// This behavior grabs the outgoing Protocol request, converts it to an HttpRequestMessage compatible with the /// HTTP recorder, sends the request through the HTTP recorder, and converts the response to an HttpWebResponse /// for serialization by the Protocol Layer. /// NOTE: This is a temporary behavior that should no longer be needed when the Batch OM switches to Hyak. /// </summary> public static RequestInterceptor CreateHttpRecordingInterceptor() { RequestInterceptor interceptor = new RequestInterceptor((batchRequest) => { // Setup HTTP recorder HttpMockServer mockServer = HttpMockServer.CreateInstance(); mockServer.InnerHandler = new HttpClientHandler(); batchRequest.RestClient.AddHandlerToPipeline(mockServer); }); return interceptor; }
// TO DO: Since we have to fetch the task, the interceptor needs to handle that case too. Once // the cmdlet can directly call the List Subtasks method by itself, update these test cases to // use the generic interceptor creation helper. private RequestInterceptor CreateFakeListSubtasksInterceptor(string taskId, CloudTaskListSubtasksResponse listSubtasksResponse) { RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudTaskListSubtasksParameters, CloudTaskListSubtasksResponse> listSubtaskRequest = baseRequest as BatchRequest<CloudTaskListSubtasksParameters, CloudTaskListSubtasksResponse>; if (listSubtaskRequest != null) { listSubtaskRequest.ServiceRequestFunc = (cancellationToken) => { Task<CloudTaskListSubtasksResponse> task = Task.FromResult(listSubtasksResponse); return task; }; } else { BatchRequest<CloudTaskGetParameters, CloudTaskGetResponse> getTaskRequest = (BatchRequest<CloudTaskGetParameters, CloudTaskGetResponse>)baseRequest; getTaskRequest.ServiceRequestFunc = (cancellationToken) => { CloudTaskGetResponse response = BatchTestHelpers.CreateCloudTaskGetResponse(taskId); Task<CloudTaskGetResponse> task = Task.FromResult(response); return task; }; } }); return interceptor; }
public void DisableJobRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; DisableJobOption disableOption = DisableJobOption.Terminate; DisableJobOption requestDisableOption = DisableJobOption.Requeue; cmdlet.Id = "testJob"; cmdlet.DisableJobOption = disableOption; // Don't go to the service on an Enable AutoScale call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudJobDisableParameters, CloudJobDisableResponse> request = (BatchRequest<CloudJobDisableParameters, CloudJobDisableResponse>)baseRequest; requestDisableOption = request.TypedParameters.DisableJobOption; request.ServiceRequestFunc = (cancellationToken) => { CloudJobDisableResponse response = new CloudJobDisableResponse(); Task<CloudJobDisableResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the job disable option was properly set on the outgoing request Assert.Equal(disableOption, requestDisableOption); }
// TO DO: Since we have to fetch the task, the interceptor needs to handle that case too. Once // the cmdlet can directly call the List Subtasks method by itself, update these test cases to // use the generic interceptor creation helper. private RequestInterceptor CreateFakeListSubtasksInterceptor( string taskId, AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders> listSubtasksResponse) { RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { TaskListSubtasksBatchRequest listSubtaskRequest = baseRequest as TaskListSubtasksBatchRequest; if (listSubtaskRequest != null) { listSubtaskRequest.ServiceRequestFunc = (cancellationToken) => { Task<AzureOperationResponse<ProxyModels.CloudTaskListSubtasksResult, ProxyModels.TaskListSubtasksHeaders>> task = Task.FromResult(listSubtasksResponse); return task; }; } else { TaskGetBatchRequest getTaskRequest = (TaskGetBatchRequest)baseRequest; getTaskRequest.ServiceRequestFunc = (cancellationToken) => { AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(taskId); Task<AzureOperationResponse<ProxyModels.CloudTask, ProxyModels.TaskGetHeaders>> task = Task.FromResult(response); return task; }; } }); return interceptor; }
public void DisableComputeNodeSchedulingRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; BatchCommon.DisableComputeNodeSchedulingOption? disableOption = BatchCommon.DisableComputeNodeSchedulingOption.TaskCompletion; BatchCommon.DisableComputeNodeSchedulingOption? requestDisableOption = null; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.DisableSchedulingOption = disableOption; // Don't go to the service on an Disable Compute Node Scheduling call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeDisableSchedulingBatchRequest request = (ComputeNodeDisableSchedulingBatchRequest)baseRequest; requestDisableOption = BatchTestHelpers.MapEnum<BatchCommon.DisableComputeNodeSchedulingOption>(request.Parameters); request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse<ComputeNodeDisableSchedulingHeaders>(); Task<AzureOperationHeaderResponse<ComputeNodeDisableSchedulingHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(disableOption, requestDisableOption); }
public void RestartComputeNodeRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.RebootOption = ComputeNodeRebootOption.Terminate; ComputeNodeRebootOption? requestRebootOption = null; // Don't go to the service on a Reboot ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<ComputeNodeRebootParameters, ComputeNodeRebootResponse> request = (BatchRequest<ComputeNodeRebootParameters, ComputeNodeRebootResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the reboot option from the outgoing request. requestRebootOption = request.TypedParameters.ComputeNodeRebootOption; ComputeNodeRebootResponse response = new ComputeNodeRebootResponse(); Task<ComputeNodeRebootResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the reboot option was properly set on the outgoing request Assert.Equal(cmdlet.RebootOption, requestRebootOption); }
public void TestAutoScaleRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; string formula = "$TargetDedicated=2"; string requestFormula = null; cmdlet.Id = "testPool"; cmdlet.AutoScaleFormula = formula; // Don't go to the service on an Evaluate AutoScale call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudPoolEvaluateAutoScaleParameters, CloudPoolEvaluateAutoScaleResponse> request = (BatchRequest<CloudPoolEvaluateAutoScaleParameters, CloudPoolEvaluateAutoScaleResponse>)baseRequest; requestFormula = request.TypedParameters.AutoScaleFormula; request.ServiceRequestFunc = (cancellationToken) => { CloudPoolEvaluateAutoScaleResponse response = new CloudPoolEvaluateAutoScaleResponse(); Task<CloudPoolEvaluateAutoScaleResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the autoscale formula was properly set on the outgoing request Assert.Equal(formula, requestFormula); }
public void SetPoolOSVersionRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; string targetOS = "targetOS"; string requestTargetOS = null; cmdlet.Id = "testPool"; cmdlet.TargetOSVersion = targetOS; // Don't go to the service on an Upgrade OS call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudPoolUpgradeOSParameters, CloudPoolUpgradeOSResponse> request = (BatchRequest<CloudPoolUpgradeOSParameters, CloudPoolUpgradeOSResponse>)baseRequest; // Grab the target OS version off the outgoing request requestTargetOS = request.TypedParameters.TargetOSVersion; request.ServiceRequestFunc = (cancellationToken) => { CloudPoolUpgradeOSResponse response = new CloudPoolUpgradeOSResponse(); Task<CloudPoolUpgradeOSResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the target OS was properly set on the outgoing request Assert.Equal(targetOS, requestTargetOS); }
public void ListBatchPoolWithoutFiltersTest() { // Setup cmdlet to list pools without filters BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.Id = null; cmdlet.Filter = null; string[] idsOfConstructedPools = new[] { "pool1", "pool2", "pool3" }; // Build some CloudPools instead of querying the service on a List CloudPools call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<CloudPoolListParameters, CloudPoolListResponse> request = (BatchRequest<CloudPoolListParameters, CloudPoolListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { CloudPoolListResponse response = BatchTestHelpers.CreateCloudPoolListResponse(idsOfConstructedPools); Task<CloudPoolListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSCloudPool> pipeline = new List<PSCloudPool>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSCloudPool>())) .Callback<object>(p => pipeline.Add((PSCloudPool)p)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed pools to the pipeline Assert.Equal(3, pipeline.Count); int poolCount = 0; foreach (PSCloudPool p in pipeline) { Assert.True(idsOfConstructedPools.Contains(p.Id)); poolCount++; } Assert.Equal(idsOfConstructedPools.Length, poolCount); }
public void ListBatchComputeNodesByODataFilterTest() { // Setup cmdlet to list vms using an OData filter. BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "pool"; cmdlet.Id = null; cmdlet.Filter = "state -eq 'idle'"; string[] idsOfConstructedComputeNodes = new[] { "computeNode1", "computeNode2" }; // Build some compute nodes instead of querying the service on a List ComputeNodes call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { BatchRequest<ComputeNodeListParameters, ComputeNodeListResponse> request = (BatchRequest<ComputeNodeListParameters, ComputeNodeListResponse>)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { ComputeNodeListResponse response = BatchTestHelpers.CreateComputeNodeListResponse(idsOfConstructedComputeNodes); Task<ComputeNodeListResponse> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List<PSComputeNode> pipeline = new List<PSComputeNode>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSComputeNode>())) .Callback<object>(c => pipeline.Add((PSComputeNode)c)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the constructed compute nodes to the pipeline Assert.Equal(2, pipeline.Count); int computeNodeCount = 0; foreach (PSComputeNode c in pipeline) { Assert.True(idsOfConstructedComputeNodes.Contains(c.Id)); computeNodeCount++; } Assert.Equal(idsOfConstructedComputeNodes.Length, computeNodeCount); }