Exemplo n.º 1
0
        public async Task HttpRequest_HttpRequestMessage_ClientMethods_Identical()
        {
            var instanceId = Guid.NewGuid().ToString();
            var orchestrationServiceClientMock = new Mock <IOrchestrationServiceClient>(MockBehavior.Strict);

            orchestrationServiceClientMock.Setup(x => x.GetOrchestrationStateAsync(It.IsAny <string>(), It.IsAny <bool>()))
            .ReturnsAsync(GetInstanceState(OrchestrationStatus.Completed));
            var storageProvider            = new DurabilityProvider("test", new Mock <IOrchestrationService>().Object, orchestrationServiceClientMock.Object, "test");
            var durableExtension           = GetDurableTaskConfig();
            var durableOrchestrationClient = (IDurableClient) new DurableClient(storageProvider, durableExtension, durableExtension.HttpApiHandler, new DurableClientAttribute {
            });
            var httpHandler = new ExtendedHttpApiHandler(new Mock <IDurableClient>(MockBehavior.Strict).Object);

            // This is super hacky, but required due to the circular dependency of ExtendedHttpApiHandler requiring IDurableClient and DurableClient requiring ExtendedHttpApiHandler
            httpHandler.InnerClient = durableOrchestrationClient;

            string sampleUrl = "https://samplesite.azurewebsites.net";
            string sampleId  = Guid.NewGuid().ToString();

            var         netFrameworkRequest = new HttpRequestMessage(HttpMethod.Get, sampleUrl);
            HttpRequest netCoreRequest      = await ConvertHttpRequestMessageAsync(netFrameworkRequest);

            HttpResponseMessage netFrameworkResponse = durableOrchestrationClient.CreateCheckStatusResponse(netFrameworkRequest, sampleId);
            HttpResponseMessage netCoreResponse      = (HttpResponseMessage)((ObjectResult)durableOrchestrationClient.CreateCheckStatusResponse(netCoreRequest, sampleId)).Value;

            await AssertHttpResponsesEqual(netFrameworkResponse, netCoreResponse);

            netFrameworkResponse = await durableOrchestrationClient.WaitForCompletionOrCreateCheckStatusResponseAsync(netFrameworkRequest, sampleId);

            netCoreResponse = (HttpResponseMessage)((ObjectResult)await durableOrchestrationClient.WaitForCompletionOrCreateCheckStatusResponseAsync(netCoreRequest, sampleId)).Value;
            await AssertHttpResponsesEqual(netFrameworkResponse, netCoreResponse);
        }
Exemplo n.º 2
0
        public async Task StartNewInstance_Returns_HTTP_400_On_Missing_Function()
        {
            string testInstanceId   = Guid.NewGuid().ToString("N");
            string testFunctionName = "NonexistentFunction";
            string exceptionMessage = $"The function '{testFunctionName}' doesn't exist, is disabled, or is not an orchestrator function. Additional info: ";

            var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";

            var testRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = startRequestUriBuilder.Uri,
                Content    = new StringContent("\"TestContent\"", Encoding.UTF8, "application/json"),
            };

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()))
            .Throws(new ArgumentException(exceptionMessage));

            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
            var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);

            Assert.Equal(HttpStatusCode.BadRequest, actualResponse.StatusCode);
            var content = await actualResponse.Content.ReadAsStringAsync();

            var error = JsonConvert.DeserializeObject <JObject>(content);

            Assert.Equal("One or more of the arguments submitted is incorrect", error["Message"].ToString());
            Assert.Equal(exceptionMessage, error["ExceptionMessage"].ToString());
        }
        public async Task GetQueryMultipleRuntimeStatus_is_Success()
        {
            var list = (IList <DurableOrchestrationStatus>) new List <DurableOrchestrationStatus>
            {
                new DurableOrchestrationStatus
                {
                    Name          = "DoThis",
                    InstanceId    = "01",
                    CreatedTime   = new DateTime(2018, 3, 10, 10, 10, 10),
                    RuntimeStatus = OrchestrationRuntimeStatus.Running,
                },
                new DurableOrchestrationStatus
                {
                    Name          = "DoThat",
                    InstanceId    = "02",
                    CreatedTime   = new DateTime(2018, 3, 10, 10, 6, 10),
                    RuntimeStatus = OrchestrationRuntimeStatus.Completed,
                },
            };

            var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0);
            var createdTimeTo   = new DateTime(2018, 3, 10, 10, 23, 59);
            var runtimeStatus   = new List <OrchestrationRuntimeStatus>();

            runtimeStatus.Add(OrchestrationRuntimeStatus.Running);
            runtimeStatus.Add(OrchestrationRuntimeStatus.Completed);

            var runtimeStatusRunningString   = OrchestrationRuntimeStatus.Running.ToString();
            var runtimeStatusCompletedString = OrchestrationRuntimeStatus.Completed.ToString();

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.GetStatusAsync(createdTimeFrom, createdTimeTo, runtimeStatus, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(list));
            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);

            var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            getStatusRequestUriBuilder.Path += $"/Instances/";
            getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}&createdTimeTo={WebUtility.UrlEncode(createdTimeTo.ToString())}&runtimeStatus={runtimeStatusRunningString},{runtimeStatusCompletedString}";

            var responseMessage = await httpApiHandler.HandleRequestAsync(
                new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = getStatusRequestUriBuilder.Uri,
            });

            Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            var actual = JsonConvert.DeserializeObject <IList <StatusResponsePayload> >(await responseMessage.Content.ReadAsStringAsync());

            clientMock.Verify(x => x.GetStatusAsync(createdTimeFrom, createdTimeTo, runtimeStatus, It.IsAny <CancellationToken>()));
            Assert.Equal("DoThis", actual[0].Name);
            Assert.Equal("01", actual[0].InstanceId);
            Assert.Equal("Running", actual[0].RuntimeStatus);
            Assert.Equal("DoThat", actual[1].Name);
            Assert.Equal("02", actual[1].InstanceId);
            Assert.Equal("Completed", actual[1].RuntimeStatus);
        }
Exemplo n.º 4
0
        public async Task StartNewInstanceAndWaitToComplete_Is_Success(string instanceId, bool hasContentHeader)
        {
            string testInstanceId   = string.IsNullOrEmpty(instanceId) ? Guid.NewGuid().ToString("N") : instanceId;
            string testFunctionName = "TestOrchestrator";

            var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";
            startRequestUriBuilder.Query = $"timeout=90&pollingInterval=10&{startRequestUriBuilder.Query.TrimStart('?')}";

            var testRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = startRequestUriBuilder.Uri,
                Content    = hasContentHeader
                    ? new StringContent("\"TestContent\"", Encoding.UTF8, "application/json")
                    : new StringContent("\"TestContent\""),
            };

            var testStatusQueryGetUri = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}?taskhub=SampleHubVS&connection=Storage&code=mykey";
            var testSendEventPostUri  = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/raiseEvent/{{eventName}}?taskHub=SampleHubVS&connection=Storage&code=mykey";
            var testTerminatePostUri  = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/terminate?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
            var testRewindPostUri     = $"{TestConstants.NotificationUrlBase}/instances/{testInstanceId}/rewind?reason={{text}}&taskHub=SampleHubVS&connection=Storage&code=mykey";
            var testResponse          = testRequest.CreateResponse(
                HttpStatusCode.Accepted,
                new
            {
                id = testInstanceId,
                statusQueryGetUri = testStatusQueryGetUri,
                sendEventPostUri  = testSendEventPostUri,
                terminatePostUri  = testTerminatePostUri,
                rewindPostUri     = testRewindPostUri,
            });

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()))
            .Returns(Task.FromResult(testInstanceId));

            clientMock
            .Setup(x => x.WaitForCompletionOrCreateCheckStatusResponseAsync(It.IsAny <HttpRequestMessage>(), It.IsAny <string>(), It.IsAny <TimeSpan>(), It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(testResponse));

            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
            var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);

            Assert.Equal(HttpStatusCode.Accepted, actualResponse.StatusCode);
            var content = await actualResponse.Content.ReadAsStringAsync();

            var status = JsonConvert.DeserializeObject <JObject>(content);

            Assert.Equal(status["id"], testInstanceId);
            Assert.Equal(status["statusQueryGetUri"], testStatusQueryGetUri);
            Assert.Equal(status["sendEventPostUri"], testSendEventPostUri);
            Assert.Equal(status["terminatePostUri"], testTerminatePostUri);
            Assert.Equal(status["rewindPostUri"], testRewindPostUri);
        }
        public async Task GetAllStatus_is_Success()
        {
            var list = (IList <DurableOrchestrationStatus>) new List <DurableOrchestrationStatus>
            {
                new DurableOrchestrationStatus
                {
                    Name          = "DoThis",
                    InstanceId    = "01",
                    RuntimeStatus = OrchestrationRuntimeStatus.Running,
                },
                new DurableOrchestrationStatus
                {
                    Name          = "DoThat",
                    InstanceId    = "02",
                    RuntimeStatus = OrchestrationRuntimeStatus.Completed,
                },
            };

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.GetStatusAsync(default(DateTime), default(DateTime), new List <OrchestrationRuntimeStatus>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(list));
            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);

            var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            getStatusRequestUriBuilder.Path += $"/Instances/";

            var responseMessage = await httpApiHandler.HandleRequestAsync(
                new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = getStatusRequestUriBuilder.Uri,
            });

            Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            Assert.Equal(string.Empty, responseMessage.Headers.GetValues("x-ms-continuation-token").FirstOrDefault());
            var actual = JsonConvert.DeserializeObject <IList <StatusResponsePayload> >(await responseMessage.Content.ReadAsStringAsync());

            Assert.Equal("DoThis", actual[0].Name);
            Assert.Equal("01", actual[0].InstanceId);
            Assert.Equal("Running", actual[0].RuntimeStatus);
            Assert.Equal("DoThat", actual[1].Name);
            Assert.Equal("02", actual[1].InstanceId);
            Assert.Equal("Completed", actual[1].RuntimeStatus);
        }
        public async Task TerminateInstanceWebhook()
        {
            string testInstanceId = Guid.NewGuid().ToString("N");
            string testReason     = "TerminationReason" + Guid.NewGuid();

            string actualInstanceId = null;
            string actualReason     = null;

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.TerminateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.CompletedTask)
            .Callback((string instanceId, string reason) =>
            {
                actualInstanceId = instanceId;
                actualReason     = reason;
            });

            clientMock
            .Setup(x => x.GetStatusAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(
                         new DurableOrchestrationStatus
            {
                InstanceId    = testInstanceId,
                RuntimeStatus = OrchestrationRuntimeStatus.Running,
            }));

            var terminateRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            terminateRequestUriBuilder.Path += $"/Instances/{testInstanceId}/terminate";
            terminateRequestUriBuilder.Query = $"reason={testReason}&{terminateRequestUriBuilder.Query.TrimStart('?')}";

            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
            await httpApiHandler.HandleRequestAsync(
                new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = terminateRequestUriBuilder.Uri,
            });

            Assert.Equal(testInstanceId, actualInstanceId);
            Assert.Equal(testReason, actualReason);
        }
Exemplo n.º 7
0
        public async Task StartNewInstance_Returns_HTTP_400_On_Bad_JSON()
        {
            string testInstanceId   = Guid.NewGuid().ToString("N");
            string testFunctionName = "TestOrchestrator";

            var startRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            startRequestUriBuilder.Path += $"/Orchestrators/{testFunctionName}";

            var testRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = startRequestUriBuilder.Uri,
                Content    = new StringContent("badly formatted JSON string", Encoding.UTF8, "application/json"),
            };

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()))
            .Returns(Task.FromResult(testInstanceId));

            clientMock
            .Setup(x => x.CreateCheckStatusResponse(It.IsAny <HttpRequestMessage>(), It.IsAny <string>()))
            .Throws(new JsonReaderException());

            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);
            var actualResponse = await httpApiHandler.HandleRequestAsync(testRequest);

            Assert.Equal(HttpStatusCode.BadRequest, actualResponse.StatusCode);
            var content = await actualResponse.Content.ReadAsStringAsync();

            var error = JsonConvert.DeserializeObject <JObject>(content);

            Assert.Equal("Invalid JSON content", error["Message"].ToString());
        }
Exemplo n.º 8
0
        public async Task GetQueryStatusWithPaging_is_Success()
        {
            var list = (IList <DurableOrchestrationStatus>) new List <DurableOrchestrationStatus>
            {
                new DurableOrchestrationStatus
                {
                    InstanceId    = "01",
                    CreatedTime   = new DateTime(2018, 3, 10, 10, 10, 10, DateTimeKind.Utc),
                    RuntimeStatus = OrchestrationRuntimeStatus.Running,
                },
                new DurableOrchestrationStatus
                {
                    InstanceId    = "02",
                    CreatedTime   = new DateTime(2018, 3, 10, 10, 6, 10, DateTimeKind.Utc),
                    RuntimeStatus = OrchestrationRuntimeStatus.Running,
                },
            };

            var ctx = new OrchestrationStatusQueryResult
            {
                DurableOrchestrationState = list,
                ContinuationToken         = "YYYY-YYYYYYYY-YYYYYYYYYYYY",
            };

            var createdTimeFrom = new DateTime(2018, 3, 10, 10, 1, 0, DateTimeKind.Utc);
            var createdTimeTo   = new DateTime(2018, 3, 10, 10, 23, 59, DateTimeKind.Utc);
            var runtimeStatus   = new List <OrchestrationRuntimeStatus>();

            runtimeStatus.Add(OrchestrationRuntimeStatus.Running);
            var runtimeStatusString = OrchestrationRuntimeStatus.Running.ToString();
            var pageSize            = 100;
            var continuationToken   = "XXXX-XXXXXXXX-XXXXXXXXXXXX";

            var clientMock = new Mock <DurableOrchestrationClientBase>();

            clientMock
            .Setup(x => x.GetStatusAsync(createdTimeFrom, createdTimeTo, runtimeStatus, pageSize, continuationToken, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(ctx));
            var httpApiHandler = new ExtendedHttpApiHandler(clientMock.Object);

            var getStatusRequestUriBuilder = new UriBuilder(TestConstants.NotificationUrl);

            getStatusRequestUriBuilder.Path += $"/Instances/";
            getStatusRequestUriBuilder.Query = $"createdTimeFrom={WebUtility.UrlEncode(createdTimeFrom.ToString())}&createdTimeTo={WebUtility.UrlEncode(createdTimeTo.ToString())}&runtimeStatus={runtimeStatusString}&top=100";

            var requestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = getStatusRequestUriBuilder.Uri,
            };

            requestMessage.Headers.Add("x-ms-continuation-token", "XXXX-XXXXXXXX-XXXXXXXXXXXX");

            var responseMessage = await httpApiHandler.HandleRequestAsync(requestMessage);

            Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            Assert.Equal("YYYY-YYYYYYYY-YYYYYYYYYYYY", responseMessage.Headers.GetValues("x-ms-continuation-token").FirstOrDefault());
            var actual = JsonConvert.DeserializeObject <IList <StatusResponsePayload> >(await responseMessage.Content.ReadAsStringAsync());

            clientMock.Verify(x => x.GetStatusAsync(createdTimeFrom, createdTimeTo, runtimeStatus, pageSize, continuationToken, It.IsAny <CancellationToken>()));
            Assert.Equal("01", actual[0].InstanceId);
            Assert.Equal("Running", actual[0].RuntimeStatus);
            Assert.Equal("02", actual[1].InstanceId);
            Assert.Equal("Running", actual[1].RuntimeStatus);
        }