public void TestPatchJob_ThrowsOnUnbound()
        {
            using BatchClient client = ClientUnitTestCommon.CreateDummyClient();
            CloudJob job = client.JobOperations.CreateJob();

            Assert.Throws <InvalidOperationException>(() => job.CommitChanges());
        }
        public void CloudJobSchedule_WhenSendingToTheServer_HasExpectedUnboundProperties()
        {
            const string jobScheduleId = "id-123";
            const string displayName   = "DisplayNameFoo";
            MetadataItem metadataItem  = new MetadataItem("foo", "bar");

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                CloudJobSchedule jobSchedule = client.JobScheduleOperations.CreateJobSchedule();
                jobSchedule.Id          = jobScheduleId;
                jobSchedule.DisplayName = displayName;
                jobSchedule.Metadata    = new List <MetadataItem> {
                    metadataItem
                };

                Assert.Equal(jobSchedule.Id, jobScheduleId); // can set an unbound object
                Assert.Equal(jobSchedule.Metadata.First().Name, metadataItem.Name);
                Assert.Equal(jobSchedule.Metadata.First().Value, metadataItem.Value);

                jobSchedule.Commit(additionalBehaviors: InterceptorFactory.CreateAddJobScheduleRequestInterceptor());

                // writing isn't allowed for a jobSchedule that is in an read only state.
                Assert.Throws <InvalidOperationException>(() => jobSchedule.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => jobSchedule.DisplayName = "cannot-change-display-name");

                //Can still read though
                Assert.Equal(jobScheduleId, jobSchedule.Id);
                Assert.Equal(displayName, jobSchedule.DisplayName);
            }
        }
Esempio n. 3
0
        public void CannotModifyUsesTaskDependenciesOnAJobScheduleAfterItHasBeenCommitted()
        {
            const bool usesTaskDependencies = true;


            using BatchClient client = ClientUnitTestCommon.CreateDummyClient();
            Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(
                baseRequest =>
            {
                var request = (Protocol.BatchRequests.JobScheduleAddBatchRequest)baseRequest;

                request.ServiceRequestFunc = token =>
                {
                    var response = new AzureOperationHeaderResponse <Models.JobScheduleAddHeaders> {
                        Response = new HttpResponseMessage(HttpStatusCode.Created)
                    };

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

            Microsoft.Azure.Batch.CloudJobSchedule cloudJobSchedule = client.JobScheduleOperations.CreateJobSchedule();
            Microsoft.Azure.Batch.JobSpecification jobSpec          = new Microsoft.Azure.Batch.JobSpecification(poolInformation: null)
            {
                UsesTaskDependencies = usesTaskDependencies
            };
            cloudJobSchedule.JobSpecification = jobSpec;
            cloudJobSchedule.Commit(new List <BatchClientBehavior> {
                interceptor
            });

            // writing isn't allowed for a CloudJobSchedule.JobSpecification.UsesTaskDependencies that is in an invalid state.
            Assert.Throws <InvalidOperationException>(() => cloudJobSchedule.JobSpecification.UsesTaskDependencies = false);
        }
Esempio n. 4
0
        public async Task UnboundJobScheduleCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id               = "Bar";
                const string displayName      = "Baz";
                var          jobSpecification = new Protocol.Models.JobSpecification()
                {
                    DisplayName = displayName
                };
                var protoJobSchedule = new Protocol.Models.CloudJobSchedule(
                    id: id,
                    displayName: displayName,
                    jobSpecification: jobSpecification);

                CloudJobSchedule jobSchedule = batchClient.JobScheduleOperations.CreateJobSchedule(id, new Schedule(), null);

                await jobSchedule.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddJobScheduleRequestInterceptor());

                await jobSchedule.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetJobScheduleRequestInterceptor(protoJobSchedule));

                Assert.Equal(id, jobSchedule.Id);
                Assert.Equal(displayName, jobSchedule.DisplayName);
                Assert.Null(jobSchedule.Schedule);
                Assert.NotNull(jobSchedule.JobSpecification);
                Assert.Equal(jobSpecification.DisplayName, jobSchedule.JobSpecification.DisplayName);
            }
        }
        public async Task TestBatchClientDefaultHttpClientTimeoutInfinite()
        {
            BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient();

            Protocol.BatchServiceClient restClient = (Protocol.BatchServiceClient) typeof(ProtocolLayer).GetField("_client", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(batchClient.ProtocolLayer);
            Assert.Equal(Timeout.InfiniteTimeSpan, restClient.HttpClient.Timeout);
        }
Esempio n. 6
0
        public async Task TaskStateMonitorTimedOut_ThrowsTimeoutException()
        {
            TimeSpan     timeout    = TimeSpan.FromSeconds(0);
            const string dummyJobId = "Dummy";

            using (BatchClient batchCli = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
            {
                List <string> taskIds = new List <string>()
                {
                    "task1",
                    "task2"
                };

                //Create some tasks which are "bound"
                IEnumerable <Protocol.Models.CloudTask> protocolTasks = taskIds.Select(CreateProtocolCloudTask);
                IEnumerable <CloudTask> taskList = protocolTasks.Select(protoTask => CreateBoundCloudTask(batchCli, dummyJobId, protoTask));

                TaskStateMonitor taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
                TimeoutException e = await Assert.ThrowsAsync <TimeoutException>(async() => await taskStateMonitor.WhenAll(
                                                                                     taskList,
                                                                                     TaskState.Completed,
                                                                                     timeout,
                                                                                     additionalBehaviors: InterceptorFactory.CreateListTasksRequestInterceptor(protocolTasks)));

                Assert.Contains(string.Format("waiting for resources after {0}", timeout), e.Message);
                Assert.IsType <OperationCanceledException>(e.InnerException);
            }
        }
Esempio n. 7
0
        public async Task TaskStateMonitorCancelled_ThrowsCancellationException()
        {
            TimeSpan     timeout    = TimeSpan.FromSeconds(0);
            const string dummyJobId = "Dummy";

            using (BatchClient batchCli = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
            {
                List <string> taskIds = new List <string>()
                {
                    "task1",
                    "task2"
                };

                //Create some tasks which are "bound"
                IEnumerable <Protocol.Models.CloudTask> protocolTasks = taskIds.Select(CreateProtocolCloudTask);
                IEnumerable <CloudTask> taskList = protocolTasks.Select(protoTask => CreateBoundCloudTask(batchCli, dummyJobId, protoTask));

                TaskStateMonitor taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
                using (CancellationTokenSource cts = new CancellationTokenSource(timeout))
                {
                    await Assert.ThrowsAsync <OperationCanceledException>(async() => await taskStateMonitor.WhenAll(
                                                                              taskList,
                                                                              TaskState.Completed,
                                                                              cts.Token,
                                                                              additionalBehaviors: InterceptorFactory.CreateListTasksRequestInterceptor(protocolTasks)));
                }
            }
        }
Esempio n. 8
0
        public async Task UnboundCertificateCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                string pfxFilePath = TestCommon.GetTemporaryCertificateFilePath("unboundcertificateunittest.pfx");
                try
                {
                    CertificateBuilder.CreateSelfSignedInFile("test", pfxFilePath, CommonResources.CertificatePassword);

                    const string expectedThumbprint = "ABC";
                    var          protoCertificate   = new Protocol.Models.Certificate(thumbprint: expectedThumbprint);
                    Certificate  certificate        = batchClient.CertificateOperations.CreateCertificate(
                        pfxFilePath,
                        CommonResources.CertificatePassword);

                    Assert.NotNull(certificate.ThumbprintAlgorithm);

                    await certificate.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddCertificateRequestInterceptor());

                    await certificate.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetCertificateRequestInterceptor(protoCertificate));

                    Assert.Equal(expectedThumbprint, certificate.Thumbprint);
                    Assert.Null(certificate.ThumbprintAlgorithm);
                }
                finally
                {
                    File.Delete(pfxFilePath);
                }
            }
        }
        public void WhenATaskIsRetrievedFromTheService_ItsDependenciesAreSurfacedCorrectly()
        {
            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                var returnFakeTasks = ClientUnitTestCommon.SimulateServiceResponse <Models.TaskListOptions, AzureOperationResponse <IPage <Models.CloudTask>, Models.TaskListHeaders> >(_ =>
                                                                                                                                                                                        new AzureOperationResponse <IPage <Models.CloudTask>, Models.TaskListHeaders>
                {
                    Body = new FakePage <Models.CloudTask>(new []
                    {
                        new Protocol.Models.CloudTask
                        {
                            DependsOn = new Protocol.Models.TaskDependencies
                            {
                                TaskIdRanges = new[] { new Protocol.Models.TaskIdRange(5, 15) },
                                TaskIds      = new List <string> {
                                    "5"
                                }
                            },
                            Id    = "5",
                            State = Models.TaskState.Active,
                        }
                    })
                });

                var tasks = client.JobOperations.ListTasks("job", additionalBehaviors: returnFakeTasks).ToList();

                var taskDependencies = tasks.First().DependsOn;

                Assert.Equal("5", taskDependencies.TaskIds.Single());
                Assert.Equal(5, taskDependencies.TaskIdRanges.Single().Start);
                Assert.Equal(15, taskDependencies.TaskIdRanges.Single().End);
            }
        }
        public async Task TestCancellationViaParameterForLists()
        {
            using BatchClient client = ClientUnitTestCommon.CreateDummyClient();
            List <IInheritedBehaviors> objectsToExamineForMethods = new List <IInheritedBehaviors>()
            {
                client.JobOperations,
                client.JobScheduleOperations,
                client.CertificateOperations,
                client.PoolOperations,
            };

            foreach (IInheritedBehaviors behaviorContainer in objectsToExamineForMethods)
            {
                List <MethodInfo> listMethods = DiscoverListMethods(behaviorContainer.GetType());

                //Call the list methods to build the enumerable
                foreach (MethodInfo listMethod in listMethods)
                {
                    behaviorContainer.CustomBehaviors.Clear();
                    behaviorContainer.CustomBehaviors.Add(CreateRequestInterceptorForCancellationMonitoring());

                    object pagedEnumerable = ReflectionHelpers.InvokeMethodWithDefaultArguments(listMethod, behaviorContainer);

                    //PagedEnumerable will have a method called: "GetPagedEnumerator"
                    MethodInfo getEnumeratorMethod = pagedEnumerable.GetType().GetMethod("GetPagedEnumerator");
                    object     pagedEnumerator     = getEnumeratorMethod.Invoke(pagedEnumerable, null);

                    //pagedEnumerator has the method to call "MoveNextAsync"
                    MethodInfo moveNextAsyncMethod = pagedEnumerator.GetType().GetMethod("MoveNextAsync");

                    await this.BatchRequestCancellationViaParameterTestAsync(moveNextAsyncMethod, pagedEnumerator, TimeSpan.FromSeconds(0));
                }
            }
        }
Esempio n. 11
0
        public async Task TestRequestWhichDoesSupportSelect()
        {
            using (BatchClient client = await BatchClient.OpenAsync(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
            {
                ODATADetailLevel    detailLevel = new ODATADetailLevel(selectClause: "foo");
                bool                wasHit      = false;
                BatchClientBehavior behavior    = new Protocol.RequestInterceptor(request =>
                {
                    PoolGetBatchRequest poolGetRequest = request as PoolGetBatchRequest;

                    poolGetRequest.ServiceRequestFunc = t =>
                    {
                        Assert.Equal(detailLevel.SelectClause, poolGetRequest.Options.Select);
                        wasHit = true; //Ensure the interceptor was hit
                        return(Task.FromResult(new AzureOperationResponse <CloudPool, PoolGetHeaders>()
                        {
                            Body = new CloudPool()
                        }));
                    };
                });
                const string dummyPoolId = "dummy";

                await client.PoolOperations.GetPoolAsync(dummyPoolId, detailLevel, new[] { behavior });

                Assert.True(wasHit);
            }
        }
        public void CannotSetUsesTaskDependenciesFromABoundCloudJob()
        {
            const string jobId = "id-123";
            const bool   usesTaskDependencies = true;

            // Bound

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(
                    baseRequest =>
                {
                    var request = (Protocol.BatchRequest <Models.JobGetOptions, AzureOperationResponse <Models.CloudJob, Models.JobGetHeaders> >)baseRequest;
                    request.ServiceRequestFunc = (token) =>
                    {
                        var response = new AzureOperationResponse <Models.CloudJob, Models.JobGetHeaders>
                        {
                            Body = new Protocol.Models.CloudJob {
                                UsesTaskDependencies = usesTaskDependencies
                            }
                        };

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

                var cloudJob = client.JobOperations.GetJob(jobId, additionalBehaviors: new List <BatchClientBehavior> {
                    interceptor
                });
                Assert.Equal(usesTaskDependencies, cloudJob.UsesTaskDependencies);
                Assert.Throws <InvalidOperationException>(() => cloudJob.UsesTaskDependencies = false);
            }
        }
        public void Pool_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string cloudPoolId          = "id-123";
            const string cloudPoolDisplayName = "pool-display-name-test";
            MetadataItem metadataItem         = new MetadataItem("foo", "bar");

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudPool protoPool = new Models.CloudPool(id: cloudPoolId, displayName: cloudPoolDisplayName, metadata: new[]
                {
                    new Models.MetadataItem
                    {
                        Name  = metadataItem.Name,
                        Value = metadataItem.Value
                    }
                });

                CloudPool boundPool = client.PoolOperations.GetPool(string.Empty, additionalBehaviors: InterceptorFactory.CreateGetPoolRequestInterceptor(protoPool));

                // Cannot change these bound properties.
                Assert.Throws <InvalidOperationException>(() => boundPool.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundPool.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => boundPool.TargetDedicatedComputeNodes = 1);
                Assert.Throws <InvalidOperationException>(() => boundPool.VirtualMachineSize          = "cannot-change-1");


                // Swap the value with the name and the name with the value.
                boundPool.Metadata = new[] { new MetadataItem(metadataItem.Value, metadataItem.Name) };
                Assert.Equal(metadataItem.Name, boundPool.Metadata.First().Value);
                Assert.Equal(metadataItem.Value, boundPool.Metadata.First().Name);
            }
        }
Esempio n. 14
0
        public void CreateJobWithApplicationReferencesTest()
        {
            const string applicationId = "blender.exe";
            const string version       = "blender";
            const string jobId         = "mock-job";

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Microsoft.Azure.Batch.PoolInformation autoPoolSpecification = new Microsoft.Azure.Batch.PoolInformation
                {
                    AutoPoolSpecification = new Microsoft.Azure.Batch.AutoPoolSpecification
                    {
                        KeepAlive         = false,
                        PoolSpecification = new Microsoft.Azure.Batch.PoolSpecification
                        {
                            ApplicationPackageReferences = new List <Microsoft.Azure.Batch.ApplicationPackageReference>
                            {
                                new Microsoft.Azure.Batch.ApplicationPackageReference
                                {
                                    ApplicationId = applicationId,
                                    Version       = version
                                }
                            },
                            AutoScaleEnabled = false
                        }
                    }
                };

                Microsoft.Azure.Batch.CloudJob cloudJob = client.JobOperations.CreateJob(jobId, autoPoolSpecification);

                Assert.Equal(cloudJob.PoolInformation.AutoPoolSpecification.PoolSpecification.ApplicationPackageReferences.First().ApplicationId, applicationId);
                Assert.Equal(cloudJob.PoolInformation.AutoPoolSpecification.PoolSpecification.ApplicationPackageReferences.First().Version, version);
            }
        }
        public async Task TestCancellationViaParameter()
        {
            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                List <IInheritedBehaviors> objectsToExamineForMethods = new List <IInheritedBehaviors>()
                {
                    client.JobOperations,
                    client.JobScheduleOperations,
                    client.CertificateOperations,
                    client.PoolOperations,
                };

                foreach (IInheritedBehaviors o in objectsToExamineForMethods)
                {
                    List <MethodInfo> methodsToCall = DiscoverCancellableMethods(o.GetType());
                    foreach (MethodInfo method in methodsToCall)
                    {
                        foreach (IInheritedBehaviors behaviorContainer in objectsToExamineForMethods)
                        {
                            behaviorContainer.CustomBehaviors.Clear();
                            behaviorContainer.CustomBehaviors.Add(CreateRequestInterceptorForCancellationMonitoring());
                        }

                        await this.BatchRequestCancellationViaParameterTestAsync(method, o, TimeSpan.FromSeconds(0));
                    }
                }
            }
        }
        public void CannotModifyDependenciesOfABoundTask()
        {
            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                var returnFakeTasks = ClientUnitTestCommon.SimulateServiceResponse <Models.TaskGetOptions, AzureOperationResponse <Models.CloudTask, Models.TaskGetHeaders> >(_ =>
                                                                                                                                                                              new AzureOperationResponse <Models.CloudTask, Models.TaskGetHeaders>
                {
                    Body = new Protocol.Models.CloudTask
                    {
                        DependsOn = new Protocol.Models.TaskDependencies
                        {
                            TaskIdRanges = new[] { new Protocol.Models.TaskIdRange(5, 15) },
                            TaskIds      = new List <string> {
                                "5"
                            }
                        },
                        Id    = "5",
                        State = Models.TaskState.Active,
                    }
                });

                var task = client.JobOperations.GetTask("job", "5", additionalBehaviors: returnFakeTasks);

                var newDependencies = Microsoft.Azure.Batch.TaskDependencies.OnId("hello");
                Assert.Throws <InvalidOperationException>(() => task.DependsOn = newDependencies);
            }
        }
        public async Task TestBatchRequestCannotBeModifiedAfterExecutionStarted()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(req =>
                {
                    PoolAddBatchRequest addPoolRequest = req as PoolAddBatchRequest;
                    addPoolRequest.ServiceRequestFunc  = token =>
                    {
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.CancellationToken       = CancellationToken.None);
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.Options                 = null);
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.RetryPolicy             = null);
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.ServiceRequestFunc      = null);
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.Timeout                 = TimeSpan.FromSeconds(0));
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.ClientRequestIdProvider = null);
                        Assert.Throws <InvalidOperationException>(() => addPoolRequest.Parameters              = null);

                        return(Task.FromResult(new AzureOperationHeaderResponse <Protocol.Models.PoolAddHeaders>()));
                    };
                });

                CloudPool pool = batchClient.PoolOperations.CreatePool("dummy", "small", default(CloudServiceConfiguration), targetDedicatedComputeNodes: 0);
                await pool.CommitAsync(additionalBehaviors : new[] { interceptor });
            }
        }
Esempio n. 18
0
        public async Task UnboundPoolCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id          = "Bar";
                const string displayName = "Baz";
                var          startTask   = new Protocol.Models.StartTask("cmd /c dir");
                var          protoPool   = new Protocol.Models.CloudPool(
                    id: id,
                    displayName: displayName,
                    startTask: startTask);

                CloudPool pool = batchClient.PoolOperations.CreatePool(id, "Woo", new CloudServiceConfiguration("4"));

                await pool.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddPoolRequestInterceptor());

                await pool.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetPoolRequestInterceptor(protoPool));

                Assert.Equal(id, pool.Id);
                Assert.Equal(displayName, pool.DisplayName);
                Assert.Null(pool.CloudServiceConfiguration);
                Assert.NotNull(pool.StartTask);
                Assert.Equal(startTask.CommandLine, pool.StartTask.CommandLine);
            }
        }
Esempio n. 19
0
        public async Task UnboundJobCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id          = "Bar";
                const string displayName = "Baz";
                var          prepTask    = new Protocol.Models.JobPreparationTask(id);

                Protocol.Models.CloudJob protoJob = new Protocol.Models.CloudJob(
                    id: id,
                    displayName: displayName,
                    jobPreparationTask: prepTask);

                CloudJob job = batchClient.JobOperations.CreateJob(id, new PoolInformation()
                {
                    PoolId = "Foo"
                });

                await job.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddJobRequestInterceptor());

                await job.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));

                Assert.Equal(id, job.Id);
                Assert.Equal(displayName, job.DisplayName);
                Assert.Null(job.PoolInformation);
                Assert.NotNull(job.JobPreparationTask);
                Assert.Equal(prepTask.Id, job.JobPreparationTask.Id);
            }
        }
Esempio n. 20
0
        public void GetJobManagerTaskWithApplicationPackageReferences()
        {
            const string jobId         = "id-123";
            const string applicationId = "foo";
            const string version       = "beta";

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudJob protoJob = new Models.CloudJob
                {
                    Id             = jobId,
                    JobManagerTask = new Models.JobManagerTask
                    {
                        ApplicationPackageReferences = new List <Models.ApplicationPackageReference>
                        {
                            new Models.ApplicationPackageReference
                            {
                                Version = version, ApplicationId = applicationId
                            }
                        }
                    }
                };

                var job = client.JobOperations.GetJob(jobId, additionalBehaviors: InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));
                Assert.Equal(applicationId, job.JobManagerTask.ApplicationPackageReferences.First().ApplicationId);
                Assert.Equal(version, job.JobManagerTask.ApplicationPackageReferences.First().Version);
            }
        }
        public async Task TestDefaultBatchRequestTimeoutSet()
        {
            TimeSpan requestTimeout = TimeSpan.MinValue;

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(req =>
                {
                    requestTimeout  = req.Timeout;
                    var castRequest = (Protocol.BatchRequest <
                                           Protocol.Models.JobGetOptions,
                                           AzureOperationResponse <Protocol.Models.CloudJob, Protocol.Models.JobGetHeaders> >)req;
                    castRequest.ServiceRequestFunc = (token) =>
                    {
                        return(Task.FromResult(new AzureOperationResponse <Protocol.Models.CloudJob, Protocol.Models.JobGetHeaders>()
                        {
                            Body = new Protocol.Models.CloudJob()
                        }));
                    };
                });
                await client.JobOperations.GetJobAsync("foo", additionalBehaviors : new List <BatchClientBehavior> {
                    interceptor
                });

                Assert.Equal(Constants.DefaultSingleRestRequestClientTimeout, requestTimeout);
            }
        }
        public void CanReadUsesTaskDependenciesFromABoundCloudJobScheduleTest()
        {
            const string jobId = "id-123";
            const bool   usesTaskDependencies = true;

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(
                    baseRequest =>
                {
                    var request = (Protocol.BatchRequest <Models.JobScheduleGetOptions, AzureOperationResponse <Models.CloudJobSchedule, Models.JobScheduleGetHeaders> >)baseRequest;

                    request.ServiceRequestFunc = token =>
                    {
                        var response = new AzureOperationResponse <Models.CloudJobSchedule, Models.JobScheduleGetHeaders>
                        {
                            Body = new Protocol.Models.CloudJobSchedule(jobId, schedule: new Protocol.Models.Schedule(), jobSpecification: new Protocol.Models.JobSpecification()
                            {
                                UsesTaskDependencies = true
                            })
                        };

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

                Microsoft.Azure.Batch.CloudJobSchedule unboundCloudJob = client.JobScheduleOperations.GetJobSchedule(jobId, additionalBehaviors: new List <BatchClientBehavior> {
                    interceptor
                });

                Assert.Equal(usesTaskDependencies, unboundCloudJob.JobSpecification.UsesTaskDependencies);
            }
        }
        public void CloudTask_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string taskId             = "id-123";
            const int    exitCode           = 1;
            const int    exitCodeRangeStart = 0;
            const int    exitCodeRangeEnd   = 4;

            Models.ExitOptions terminateExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Terminate
            };
            Models.ExitOptions disableExitOption = new Models.ExitOptions()
            {
                JobAction        = Models.JobAction.Disable,
                DependencyAction = Models.DependencyAction.Satisfy
            };

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudTask cloudTask = new Models.CloudTask()
                {
                    Id             = jobId,
                    ExitConditions = new Models.ExitConditions()
                    {
                        DefaultProperty = disableExitOption,
                        ExitCodeRanges  = new List <Models.ExitCodeRangeMapping>()
                        {
                            new Models.ExitCodeRangeMapping(exitCodeRangeStart, exitCodeRangeEnd, terminateExitOption)
                        },
                        ExitCodes = new List <Models.ExitCodeMapping>()
                        {
                            new Models.ExitCodeMapping(exitCode, terminateExitOption)
                        },
                        PreProcessingError = terminateExitOption,
                        FileUploadError    = disableExitOption
                    }
                };

                CloudTask boundTask = client.JobOperations.GetTask(
                    jobId,
                    taskId,
                    additionalBehaviors: InterceptorFactory.CreateGetTaskRequestInterceptor(cloudTask));

                Assert.Equal(taskId, boundTask.Id); // reading is allowed from a task that is returned from the server.
                // These need to be compared as strings because they are different types but we are interested in the values being the same.
                Assert.Equal(disableExitOption.JobAction.ToString(), boundTask.ExitConditions.Default.JobAction.ToString());
                Assert.Equal(DependencyAction.Satisfy, boundTask.ExitConditions.Default.DependencyAction);
                Assert.Equal(DependencyAction.Satisfy, boundTask.ExitConditions.FileUploadError.DependencyAction);
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions         = new ExitConditions());
                Assert.Throws <InvalidOperationException>(() => boundTask.DependsOn              = new TaskDependencies(new List <string>(), new List <TaskIdRange>()));
                Assert.Throws <InvalidOperationException>(() => boundTask.UserIdentity           = new UserIdentity("abc"));
                Assert.Throws <InvalidOperationException>(() => boundTask.CommandLine            = "Cannot change command line");
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions.Default = new ExitOptions()
                {
                    JobAction = JobAction.Terminate
                });
            }
        }
        public void CloudJob_WhenSendingToTheServer_HasExpectedUnboundProperties()
        {
            const string jobId              = "id-123";
            const string displayName        = "DisplayNameFoo";
            MetadataItem metadataItem       = new MetadataItem("foo", "bar");
            const int    priority           = 0;
            const string applicationId      = "testApp";
            const string applicationVersion = "beta";

            using BatchClient client = ClientUnitTestCommon.CreateDummyClient();
            CloudJob cloudJob = client.JobOperations.CreateJob(jobId, new PoolInformation {
                AutoPoolSpecification = new AutoPoolSpecification {
                    KeepAlive = false
                }
            });

            cloudJob.Id          = jobId;
            cloudJob.DisplayName = displayName;
            cloudJob.Metadata    = new List <MetadataItem> {
                metadataItem
            };
            cloudJob.Priority       = priority;
            cloudJob.JobManagerTask = new JobManagerTask
            {
                ApplicationPackageReferences = new List <ApplicationPackageReference>
                {
                    new ApplicationPackageReference {
                        ApplicationId = applicationId, Version = applicationVersion
                    }
                },
                AuthenticationTokenSettings = new AuthenticationTokenSettings()
                {
                    Access = AccessScope.Job
                }
            };

            cloudJob.OnAllTasksComplete = OnAllTasksComplete.NoAction;
            cloudJob.OnTaskFailure      = OnTaskFailure.NoAction;


            Assert.Throws <InvalidOperationException>(() => cloudJob.Url); // cannot read a Url since it's unbound at this point.
            Assert.Equal(cloudJob.Id, jobId);                              // can set an unbound object
            Assert.Equal(cloudJob.Metadata.First().Name, metadataItem.Name);
            Assert.Equal(cloudJob.Metadata.First().Value, metadataItem.Value);
            Assert.Equal(OnAllTasksComplete.NoAction, cloudJob.OnAllTasksComplete);
            Assert.Equal(OnTaskFailure.NoAction, cloudJob.OnTaskFailure);

            cloudJob.Commit(additionalBehaviors: InterceptorFactory.CreateAddJobRequestInterceptor());

            // writing isn't allowed for a job that is in an invalid state.
            Assert.Throws <InvalidOperationException>(() => cloudJob.Id          = "cannot-change-id");
            Assert.Throws <InvalidOperationException>(() => cloudJob.DisplayName = "cannot-change-display-name");

            AuthenticationTokenSettings authenticationTokenSettings = new AuthenticationTokenSettings {
                Access = AccessScope.Job
            };

            Assert.Throws <InvalidOperationException>(() => { cloudJob.JobManagerTask.AuthenticationTokenSettings = authenticationTokenSettings; });
        }
Esempio n. 25
0
 public void TestPatchJobSchedule_ThrowsOnUnbound()
 {
     using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
     {
         CloudJobSchedule jobSchedule = client.JobScheduleOperations.CreateJobSchedule();
         Assert.Throws <InvalidOperationException>(() => jobSchedule.CommitChanges());
     }
 }
Esempio n. 26
0
 public void TestPatchPool_ThrowsOnUnbound()
 {
     using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
     {
         CloudPool pool = client.PoolOperations.CreatePool();
         Assert.Throws <InvalidOperationException>(() => pool.CommitChanges());
     }
 }
Esempio n. 27
0
        public void GetPoolResizeError()
        {
            var autoScaleRunError = new Models.AutoScaleRunError
            {
                Code    = "InsufficientSampleData",
                Message = "Autoscale evaluation failed due to insufficient sample data",
                Values  = new List <Models.NameValuePair>
                {
                    new Models.NameValuePair
                    {
                        Name  = "Message",
                        Value = "Line 1, Col 24: Insufficient data from data set: $RunningTasks wanted 100%, received 0%"
                    }
                }
            };

            var autoScaleError = new Models.AutoScaleRun {
                Error = autoScaleRunError
            };

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(baseRequest =>
                {
                    var request = (Protocol.BatchRequest <Models.PoolGetOptions, AzureOperationResponse <Models.CloudPool, Models.PoolGetHeaders> >)baseRequest;

                    request.ServiceRequestFunc = async(token) =>
                    {
                        var response = new AzureOperationResponse <Models.CloudPool, Models.PoolGetHeaders>
                        {
                            Body = new Models.CloudPool
                            {
                                DisplayName      = "batch-test",
                                AutoScaleFormula = "$RunningTasks.GetSample(10 * TimeInterval_Second, 0 * TimeInterval_Second, 100);",
                                AutoScaleRun     = autoScaleError,
                                EnableAutoScale  = true,
                            }
                        };

                        var task = Task.FromResult(response);
                        return(await task);
                    };
                });

                var pool = client.PoolOperations.GetPool("batch-test", additionalBehaviors: new List <BatchClientBehavior> {
                    interceptor
                });

                Assert.Equal("batch-test", pool.DisplayName);
                Assert.Equal(pool.AutoScaleEnabled, true);
                Assert.Equal(pool.AutoScaleRun.Error.Code, "InsufficientSampleData");
                Assert.Equal(pool.AutoScaleRun.Error.Message, "Autoscale evaluation failed due to insufficient sample data");
                Assert.Equal(pool.AutoScaleRun.Error.Values.First().Name, "Message");
                Assert.Equal(pool.AutoScaleRun.Error.Values.First().Value, "Line 1, Col 24: Insufficient data from data set: $RunningTasks wanted 100%, received 0%");
            }
        }
        public async Task CreateJobScheduleWithApplicationPackageReferences()
        {
            const string applicationId = "blender.exe";
            const string version       = "blender";
            const string jobId         = "mock-job";

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor(
                    baseRequest =>
                {
                    var request =
                        (Protocol.BatchRequest <Models.JobScheduleGetOptions, AzureOperationResponse <Models.CloudJobSchedule, Models.JobScheduleGetHeaders> >)baseRequest;

                    request.ServiceRequestFunc = (token) =>
                    {
                        var response = new AzureOperationResponse <Models.CloudJobSchedule, Models.JobScheduleGetHeaders>
                        {
                            Body = new Models.CloudJobSchedule
                            {
                                JobSpecification = new Protocol.Models.JobSpecification
                                {
                                    PoolInfo = new Models.PoolInformation
                                    {
                                        AutoPoolSpecification = new Models.AutoPoolSpecification
                                        {
                                            Pool = new Models.PoolSpecification
                                            {
                                                ApplicationPackageReferences = new[]
                                                {
                                                    new Protocol.Models.ApplicationPackageReference
                                                    {
                                                        ApplicationId = applicationId,
                                                        Version       = version,
                                                    }
                                                },
                                                MaxTasksPerNode = 4
                                            }
                                        }
                                    }
                                }
                            }
                        };
                        return(Task.FromResult(response));
                    };
                });

                Microsoft.Azure.Batch.CloudJobSchedule cloudJobSchedule = await client.JobScheduleOperations.GetJobScheduleAsync(jobId, additionalBehaviors : new List <BatchClientBehavior> {
                    interceptor
                });

                Assert.Equal(cloudJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification.PoolSpecification.ApplicationPackageReferences.First().ApplicationId, applicationId);
                Assert.Equal(cloudJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification.PoolSpecification.ApplicationPackageReferences.First().Version, version);
            }
        }
        public void CloudJob_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string displayName        = "DisplayNameFoo";
            string       applicationVersion = "beta";
            string       applicationId      = "test";

            MetadataItem metadataItem       = new MetadataItem("foo", "bar");
            const int    priority           = 0;
            var          onAllTasksComplete = OnAllTasksComplete.TerminateJob;

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                DateTime creationTime = DateTime.Now;

                Models.CloudJob protoJob = new Models.CloudJob(
                    jobId,
                    displayName,
                    jobManagerTask: new Models.JobManagerTask()
                {
                    ApplicationPackageReferences = new [] { new Models.ApplicationPackageReference()
                                                            {
                                                                ApplicationId = applicationId, Version = applicationVersion
                                                            } }
                },
                    metadata: new[] { new Models.MetadataItem {
                                          Name = metadataItem.Name, Value = metadataItem.Value
                                      } },
                    creationTime: creationTime,
                    priority: priority,
                    url: ClientUnitTestCommon.DummyBaseUrl,
                    onAllTasksComplete: Models.OnAllTasksComplete.NoAction);

                CloudJob boundJob = client.JobOperations.GetJob(jobId, additionalBehaviors: InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));



                Assert.Equal(jobId, boundJob.Id); // reading is allowed from a job that is returned from the server.
                Assert.Equal(creationTime, boundJob.CreationTime);
                Assert.Equal(displayName, boundJob.DisplayName);
                Assert.Equal(applicationId, boundJob.JobManagerTask.ApplicationPackageReferences.First().ApplicationId);
                Assert.Equal(applicationVersion, boundJob.JobManagerTask.ApplicationPackageReferences.First().Version);

                AssertPatchableJobPropertiesCanBeWritten(boundJob, priority, metadataItem, onAllTasksComplete);

                // Can only read a url from a returned object.
                Assert.Equal(ClientUnitTestCommon.DummyBaseUrl, boundJob.Url);

                // Cannot change a bound displayName, Id and any property on a JobManagerTask.
                Assert.Throws <InvalidOperationException>(() => boundJob.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundJob.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => boundJob.JobManagerTask.ApplicationPackageReferences = new List <ApplicationPackageReference>());
                Assert.Throws <InvalidOperationException>(() => boundJob.JobManagerTask = new JobManagerTask());
            }
        }
        public void CloudTask_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string taskId             = "id-123";
            const int    exitCode           = 1;
            const int    exitCodeRangeStart = 0;
            const int    exitCodeRangeEnd   = 4;

            Models.ExitOptions terminateExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Terminate
            };
            Models.ExitOptions disableExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Disable
            };

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                Models.CloudTask cloudTask = new Models.CloudTask()
                {
                    Id             = jobId,
                    ExitConditions = new Models.ExitConditions()
                    {
                        DefaultProperty = disableExitOption,
                        ExitCodeRanges  = new List <Models.ExitCodeRangeMapping>()
                        {
                            new Models.ExitCodeRangeMapping(exitCodeRangeStart, exitCodeRangeEnd, terminateExitOption)
                        },
                        ExitCodes = new List <Models.ExitCodeMapping>()
                        {
                            new Models.ExitCodeMapping(exitCode, terminateExitOption)
                        },
                        SchedulingError = terminateExitOption,
                    }
                };

                CloudTask boundTask = client.JobOperations.GetTask(
                    jobId,
                    taskId,
                    additionalBehaviors: InterceptorFactory.CreateGetTaskRequestInterceptor(cloudTask));


                Assert.Equal(taskId, boundTask.Id); // reading is allowed from a task that is returned from the server.
                Assert.Equal(disableExitOption.JobAction.ToString(), boundTask.ExitConditions.Default.JobAction.ToString());
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions         = new ExitConditions());
                Assert.Throws <InvalidOperationException>(() => boundTask.DependsOn              = new TaskDependencies(new List <string>(), new List <TaskIdRange>()));
                Assert.Throws <InvalidOperationException>(() => boundTask.RunElevated            = true);
                Assert.Throws <InvalidOperationException>(() => boundTask.CommandLine            = "Cannot change command line");
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions.Default = new ExitOptions()
                {
                    JobAction = JobAction.Terminate
                });
            }
        }