Beispiel #1
0
        public void NewBatchPoolNetworkConfigurationParameterTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            var networkConfiguration = new PSNetworkConfiguration();

            networkConfiguration.SubnetId = "fakeSubnetId";

            cmdlet.Id = "testPool";
            cmdlet.VirtualMachineSize   = "small";
            cmdlet.NetworkConfiguration = networkConfiguration;

            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);

            string subnetId = null;

            Action <BatchRequest <
                        PoolAddParameter,
                        PoolAddOptions,
                        AzureOperationHeaderResponse <PoolAddHeaders> > > extractPoolAction =
                (request) =>
            {
                subnetId = request.Parameters.NetworkConfiguration.SubnetId;
            };

            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor(requestAction: extractPoolAction);

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

            cmdlet.ExecuteCmdlet();

            Assert.Equal(cmdlet.NetworkConfiguration.SubnetId, subnetId);
        }
Beispiel #2
0
        public void GetBatchNodeFileByTaskParametersTest()
        {
            // 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;

            string filePath = "stdout.txt";

            // Don't go to the service on a Get NodeFile call or Get NodeFile Properties call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeGetFileAndPropertiesFromTaskResponseInterceptor(cmdlet.Path);

            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.Path   = filePath;

                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
        }
Beispiel #3
0
        public void WhenStartBatchComputeNodeServiceLogUploadCommandIsCalledWithPoolIdAndComputeNodeId_ShouldSucceed()
        {
            // Setup cmdlet to get a compute node by id
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            startComputeNodeServiceLogUploadCommand.BatchContext  = context;
            startComputeNodeServiceLogUploadCommand.PoolId        = "pool";
            startComputeNodeServiceLogUploadCommand.ComputeNodeId = "tvm";
            startComputeNodeServiceLogUploadCommand.ContainerUrl  = fakeUrl;
            startComputeNodeServiceLogUploadCommand.StartTime     = DateTime.UtcNow;

            const int    numberOfFilesUploaded = 2;
            const string virtualDirectoryName  = "pool1/tvm";

            // Build a compute node instead of querying the service on a Get ComputeNode call
            AzureOperationResponse <ProxyModels.UploadBatchServiceLogsResult, ProxyModels.ComputeNodeUploadBatchServiceLogsHeaders> response =
                BatchTestHelpers.CreateComputeNodeServiceLogsAddResponse(numberOfFilesUploaded, virtualDirectoryName);

            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.ComputeNodeUploadBatchServiceLogsOptions,
                AzureOperationResponse <ProxyModels.UploadBatchServiceLogsResult, ProxyModels.ComputeNodeUploadBatchServiceLogsHeaders> >(response);

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

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            PSStartComputeNodeServiceLogUploadResult result = null;

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSStartComputeNodeServiceLogUploadResult>())).Callback <object>(c => result = (PSStartComputeNodeServiceLogUploadResult)c);

            startComputeNodeServiceLogUploadCommand.ExecuteCmdlet();

            Assert.NotNull(result);
            Assert.Equal(result.NumberOfFilesUploaded, numberOfFilesUploaded);
            Assert.Equal(result.VirtualDirectoryName, virtualDirectoryName);
        }
Beispiel #4
0
        public void EnableAutoScaleRequestTest()
        {
            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 Enable AutoScale call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                BatchRequest <CloudPoolEnableAutoScaleParameters, CloudPoolEnableAutoScaleResponse> request =
                    (BatchRequest <CloudPoolEnableAutoScaleParameters, CloudPoolEnableAutoScaleResponse>)baseRequest;

                requestFormula = request.TypedParameters.AutoScaleFormula;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    CloudPoolEnableAutoScaleResponse response    = new CloudPoolEnableAutoScaleResponse();
                    Task <CloudPoolEnableAutoScaleResponse> 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);
        }
Beispiel #5
0
        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) =>
            {
                PoolUpgradeOSBatchRequest request = (PoolUpgradeOSBatchRequest)baseRequest;

                // Grab the target OS version off the outgoing request
                requestTargetOS = request.Parameters;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    var response = new AzureOperationHeaderResponse <PoolUpgradeOSHeaders>();
                    Task <AzureOperationHeaderResponse <PoolUpgradeOSHeaders> > 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 RemoveBatchNodeFileParametersFromComputeNodeTest()
        {
            // Setup cmdlet to skip confirmation popup
            cmdlet.Force = true;
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);

            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.JobId        = null;
            cmdlet.TaskId       = null;
            cmdlet.Path         = null;
            cmdlet.InputObject  = null;

            // Don't go to the service on a Delete NodeFile call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                bool?,
                FileDeleteFromComputeNodeOptions,
                AzureOperationHeaderResponse <FileDeleteFromComputeNodeHeaders> >();

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

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

            // Setup compute node parameters
            cmdlet.JobId         = null;
            cmdlet.TaskId        = null;
            cmdlet.PoolId        = "testPool";
            cmdlet.ComputeNodeId = "computeNode-1";
            cmdlet.Path          = "stdout.txt";

            // Verify no exceptions occur
            cmdlet.ExecuteCmdlet();
        }
        public void RestartComputeNodeRequestTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.PoolId       = "testPool";
            cmdlet.Id           = "computeNode1";
            cmdlet.RebootOption = BatchCommon.ComputeNodeRebootOption.Terminate;

            ComputeNodeRebootOption?requestRebootOption = null;

            // Don't go to the service on a Reboot ComputeNode call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                ComputeNodeRebootBatchRequest request = (ComputeNodeRebootBatchRequest)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    // Grab the reboot option from the outgoing request.
                    requestRebootOption = request.Parameters;

                    var response = new AzureOperationHeaderResponse <ComputeNodeRebootHeaders>();
                    Task <AzureOperationHeaderResponse <ComputeNodeRebootHeaders> > 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, BatchTestHelpers.MapEnum <BatchCommon.ComputeNodeRebootOption>(requestRebootOption));
        }
        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);
        }
Beispiel #9
0
        public void GetBatchNodeFileByComputeNodeContentParametersTest()
        {
            // Setup cmdlet without required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext    = context;
            cmdlet.PoolId          = null;
            cmdlet.ComputeNodeId   = null;
            cmdlet.Name            = null;
            cmdlet.InputObject     = null;
            cmdlet.DestinationPath = null;

            string fileName = "startup\\stdout.txt";

            // Don't go to the service on a Get NodeFile call or Get NodeFile Properties call
            RequestInterceptor interceptor = BatchTestHelpers.CreateNoOpGetFileAndPropertiesInterceptor(cmdlet.Name);

            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 compute node details
                cmdlet.PoolId        = "pool";
                cmdlet.ComputeNodeId = "computeNode1";
                cmdlet.Name          = fileName;

                // Verify no exceptions occur
                cmdlet.ExecuteCmdlet();
            }
        }
        public void RemoveBatchTaskParametersTest()
        {
            // 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.JobId = "job-1";
            cmdlet.Id    = "testTask";

            // Don't go to the service on a Delete CloudTask call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                BatchRequest <CloudTaskDeleteParameters, CloudTaskDeleteResponse> request =
                    (BatchRequest <CloudTaskDeleteParameters, CloudTaskDeleteResponse>)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    CloudTaskDeleteResponse response    = new CloudTaskDeleteResponse();
                    Task <CloudTaskDeleteResponse> task = Task.FromResult(response);
                    return(task);
                };
            });

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

            // Verify no exceptions when required parameters are set
            cmdlet.ExecuteCmdlet();
        }
Beispiel #11
0
        public void ListBatchComputeNodesODataTest()
        {
            // Setup cmdlet to list compute nodes using an OData filter
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.PoolId       = "testPool";
            cmdlet.Id           = null;
            cmdlet.Filter       = "startswith(id,'test')";
            cmdlet.Select       = "id,state";

            string requestFilter = null;
            string requestSelect = null;

            AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> response =
                BatchTestHelpers.CreateGenericAzureOperationListResponse <ProxyModels.ComputeNode, ProxyModels.ComputeNodeListHeaders>();

            Action <BatchRequest <ProxyModels.ComputeNodeListOptions, AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> > > listComputeNodeAction =
                (request) =>
            {
                ProxyModels.ComputeNodeListOptions options = (ProxyModels.ComputeNodeListOptions)request.Options;

                requestFilter = options.Filter;
                requestSelect = options.Select;
            };

            RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <ProxyModels.ComputeNodeListOptions, AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> >(response, listComputeNodeAction);

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

            cmdlet.ExecuteCmdlet();

            Assert.Equal(cmdlet.Filter, requestFilter);
            Assert.Equal(cmdlet.Select, requestSelect);
        }
Beispiel #12
0
        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.ExecuteCmdlet();

            Assert.Equal(cmdlet.Filter, requestFilter);
            Assert.Equal(cmdlet.Select, requestSelect);
            Assert.Equal(cmdlet.Expand, requestExpand);
        }
        public void GetBatchPoolODataTest()
        {
            // Setup cmdlet to get a single pool
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = "testPool";
            cmdlet.Select       = "id,state";
            cmdlet.Expand       = "stats";

            string requestSelect = null;
            string requestExpand = null;

            // Fetch the OData clauses off the request. The OData clauses are applied after user provided RequestInterceptors, so a ResponseInterceptor is used.
            AzureOperationResponse <ProxyModels.CloudPool, ProxyModels.PoolGetHeaders> getResponse = BatchTestHelpers.CreateCloudPoolGetResponse(cmdlet.Id);
            RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.PoolGetOptions,
                AzureOperationResponse <ProxyModels.CloudPool, ProxyModels.PoolGetHeaders> >(getResponse);

            ResponseInterceptor responseInterceptor = new ResponseInterceptor((response, request) =>
            {
                ProxyModels.PoolGetOptions options = (ProxyModels.PoolGetOptions)request.Options;
                requestSelect = options.Select;
                requestExpand = options.Expand;

                return(Task.FromResult(response));
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                requestInterceptor, responseInterceptor
            };

            cmdlet.ExecuteCmdlet();

            Assert.Equal(cmdlet.Select, requestSelect);
            Assert.Equal(cmdlet.Expand, requestExpand);
        }
Beispiel #14
0
        public void GetBatchJobTest()
        {
            // Setup cmdlet to get a Job by name
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

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

            // Build a Job instead of querying the service on a GetJob call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is GetJobRequest)
                {
                    GetJobResponse response = BatchTestHelpers.CreateGetJobResponse(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 <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 Job returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Name, pipeline[0].Name);
        }
Beispiel #15
0
        public void RegenBatchAccountKeysTest()
        {
            string newPrimaryKey   = "newPrimaryKey";
            string newSecondaryKey = "newSecondaryKey";

            string              accountName     = "account01";
            string              resourceGroup   = "resourceGroup";
            AccountKeyType      keyType         = AccountKeyType.Primary;
            AccountResource     accountResource = BatchTestHelpers.CreateAccountResource(accountName, resourceGroup);
            BatchAccountContext expected        = BatchAccountContext.ConvertAccountResourceToNewAccountContext(accountResource);

            expected.PrimaryAccountKey   = newPrimaryKey;
            expected.SecondaryAccountKey = newSecondaryKey;

            batchClientMock.Setup(b => b.RegenerateKeys(resourceGroup, accountName, keyType)).Returns(expected);

            cmdlet.AccountName       = accountName;
            cmdlet.ResourceGroupName = resourceGroup;
            cmdlet.KeyType           = keyType.ToString();
            cmdlet.ExecuteCmdlet();

            commandRuntimeMock.Verify(r => r.WriteObject(expected), Times.Once());
        }
        /// <summary>
        /// Converts the HttpResponseMessage into an HttpWebResponse that can be used by the Protocol layer
        /// </summary>
        private static HttpWebResponse ConvertResponseMessageToWebResponse(HttpResponseMessage responseMessage)
        {
            HttpWebResponse webResponse = null;

            // The HttpWebResponse class isn't meant to be built on the fly outside of the .NET framework internals, so we use Reflection.
            ConstructorInfo constructor = typeof(HttpWebResponse).GetConstructor(new Type[] { });

            if (constructor != null)
            {
                webResponse = constructor.Invoke(null) as HttpWebResponse;
                if (webResponse != null)
                {
                    BatchTestHelpers.SetField(webResponse, "m_HttpResponseHeaders", new WebHeaderCollection());
                    foreach (var header in responseMessage.Headers)
                    {
                        webResponse.Headers.Add(header.Key, header.Value.FirstOrDefault());
                    }
                    webResponse.Headers.Add("Content-Type", ContentTypeString);
                    BatchTestHelpers.SetField(webResponse, "m_StatusCode", responseMessage.StatusCode);
                }
            }
            return(webResponse);
        }
Beispiel #17
0
        public void DisableJobParametersTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = null;

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

            cmdlet.Id = "testJob";
            cmdlet.DisableJobOption = DisableJobOption.Terminate;

            // Don't go to the service on a Disable CloudJob call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CloudJobDisableParameters, CloudJobDisableResponse>();

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

            // Verify no exceptions when required parameter is set
            cmdlet.ExecuteCmdlet();
        }
        public void CanCreateUserSubscriptionBatchAccount()
        {
            string                  accountName            = "account01";
            string                  resourceGroup          = "resourceGroup";
            string                  location               = "location";
            string                  keyVaultId             = "subscriptions/0000/resourceGroups/resourceGroup/providers/Microsoft.KeyVault/vaults/myVault";
            string                  keyVaultUrl            = "https://myVault.vault.azure.com";
            PoolAllocationMode      allocationMode         = PoolAllocationMode.UserSubscription;
            AccountCreateParameters actualCreateParameters = null;

            // Setup the mock client to return a fake response and capture the account create parameters
            BatchAccount        accountResource = BatchTestHelpers.CreateAccountResource(accountName, resourceGroup, location);
            BatchAccountContext fakeResponse    = BatchAccountContext.ConvertAccountResourceToNewAccountContext(accountResource, null);

            batchClientMock.Setup(b => b.CreateAccount(It.IsAny <AccountCreateParameters>()))
            .Returns(fakeResponse)
            .Callback((AccountCreateParameters p) => actualCreateParameters = p);

            // Setup and run the cmdlet
            cmdlet.AccountName        = accountName;
            cmdlet.ResourceGroupName  = resourceGroup;
            cmdlet.Location           = location;
            cmdlet.PoolAllocationMode = allocationMode;
            cmdlet.KeyVaultId         = keyVaultId;
            cmdlet.KeyVaultUrl        = keyVaultUrl;
            cmdlet.ExecuteCmdlet();

            // Verify the fake response was written to the pipeline and that the captured account create
            // parameters matched expectations.
            commandRuntimeMock.Verify(r => r.WriteObject(fakeResponse), Times.Once());
            Assert.Equal(accountName, actualCreateParameters.BatchAccount);
            Assert.Equal(resourceGroup, actualCreateParameters.ResourceGroup);
            Assert.Equal(location, actualCreateParameters.Location);
            Assert.Equal(allocationMode, actualCreateParameters.PoolAllocationMode);
            Assert.Equal(keyVaultId, actualCreateParameters.KeyVaultId);
            Assert.Equal(keyVaultUrl, actualCreateParameters.KeyVaultUrl);
        }
Beispiel #19
0
        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 ListBatchPoolsODataTest()
        {
            // Setup cmdlet to list pools using an OData filter
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = null;
            cmdlet.Filter       = "startswith(id,'test')";
            cmdlet.Select       = "id,state";
            cmdlet.Expand       = "stats";

            string requestFilter = null;
            string requestSelect = null;
            string requestExpand = null;

            // Fetch the OData clauses off the request. The OData clauses are applied after user provided RequestInterceptors, so a ResponseInterceptor is used.
            RequestInterceptor  requestInterceptor  = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CloudPoolListParameters, CloudPoolListResponse>();
            ResponseInterceptor responseInterceptor = new ResponseInterceptor((response, request) =>
            {
                requestFilter = request.Parameters.DetailLevel.FilterClause;
                requestSelect = request.Parameters.DetailLevel.SelectClause;
                requestExpand = request.Parameters.DetailLevel.ExpandClause;

                return(Task.FromResult(response));
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                requestInterceptor, responseInterceptor
            };

            cmdlet.ExecuteCmdlet();

            Assert.Equal(cmdlet.Filter, requestFilter);
            Assert.Equal(cmdlet.Select, requestSelect);
            Assert.Equal(cmdlet.Expand, requestExpand);
        }
        public void GetBatchPoolTest()
        {
            // Setup cmdlet to get a pool by id
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = "testPool";
            cmdlet.Filter       = null;

            // Pool returned in the response
            ProxyModels.CloudPool pool = new ProxyModels.CloudPool();
            pool.Id = cmdlet.Id;
            pool.TaskSlotsPerNode = 16;

            // Build a CloudPool instead of querying the service on a Get CloudPool call
            AzureOperationResponse <ProxyModels.CloudPool, ProxyModels.PoolGetHeaders> response = BatchTestHelpers.CreateCloudPoolGetResponse(pool);
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.PoolGetOptions,
                AzureOperationResponse <ProxyModels.CloudPool, ProxyModels.PoolGetHeaders> >(response);

            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 pool returned from the OM to the pipeline
            Assert.Single(pipeline);
            Assert.Equal(cmdlet.Id, pipeline[0].Id);
            Assert.Equal(16, pipeline[0].TaskSlotsPerNode);
        }
Beispiel #22
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();
        }
Beispiel #23
0
        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();
        }
        public void NewBatchPoolOSDiskGetsPassedToRequest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.Id = "testPool";
            cmdlet.TargetDedicatedComputeNodes = 3;

            Azure.Batch.Common.CachingType cachingType = Azure.Batch.Common.CachingType.ReadWrite;
            cmdlet.VirtualMachineConfiguration =
                new PSVirtualMachineConfiguration(new PSImageReference("offer", "publisher", "sku"), "node agent")
            {
                OSDisk = new PSOSDisk(cachingType)
            };
            PoolAddParameter requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                PoolAddParameter,
                PoolAddOptions,
                AzureOperationHeaderResponse <PoolAddHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };
            commandRuntimeMock.Setup(cr => cr.ShouldProcess(It.IsAny <string>())).Returns(true);
            cmdlet.ExecuteCmdlet();

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(cachingType.ToString().ToLowerInvariant(),
                         requestParameters.VirtualMachineConfiguration.OsDisk.Caching.ToString().ToLowerInvariant());
        }
Beispiel #25
0
        public void NewBatchTaskParametersTest()
        {
            // Setup cmdlet without the required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

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

            cmdlet.JobId = "job-1";

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

            cmdlet.Id = "testTask";

            // Don't go to the service on an Add CloudTask call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                BatchRequest <CloudTaskAddParameters, CloudTaskAddResponse> request =
                    (BatchRequest <CloudTaskAddParameters, CloudTaskAddResponse>)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    CloudTaskAddResponse response    = new CloudTaskAddResponse();
                    Task <CloudTaskAddResponse> task = Task.FromResult(response);
                    return(task);
                };
            });

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

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

            cmdlet.BatchContext = context;

            cmdlet.PoolId        = "testPool";
            cmdlet.ComputeNodeId = "computeNode1";
            cmdlet.Name          = "user";
            cmdlet.Password      = "******";
            cmdlet.IsAdmin       = true;
            cmdlet.ExpiryTime    = DateTime.Now.AddDays(30);

            ProxyModels.ComputeNodeUser requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.ComputeNodeUser,
                ProxyModels.ComputeNodeAddUserOptions,
                AzureOperationHeaderResponse <ProxyModels.ComputeNodeAddUserHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

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

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(cmdlet.Name, requestParameters.Name);
            Assert.Equal(cmdlet.Password, requestParameters.Password);
            Assert.Equal(cmdlet.IsAdmin, requestParameters.IsAdmin);
            Assert.Equal(cmdlet.ExpiryTime, requestParameters.ExpiryTime);
        }
        public void DisableAutoScaleParametersTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = null;

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

            cmdlet.Id = "testPool";

            // Don't go to the service on an Disable AutoScale call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                PoolDisableAutoScaleOptions,
                AzureOperationHeaderResponse <PoolDisableAutoScaleHeaders> >();

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

            // Verify no exceptions when required parameter is set
            cmdlet.ExecuteCmdlet();
        }
        public void ApplicationPackageReferencesAreSentToService()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = "job-id";
            string applicationName    = "foo";
            string applicationVersion = "beta";

            cmdlet.JobManagerTask = new PSJobManagerTask {
                ApplicationPackageReferences = new[]
                {
                    new PSApplicationPackageReference {
                        ApplicationId = applicationName, Version = applicationVersion
                    },
                }
            };

            // Don't go to the service on an Add CloudJob call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <JobAddParameter, JobAddOptions, AzureOperationHeaderResponse <JobAddHeaders> >(
                new AzureOperationHeaderResponse <JobAddHeaders>(),
                request =>
            {
                var applicationPackageReference = request.Parameters.JobManagerTask.ApplicationPackageReferences.First();
                Assert.Equal(applicationName, 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 NewBatchPoolParametersTest()
        {
            // Setup cmdlet without the required parameters
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

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

            cmdlet.Id = "testPool";
            cmdlet.VirtualMachineSize = "small";
            cmdlet.OSFamily           = "4";

            // Don't go to the service on an Add CloudPool call
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CloudPoolAddParameters, CloudPoolAddResponse>();

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

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

            cmdlet.BatchContext = context;

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

            cmdlet.WorkItemName = "testWorkItem";
            cmdlet.JobName      = "job-0000000001";

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

            cmdlet.Name = "testTask";

            // Don't go to the service on an AddWorkItem call
            YieldInjectionInterceptor interceptor = new YieldInjectionInterceptor((opContext, request) =>
            {
                if (request is AddTaskRequest)
                {
                    AddTaskResponse response = new AddTaskResponse();
                    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();
        }