public void GetBatchVMTest()
        {
            // Setup cmdlet to get a vm by name
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.PoolName = "pool";
            cmdlet.Name = "vm1";
            cmdlet.Filter = null;

            // Build a vm instead of querying the service on a GetTVM call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTVMRequest)
                {
                    GetTVMResponse response = BatchTestHelpers.CreateGetTVMResponse(cmdlet.Name);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSVM> pipeline = new List<PSVM>();
            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSVM>())).Callback<object>(v => pipeline.Add((PSVM)v));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the vm returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Name, pipeline[0].Name);
        }
        public void NewBatchVMUserParametersTest()
        {
            // Setup cmdlet without the required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;

            Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.PoolName = "testPool";
            cmdlet.VMName = "vm1";
            cmdlet.Name = "testUser";

            // Don't go to the service on an AddTVMUser call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is AddTVMUserRequest)
                {
                    AddTVMUserResponse response = new AddTVMUserResponse();
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
        public void StartPoolResizeParametersTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.Name = null;

            Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.Name = "testPool";

            // Don't go to the service on a ResizePool call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ResizePoolRequest)
                {
                    ResizePoolResponse response = new ResizePoolResponse();
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Verify no exceptions when required parameter is set
            cmdlet.ExecuteCmdlet();
        }
        /// <summary>
        /// Waits for a recent job on a workitem and returns its name. If a previous job is specified, this method waits until a new job is created.
        /// </summary>
        public static string WaitForRecentJob(BatchController controller, BatchAccountContext context, string workItemName, string previousJob = null)
        {
            DateTime timeout = DateTime.Now.AddMinutes(2);

            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListWorkItemOptions options = new ListWorkItemOptions(context, behaviors)
            {
                WorkItemName = workItemName,
                Filter       = null,
                MaxCount     = Constants.DefaultMaxCount
            };
            PSCloudWorkItem workItem = client.ListWorkItems(options).First();

            while (workItem.ExecutionInformation.RecentJob == null || string.Equals(workItem.ExecutionInformation.RecentJob.Name, previousJob, StringComparison.OrdinalIgnoreCase))
            {
                if (DateTime.Now > timeout)
                {
                    throw new TimeoutException("Timed out waiting for recent job");
                }
                Sleep(5000);
                workItem = client.ListWorkItems(options).First();
            }
            return(workItem.ExecutionInformation.RecentJob.Name);
        }
        public void RemoveBatchUserParametersTest()
        {
            // 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.PoolName = "testPool";
            cmdlet.VMName = "vm1";
            cmdlet.Name = "testUser";

            // Don't go to the service on a DeleteTVMUser call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is DeleteTVMUserRequest)
                {
                    DeleteTVMUserResponse response = new DeleteTVMUserResponse();
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
예제 #6
0
        public void StartPoolResizeParametersTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Name         = null;

            Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.Name = "testPool";

            // Don't go to the service on a ResizePool call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ResizePoolRequest)
                {
                    ResizePoolResponse response = new ResizePoolResponse();
                    Task <object> task          = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Verify no exceptions when required parameter is set
            cmdlet.ExecuteCmdlet();
        }
        /// <summary>
        /// Creates a test workitem for use in Scenario tests.
        /// </summary>
        public static void CreateTestWorkItem(BatchController controller, BatchAccountContext context, string workItemName, TimeSpan?recurrenceInterval)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            PSJobExecutionEnvironment jobExecutionEnvironment = new PSJobExecutionEnvironment();

            jobExecutionEnvironment.PoolName = DefaultPoolName;
            PSWorkItemSchedule schedule = null;

            if (recurrenceInterval != null)
            {
                schedule = new PSWorkItemSchedule();
                schedule.RecurrenceInterval = recurrenceInterval;
            }

            NewWorkItemParameters parameters = new NewWorkItemParameters(context, workItemName, behaviors)
            {
                JobExecutionEnvironment = jobExecutionEnvironment,
                Schedule = schedule
            };

            client.CreateWorkItem(parameters);
        }
예제 #8
0
        public static void WaitForSteadyPoolAllocation(BatchController controller, BatchAccountContext context, string poolName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListPoolOptions options = new ListPoolOptions(context, behaviors)
            {
                PoolName = poolName
            };

            DateTime    timeout = DateTime.Now.AddMinutes(2);
            PSCloudPool pool    = client.ListPools(options).First();

            while (pool.AllocationState != AllocationState.Steady)
            {
                if (DateTime.Now > timeout)
                {
                    throw new TimeoutException("Timed out waiting for steady allocation state");
                }
                Sleep(5000);
                pool = client.ListPools(options).First();
            }
        }
예제 #9
0
        public void RemoveBatchPoolParametersTest()
        {
            // 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.Name = "testPool";

            // Don't go to the service on a DeletePool call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is DeletePoolRequest)
                {
                    DeletePoolResponse response = new DeletePoolResponse();
                    Task <object> task          = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
예제 #10
0
        public void NewBatchVMUserParametersTest()
        {
            // Setup cmdlet without the required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.PoolName = "testPool";
            cmdlet.VMName   = "vm1";
            cmdlet.Name     = "testUser";

            // Don't go to the service on an AddTVMUser call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is AddTVMUserRequest)
                {
                    AddTVMUserResponse response = new AddTVMUserResponse();
                    Task <object> task          = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
        public void GetBatchVMFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.PoolName = null;
            cmdlet.VMName = null;
            cmdlet.Name = null;
            cmdlet.VM = null;
            cmdlet.Filter = null;

            // Build some vm files instead of querying the service on a ListTVMFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMFilesRequest)
                {
                    ListTVMFilesResponse response = BatchTestHelpers.CreateListTVMFilesResponse(new string[] { "startup\\stdout.txt" });
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.PoolName = "pool";
            cmdlet.VMName = "vm1";

            // Verify no exceptions occur
            cmdlet.ExecuteCmdlet();
        }
예제 #12
0
        /// <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 YieldInjectionInterceptor CreateHttpRecordingInterceptor()
        {
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, batchRequest) =>
            {
                Task <object> task = Task <object> .Factory.StartNew(() =>
                {
                    object batchResponse = null;

                    Delegate postProcessDelegate = null;
                    HttpRequestMessage request   = GenerateHttpRequest((BatchRequest)batchRequest);

                    // Setup HTTP recorder and send the request
                    HttpMockServer mockServer = HttpMockServer.CreateInstance();
                    mockServer.InnerHandler   = new HttpClientHandler();
                    HttpClient client         = new HttpClient(mockServer);
                    Task <HttpResponseMessage> responseTask = client.SendAsync(request);
                    responseTask.Wait();
                    HttpResponseMessage response = responseTask.Result;

                    Task <Stream> getContentTask = response.Content.ReadAsStreamAsync();
                    getContentTask.Wait();
                    Stream body = getContentTask.Result;

                    HttpWebResponse webResponse = ConvertResponseMessageToWebResponse(response);

                    batchResponse = GenerateBatchResponse((BatchRequest)batchRequest, webResponse, body);

                    return(batchResponse);
                });
                return(task);
            });

            return(interceptor);
        }
        public void GetBatchTaskFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext    = context;
            cmdlet.WorkItemName    = null;
            cmdlet.JobName         = null;
            cmdlet.TaskName        = null;
            cmdlet.Name            = null;
            cmdlet.InputObject     = null;
            cmdlet.DestinationPath = null;

            string fileName = "stdout.txt";

            // Don't hit the file system during unit tests
            cmdlet.Stream = new MemoryStream();

            // Don't go to the service on a GetTaskFile call or GetTaskFileProperties call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTaskFilePropertiesRequest)
                {
                    GetTaskFilePropertiesResponse response = BatchTestHelpers.CreateGetTaskFilePropertiesResponse(fileName);
                    Task <object> task = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                if (request is GetTaskFileRequest)
                {
                    GetTaskFileResponse response = new GetTaskFileResponse();
                    Task <object> task           = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            // Fill required Task file details
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName      = "job-0000000001";
            cmdlet.TaskName     = "task";
            cmdlet.Name         = fileName;

            try
            {
                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
            finally
            {
                cmdlet.Stream.Dispose();
            }
        }
예제 #14
0
        /// <summary>
        /// Deletes a workitem used in a Scenario test.
        /// </summary>
        public static void DeleteWorkItem(BatchController controller, BatchAccountContext context, string workItemName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            client.DeleteWorkItem(context, workItemName, behaviors);
        }
        public void ListTaskFilesMaxCountTest()
        {
            // Verify default max count
            Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount);

            // Setup cmdlet to list Task files and a max count.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName      = "job-0000000001";
            cmdlet.TaskName     = "task";
            cmdlet.Name         = null;
            cmdlet.Filter       = null;
            int maxCount = 2;

            cmdlet.MaxCount = maxCount;

            string[] namesOfConstructedTaskFiles = new[] { "stdout.txt", "stderr.txt", "wd" };

            // Build some Task files instead of querying the service on a ListTaskFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTaskFilesRequest)
                {
                    ListTaskFilesResponse response = BatchTestHelpers.CreateListTaskFilesResponse(namesOfConstructedTaskFiles);
                    Task <object> task             = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSTaskFile> pipeline = new List <PSTaskFile>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSTaskFile>()))
            .Callback <object>(t => pipeline.Add((PSTaskFile)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(namesOfConstructedTaskFiles.Length, pipeline.Count);
        }
예제 #16
0
        /// <summary>
        /// Deletes a user used in a Scenario test.
        /// </summary>
        public static void DeleteUser(BatchController controller, BatchAccountContext context, string poolName, string vmName, string vmUserName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            VMUserOperationParameters parameters = new VMUserOperationParameters(context, poolName, vmName, vmUserName, behaviors);

            client.DeleteVMUser(parameters);
        }
예제 #17
0
        /// <summary>
        /// Gets the number of pools under the specified account
        /// </summary>
        public static int GetPoolCount(BatchController controller, BatchAccountContext context)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListPoolOptions options = new ListPoolOptions(context, behaviors);

            return(client.ListPools(options).Count());
        }
        public void ListBatchTaskFilesWithoutFiltersTest()
        {
            // Setup cmdlet to list Task files without filters.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName      = "job-0000000001";
            cmdlet.TaskName     = "task";
            cmdlet.Name         = null;
            cmdlet.Filter       = null;

            string[] namesOfConstructedTaskFiles = new[] { "stdout.txt", "stderr.txt", "wd" };

            // Build some Task files instead of querying the service on a ListTaskFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTaskFilesRequest)
                {
                    ListTaskFilesResponse response = BatchTestHelpers.CreateListTaskFilesResponse(namesOfConstructedTaskFiles);
                    Task <object> task             = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSTaskFile> pipeline = new List <PSTaskFile>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSTaskFile>()))
            .Callback <object>(t => pipeline.Add((PSTaskFile)t));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed Task files to the pipeline
            Assert.Equal(3, pipeline.Count);
            int taskCount = 0;

            foreach (PSTaskFile f in pipeline)
            {
                Assert.True(namesOfConstructedTaskFiles.Contains(f.Name));
                taskCount++;
            }
            Assert.Equal(namesOfConstructedTaskFiles.Length, taskCount);
        }
        public void GetBatchTaskFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = null;
            cmdlet.JobName = null;
            cmdlet.TaskName = null;
            cmdlet.Name = null;
            cmdlet.InputObject = null;
            cmdlet.DestinationPath = null;

            string fileName = "stdout.txt";

            // Don't go to the service on a GetTaskFile call or GetTaskFileProperties call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTaskFilePropertiesRequest)
                {
                    GetTaskFilePropertiesResponse response = BatchTestHelpers.CreateGetTaskFilePropertiesResponse(fileName);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                if (request is GetTaskFileRequest)
                {
                    GetTaskFileResponse response = new GetTaskFileResponse();
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            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 Task file details
                cmdlet.WorkItemName = "workItem";
                cmdlet.JobName = "job-0000000001";
                cmdlet.TaskName = "task";
                cmdlet.Name = fileName;

                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
        }
예제 #20
0
        public void ListBatchVMFilesByODataFilterTest()
        {
            // Setup cmdlet to list vm files using an OData filter.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.PoolName     = "pool";
            cmdlet.VMName       = "vm1";
            cmdlet.Name         = null;
            cmdlet.Filter       = "startswith(name,'startup')";

            string[] namesOfConstructedVMFiles = new[] { "startup\\stdout.txt", "startup\\stderr.txt" };

            // Build some vm files instead of querying the service on a ListTVMFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMFilesRequest)
                {
                    ListTVMFilesResponse response = BatchTestHelpers.CreateListTVMFilesResponse(namesOfConstructedVMFiles);
                    Task <object> task            = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSVMFile> pipeline = new List <PSVMFile>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSVMFile>()))
            .Callback <object>(f => pipeline.Add((PSVMFile)f));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed vm files to the pipeline
            Assert.Equal(2, pipeline.Count);
            int taskCount = 0;

            foreach (PSVMFile f in pipeline)
            {
                Assert.True(namesOfConstructedVMFiles.Contains(f.Name));
                taskCount++;
            }
            Assert.Equal(namesOfConstructedVMFiles.Length, taskCount);
        }
예제 #21
0
        public void ListBatchJobsByODataFilterTest()
        {
            // Setup cmdlet to list Jobs using an OData filter. Use WorkItemName input.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.Name         = null;
            cmdlet.Filter       = "state -eq 'active'";

            string[] namesOfConstructedJobs = new[] { "job-0000000001", "job-0000000002" };

            // Build some Jobs instead of querying the service on a ListJobs call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListJobsRequest)
                {
                    ListJobsResponse response = BatchTestHelpers.CreateListJobsResponse(namesOfConstructedJobs);
                    Task <object> task        = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            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 cmdlet wrote the constructed Jobs to the pipeline
            Assert.Equal(2, pipeline.Count);
            int jobCount = 0;

            foreach (PSCloudJob j in pipeline)
            {
                Assert.True(namesOfConstructedJobs.Contains(j.Name));
                jobCount++;
            }
            Assert.Equal(namesOfConstructedJobs.Length, jobCount);
        }
        public void ListBatchVMsWithoutFiltersTest()
        {
            // Setup cmdlet to list vms without filters.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Pool         = BatchTestHelpers.CreatePSCloudPool();
            cmdlet.Name         = null;
            cmdlet.Filter       = null;

            string[] namesOfConstructedVMs = new[] { "vm1", "vm2", "vm3" };

            // Build some vms instead of querying the service on a ListTVMs call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMsRequest)
                {
                    ListTVMsResponse response = BatchTestHelpers.CreateListTVMsResponse(namesOfConstructedVMs);
                    Task <object> task        = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSVM> pipeline = new List <PSVM>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSVM>()))
            .Callback <object>(v => pipeline.Add((PSVM)v));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed vms to the pipeline
            Assert.Equal(3, pipeline.Count);
            int vmCount = 0;

            foreach (PSVM v in pipeline)
            {
                Assert.True(namesOfConstructedVMs.Contains(v.Name));
                vmCount++;
            }
            Assert.Equal(namesOfConstructedVMs.Length, vmCount);
        }
예제 #23
0
        /// <summary>
        /// Creates a test user for use in Scenario tests.
        /// </summary>
        public static void CreateTestUser(BatchController controller, BatchAccountContext context, string poolName, string vmName, string vmUserName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            NewVMUserParameters parameters = new NewVMUserParameters(context, poolName, vmName, null, behaviors)
            {
                VMUserName = vmUserName,
                Password   = "******",
            };

            client.CreateVMUser(parameters);
        }
예제 #24
0
        /// <summary>
        /// Creates a test task for use in Scenario tests.
        /// </summary>
        public static void CreateTestTask(BatchController controller, BatchAccountContext context, string workItemName, string jobName, string taskName, string cmdLine = "cmd /c dir /s")
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            NewTaskParameters parameters = new NewTaskParameters(context, workItemName, jobName, null, taskName, behaviors)
            {
                CommandLine = cmdLine,
                RunElevated = true
            };

            client.CreateTask(parameters);
        }
        public void ListBatchWorkItemByODataFilterTest()
        {
            // Setup cmdlet to list WorkItems using an OData filter
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Name         = null;
            cmdlet.Filter       = "startswith(name,'test')";

            string[] namesOfConstructedWorkItems = new[] { "test1", "test2" };

            // Build some WorkItems instead of querying the service on a ListWorkItems call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListWorkItemsRequest)
                {
                    ListWorkItemsResponse response = BatchTestHelpers.CreateListWorkItemsResponse(namesOfConstructedWorkItems);
                    Task <object> task             = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSCloudWorkItem> pipeline = new List <PSCloudWorkItem>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSCloudWorkItem>()))
            .Callback <object>(w => pipeline.Add((PSCloudWorkItem)w));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed WorkItems to the pipeline
            Assert.Equal(2, pipeline.Count);
            int workItemCount = 0;

            foreach (PSCloudWorkItem w in pipeline)
            {
                Assert.True(namesOfConstructedWorkItems.Contains(w.Name));
                workItemCount++;
            }
            Assert.Equal(namesOfConstructedWorkItems.Length, workItemCount);
        }
예제 #26
0
        /// <summary>
        /// Creates a test pool for use in Scenario tests.
        /// </summary>
        public static void CreateTestPool(BatchController controller, BatchAccountContext context, string poolName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            NewPoolParameters parameters = new NewPoolParameters(context, poolName, behaviors)
            {
                OSFamily        = "4",
                TargetOSVersion = "*",
                TargetDedicated = 1
            };

            client.CreatePool(parameters);
        }
예제 #27
0
        /// <summary>
        /// Gets the CurrentDedicated count from a pool
        /// </summary>
        public static int GetPoolCurrentDedicated(BatchController controller, BatchAccountContext context, string poolName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListPoolOptions options = new ListPoolOptions(context, behaviors)
            {
                PoolName = poolName
            };

            PSCloudPool pool = client.ListPools(options).First();

            return(pool.CurrentDedicated.Value);
        }
        public void GetBatchTaskFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = null;
            cmdlet.JobName      = null;
            cmdlet.TaskName     = null;
            cmdlet.Name         = null;
            cmdlet.Task         = null;
            cmdlet.Filter       = null;

            // Build some Task files instead of querying the service on a ListTaskFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTaskFilesRequest)
                {
                    ListTaskFilesResponse response = BatchTestHelpers.CreateListTaskFilesResponse(new string[] { "stdout.txt" });
                    Task <object> task             = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName      = "job-0000000001";
            cmdlet.TaskName     = "task";

            // Verify no exceptions occur
            cmdlet.ExecuteCmdlet();

            cmdlet.WorkItemName = null;
            cmdlet.JobName      = null;
            cmdlet.TaskName     = 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());
        }
예제 #29
0
        /// <summary>
        /// Waits for the specified task to complete
        /// </summary>
        public static void WaitForTaskCompletion(BatchController controller, BatchAccountContext context, string workItemName, string jobName, string taskName)
        {
            YieldInjectionInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListTaskOptions options = new ListTaskOptions(context, workItemName, jobName, null, behaviors)
            {
                TaskName = taskName
            };
            IEnumerable <PSCloudTask> tasks = client.ListTasks(options);

            ITaskStateMonitor monitor = context.BatchOMClient.OpenToolbox().CreateTaskStateMonitor();

            monitor.WaitAll(tasks.Select(t => t.omObject), TaskState.Completed, TimeSpan.FromMinutes(2), null, behaviors);
        }
        public void GetBatchRDPFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext    = context;
            cmdlet.PoolName        = null;
            cmdlet.VMName          = null;
            cmdlet.VM              = null;
            cmdlet.DestinationPath = null;

            // Don't go to the service on a GetTVMRDPFile call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTVMRDPFileRequest)
                {
                    GetTVMRDPFileResponse response = new GetTVMRDPFileResponse();
                    Task <object> task             = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            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 Task file details
                cmdlet.PoolName = "pool";
                cmdlet.VMName   = "vm1";

                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
        }
        public void GetBatchTaskFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = null;
            cmdlet.JobName = null;
            cmdlet.TaskName = null;
            cmdlet.Name = null;
            cmdlet.Task = null;
            cmdlet.Filter = null;

            // Build some Task files instead of querying the service on a ListTaskFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTaskFilesRequest)
                {
                    ListTaskFilesResponse response = BatchTestHelpers.CreateListTaskFilesResponse(new string[] { "stdout.txt" });
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            Assert.Throws<ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName = "job-0000000001";
            cmdlet.TaskName = "task";

            // Verify no exceptions occur
            cmdlet.ExecuteCmdlet();

            cmdlet.WorkItemName = null;
            cmdlet.JobName = null;
            cmdlet.TaskName = 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 GetBatchTaskFileTest()
        {
            // Setup cmdlet to get a Task file by name
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName      = "job-0000000001";
            cmdlet.TaskName     = "task";
            cmdlet.Name         = "stdout.txt";
            cmdlet.Filter       = null;

            // Build a Task file instead of querying the service on a GetTaskFileProperties call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTaskFilePropertiesRequest)
                {
                    GetTaskFilePropertiesResponse response = BatchTestHelpers.CreateGetTaskFilePropertiesResponse(cmdlet.Name);
                    Task <object> task = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSTaskFile> pipeline = new List <PSTaskFile>();

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSTaskFile>())).Callback <object>(f => pipeline.Add((PSTaskFile)f));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the Task file returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Name, pipeline[0].Name);
        }
        public void GetBatchRDPFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.PoolName = null;
            cmdlet.VMName = null;
            cmdlet.VM = null;
            cmdlet.DestinationPath = null;

            // Don't go to the service on a GetTVMRDPFile call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTVMRDPFileRequest)
                {
                    GetTVMRDPFileResponse response = new GetTVMRDPFileResponse();
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            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 Task file details
                cmdlet.PoolName = "pool";
                cmdlet.VMName = "vm1";

                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
        }
        public void GetBatchVMTest()
        {
            // Setup cmdlet to get a vm by name
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.PoolName     = "pool";
            cmdlet.Name         = "vm1";
            cmdlet.Filter       = null;

            // Build a vm instead of querying the service on a GetTVM call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTVMRequest)
                {
                    GetTVMResponse response = BatchTestHelpers.CreateGetTVMResponse(cmdlet.Name);
                    Task <object> task      = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List <PSVM> pipeline = new List <PSVM>();

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSVM>())).Callback <object>(v => pipeline.Add((PSVM)v));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the vm returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Name, pipeline[0].Name);
        }
예제 #35
0
        public void GetBatchVMFileParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.PoolName     = null;
            cmdlet.VMName       = null;
            cmdlet.Name         = null;
            cmdlet.VM           = null;
            cmdlet.Filter       = null;

            // Build some vm files instead of querying the service on a ListTVMFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMFilesRequest)
                {
                    ListTVMFilesResponse response = BatchTestHelpers.CreateListTVMFilesResponse(new string[] { "startup\\stdout.txt" });
                    Task <object> task            = Task <object> .Factory.StartNew(() => { return(response); });
                    return(task);
                }
                return(null);
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            Assert.Throws <ArgumentNullException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.PoolName = "pool";
            cmdlet.VMName   = "vm1";

            // Verify no exceptions occur
            cmdlet.ExecuteCmdlet();
        }
        public void GetBatchTaskFileTest()
        {
            // Setup cmdlet to get a Task file by name
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName = "job-0000000001";
            cmdlet.TaskName = "task";
            cmdlet.Name = "stdout.txt";
            cmdlet.Filter = null;

            // Build a Task file instead of querying the service on a GetTaskFileProperties call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetTaskFilePropertiesRequest)
                {
                    GetTaskFilePropertiesResponse response = BatchTestHelpers.CreateGetTaskFilePropertiesResponse(cmdlet.Name);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSTaskFile> pipeline = new List<PSTaskFile>();
            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny<PSTaskFile>())).Callback<object>(f => pipeline.Add((PSTaskFile)f));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the Task file returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Name, pipeline[0].Name);
        }
        public void ListBatchVMFilesWithoutFiltersTest()
        {
            // Setup cmdlet to list vm files without filters. 
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.PoolName = "pool";
            cmdlet.VMName = "vm1";
            cmdlet.Name = null;
            cmdlet.Filter = null;

            string[] namesOfConstructedVMFiles = new[] { "startup", "workitems", "shared" };

            // Build some vm files instead of querying the service on a ListTVMFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMFilesRequest)
                {
                    ListTVMFilesResponse response = BatchTestHelpers.CreateListTVMFilesResponse(namesOfConstructedVMFiles);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSVMFile> pipeline = new List<PSVMFile>();
            commandRuntimeMock.Setup(r =>
                r.WriteObject(It.IsAny<PSVMFile>()))
                .Callback<object>(f => pipeline.Add((PSVMFile)f));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed vm files to the pipeline
            Assert.Equal(3, pipeline.Count);
            int taskCount = 0;
            foreach (PSVMFile f in pipeline)
            {
                Assert.True(namesOfConstructedVMFiles.Contains(f.Name));
                taskCount++;
            }
            Assert.Equal(namesOfConstructedVMFiles.Length, taskCount);
        }
        public void ListBatchJobsWithoutFiltersTest()
        {
            // Setup cmdlet to list Jobs without filters. Use WorkItem input.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItem = BatchTestHelpers.CreatePSCloudWorkItem();
            cmdlet.Name = null;
            cmdlet.Filter = null;

            string[] namesOfConstructedJobs = new[] { "job-0000000001", "job-0000000002", "job-0000000003" };

            // Build some Jobs instead of querying the service on a ListJobs call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListJobsRequest)
                {
                    ListJobsResponse response = BatchTestHelpers.CreateListJobsResponse(namesOfConstructedJobs);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            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 cmdlet wrote the constructed Jobs to the pipeline
            Assert.Equal(3, pipeline.Count);
            int jobCount = 0;
            foreach (PSCloudJob j in pipeline)
            {
                Assert.True(namesOfConstructedJobs.Contains(j.Name));
                jobCount++;
            }
            Assert.Equal(namesOfConstructedJobs.Length, jobCount);
        }
        public void ListBatchTasksByODataFilterTest()
        {
            // Setup cmdlet to list Tasks using an OData filter. Use WorkItemName and JobName input.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName = "job-0000000001";
            cmdlet.Name = null;
            cmdlet.Filter = "startswith(name,'test')";

            string[] namesOfConstructedTasks = new[] { "testTask1", "testTask2" };

            // Build some Tasks instead of querying the service on a ListTasks call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTasksRequest)
                {
                    ListTasksResponse response = BatchTestHelpers.CreateListTasksResponse(namesOfConstructedTasks);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            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(2, pipeline.Count);
            int taskCount = 0;
            foreach (PSCloudTask t in pipeline)
            {
                Assert.True(namesOfConstructedTasks.Contains(t.Name));
                taskCount++;
            }
            Assert.Equal(namesOfConstructedTasks.Length, taskCount);
        }
        public void ListVMsMaxCountTest()
        {
            // Verify default max count
            Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount);

            // Setup cmdlet to list vms without filters and a max count
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.Pool = BatchTestHelpers.CreatePSCloudPool();
            cmdlet.Name = null;
            cmdlet.Filter = null;
            int maxCount = 2;
            cmdlet.MaxCount = maxCount;

            string[] namesOfConstructedVMs = new[] { "vm1", "vm2", "vm3" };

            // Build some vms instead of querying the service on a ListTVMs call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMsRequest)
                {
                    ListTVMsResponse response = BatchTestHelpers.CreateListTVMsResponse(namesOfConstructedVMs);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSVM> pipeline = new List<PSVM>();
            commandRuntimeMock.Setup(r =>
                r.WriteObject(It.IsAny<PSVM>()))
                .Callback<object>(v => pipeline.Add((PSVM)v));

            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(namesOfConstructedVMs.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 YieldInjectionInterceptor CreateHttpRecordingInterceptor()
        {
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, batchRequest) =>
            {
                Task<object> task = Task<object>.Factory.StartNew(() =>
                {
                    object batchResponse = null;

                    Delegate postProcessDelegate = null;
                    HttpRequestMessage request = GenerateHttpRequest((BatchRequest)batchRequest);

                    // Setup HTTP recorder and send the request
                    HttpMockServer mockServer = HttpMockServer.CreateInstance();
                    mockServer.InnerHandler = new HttpClientHandler();
                    HttpClient client = new HttpClient(mockServer);
                    Task<HttpResponseMessage> responseTask = client.SendAsync(request);
                    responseTask.Wait();
                    HttpResponseMessage response = responseTask.Result;

                    Task<Stream> getContentTask = response.Content.ReadAsStreamAsync();
                    getContentTask.Wait();
                    Stream body = getContentTask.Result;

                    HttpWebResponse webResponse = ConvertResponseMessageToWebResponse(response);

                    batchResponse = GenerateBatchResponse((BatchRequest)batchRequest, webResponse, body);

                    return batchResponse;
                });
                return task;
            });
            return interceptor;
        }
        public void ListBatchVMsByODataFilterTest()
        {
            // Setup cmdlet to list vms using an OData filter.
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.PoolName = "pool";
            cmdlet.Name = null;
            cmdlet.Filter = "state -eq 'idle'";

            string[] namesOfConstructedVMs = new[] { "vm1", "vm2" };

            // Build some vms instead of querying the service on a ListTVMs call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTVMsRequest)
                {
                    ListTVMsResponse response = BatchTestHelpers.CreateListTVMsResponse(namesOfConstructedVMs);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSVM> pipeline = new List<PSVM>();
            commandRuntimeMock.Setup(r =>
                r.WriteObject(It.IsAny<PSVM>()))
                .Callback<object>(v => pipeline.Add((PSVM)v));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the constructed vms to the pipeline
            Assert.Equal(2, pipeline.Count);
            int vmCount = 0;
            foreach (PSVM v in pipeline)
            {
                Assert.True(namesOfConstructedVMs.Contains(v.Name));
                vmCount++;
            }
            Assert.Equal(namesOfConstructedVMs.Length, vmCount);
        }
        public void ListTaskFilesMaxCountTest()
        {
            // Verify default max count
            Assert.Equal(Microsoft.Azure.Commands.Batch.Utils.Constants.DefaultMaxCount, cmdlet.MaxCount);

            // Setup cmdlet to list Task files and a max count. 
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();
            cmdlet.BatchContext = context;
            cmdlet.WorkItemName = "workItem";
            cmdlet.JobName = "job-0000000001";
            cmdlet.TaskName = "task";
            cmdlet.Name = null;
            cmdlet.Filter = null;
            int maxCount = 2;
            cmdlet.MaxCount = maxCount;

            string[] namesOfConstructedTaskFiles = new[] { "stdout.txt", "stderr.txt", "wd" };

            // Build some Task files instead of querying the service on a ListTaskFiles call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is ListTaskFilesRequest)
                {
                    ListTaskFilesResponse response = BatchTestHelpers.CreateListTaskFilesResponse(namesOfConstructedTaskFiles);
                    Task<object> task = Task<object>.Factory.StartNew(() => { return response; });
                    return task;
                }
                return null;
            });
            cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            List<PSTaskFile> pipeline = new List<PSTaskFile>();
            commandRuntimeMock.Setup(r =>
                r.WriteObject(It.IsAny<PSTaskFile>()))
                .Callback<object>(t => pipeline.Add((PSTaskFile)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(namesOfConstructedTaskFiles.Length, pipeline.Count);
        }