public async Task HttpObjects_Headers(bool ignoreEmptyValues, string[] headerKeys, string[] headerValues, string[] expectedKeys, string[] expectedValues)
        {
            var logger = MockNullLoggerFactory.CreateLogger();
            // Capability must be enabled
            var capabilities = new Capabilities(logger);

            if (ignoreEmptyValues)
            {
                capabilities.UpdateCapabilities(new MapField <string, string>
                {
                    { RpcWorkerConstants.IgnoreEmptyValuedRpcHttpHeaders, "true" }
                });
            }

            var headerDictionary = new HeaderDictionary();

            for (int i = 0; i < headerValues.Length; i++)
            {
                headerDictionary.Add(headerKeys[i], headerValues[i]);
            }

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", $"http://localhost/api/httptrigger-scenarios", headerDictionary);

            var rpcRequestObject = await request.ToRpc(logger, capabilities);

            // Same key and value strings for each pair
            for (int i = 0; i < expectedKeys.Length; i++)
            {
                Assert.True(rpcRequestObject.Http.Headers.ContainsKey(expectedKeys[i]));
                Assert.Equal(expectedValues[i], rpcRequestObject.Http.Headers.GetValueOrDefault(expectedKeys[i]));
            }
        }
        public async Task HttpTrigger_Post_ByteArray(string contentType)
        {
            TestHelpers.ClearFunctionLogs("HttpTriggerByteArray");

            IHeaderDictionary headers = new HeaderDictionary();

            headers.Add("Content-Type", contentType);

            byte[] inputBytes = new byte[] { 1, 2, 3, 4, 5 };
            var    content    = inputBytes;

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/httptriggerbytearray", headers, content);

            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "req", request }
            };
            await Fixture.JobHost.CallAsync("HttpTriggerByteArray", arguments);

            var result = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];

            RawScriptResult objectResult = result as RawScriptResult;

            Assert.NotNull(objectResult);
            Assert.Equal(200, objectResult.StatusCode);

            JObject body = (JObject)objectResult.Content;

            Assert.True((bool)body["isBuffer"]);
            Assert.Equal(5, body["length"]);

            var rawBody = Encoding.UTF8.GetBytes((string)body["rawBody"]);

            Assert.Equal(inputBytes, rawBody);
        }
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
        public async Task HttpTrigger_GetWithAccept_NegotiatesContent(string accept, string expectedBody)
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
        {
            var input = new JObject
            {
                { "name", "Fabio Cavalcante" },
                { "location", "Seattle" }
            };

            var headers = new HeaderDictionary
            {
                { "Accept", new Microsoft.Extensions.Primitives.StringValues(accept) },
                { "Content-Type", new Microsoft.Extensions.Primitives.StringValues("application/json") }
            };

            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/httptrigger-dynamic", headers, body: input.ToString());


            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "input", request },
                { ScriptConstants.SystemTriggerParameterName, request }
            };

            await Fixture.Host.CallAsync("HttpTrigger-Dynamic", arguments);

            var response = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];

            Assert.NotNull(response);
            //Assert.Equal(accept, response.Content.Headers.ContentType.MediaType);

            //string body = await response.Content.ReadAsStringAsync();
            //Assert.Equal(expectedBody, body);
        }
        public async Task HttpTrigger_Post_Dynamic()
        {
            var input = new JObject
            {
                { "name", "Mathew Charles" },
                { "location", "Seattle" }
            };

            var headers = new HeaderDictionary();

            headers.Add("accept", "text/plain");

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("POST", string.Format("http://localhost/api/httptrigger-dynamic"), headers, input.ToString());

            request.ContentType = "application/json";

            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "input", request },
                { ScriptConstants.SystemTriggerParameterName, request }
            };
            await Fixture.Host.CallAsync("HttpTrigger-Dynamic", arguments);

            var response = request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];
            // Assert.Equal(HttpStatusCode.OK, response.);

            // string body = await response.Content.ReadAsStringAsync();
            // Assert.Equal("Name: Mathew Charles, Location: Seattle", body);
        }
Exemple #5
0
        public async Task HttpTrigger_Get(string functionsWorkerLanguage)
        {
            try
            {
                string functionName = "HttpTrigger";
                var    fixture      = new NodeScriptHostTests.TestFixture(new Collection <string> {
                    functionName
                }, functionsWorkerLanguage);
                string url     = $"http://localhost/api/{functionName}?name=test";
                var    request = HttpTestHelpers.CreateHttpRequest("GET", url);

                Dictionary <string, object> arguments = new Dictionary <string, object>
                {
                    { "request", request }
                };
                if (string.Equals(ScriptConstants.NodeLanguageWorkerName, functionsWorkerLanguage, System.StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(functionsWorkerLanguage))
                {
                    await fixture.Host.CallAsync(functionName, arguments);

                    var result = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];
                    Assert.IsType <RawScriptResult>(result);
                    var objResult = result as RawScriptResult;
                    Assert.Equal(200, objResult.StatusCode);
                }
                else
                {
                    await Assert.ThrowsAsync <InvalidOperationException>(async() => await fixture.Host.CallAsync(functionName, arguments));
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable(ScriptConstants.FunctionWorkerRuntimeSettingName, string.Empty);
            }
        }
Exemple #6
0
        public void IsWarmUpRequest_ReturnsExpectedValue()
        {
            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");

            Assert.False(StandbyManager.IsWarmUpRequest(request));

            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, null }
            };

            ScriptSettingsManager.Instance.Reset();
            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsiteInstanceId, "12345");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/csharphttpwarmup");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
                request.Headers.Add(ScriptConstants.AntaresLogIdHeaderName, "xyz123");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/foo");
                Assert.False(StandbyManager.IsWarmUpRequest(request));
            }
        }
Exemple #7
0
        public void IsAntaresInternalRequest_ReturnsExpectedResult()
        {
            // not running under Azure
            var request = HttpTestHelpers.CreateHttpRequest("GET", "http://foobar");

            Assert.False(request.IsAntaresInternalRequest());

            // running under Azure
            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsiteInstanceId, "123" }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                // with header
                var headers = new HeaderDictionary();
                headers.Add(ScriptConstants.AntaresLogIdHeaderName, "123");

                request = HttpTestHelpers.CreateHttpRequest("GET", "http://foobar", headers);
                Assert.False(request.IsAntaresInternalRequest());

                request = HttpTestHelpers.CreateHttpRequest("GET", "http://foobar");
                Assert.True(request.IsAntaresInternalRequest());
            }
        }
Exemple #8
0
        public void HttpTrigger_EmptyBodyAndQuery()
        {
            var result = HttpTrigger.Run(
                req: HttpTestHelpers.CreateHttpRequest("POST", uriString: "http://localhost"),
                log: log);

            Assert.IsType <BadRequestObjectResult>(result);
        }
Exemple #9
0
        private static async Task CallRunFunc(JobHost jobHost)
        {
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://functions.com/api/abc?name=RobZombie");
            var         method  = typeof(FunctionApp1.Function1).GetMethod(nameof(FunctionApp1.Function1.Run));
            await jobHost.CallAsync(method, new { req = request });

            Console.WriteLine(request.HttpContext.Items["$ret"]);
        }
Exemple #10
0
        private static async Task CallEchoFunc(JobHost jobHost)
        {
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://functions.com/api/abc");
            var         method  = typeof(TestFunctions).GetMethod(nameof(TestFunctions.TestResponse));
            await jobHost.CallAsync(method, new { req = request });

            Console.WriteLine(request.HttpContext.Items["$ret"]);
        }
Exemple #11
0
        public async Task HttpTrigger_Get(string functionName)
        {
            string userAgent    = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36";
            string accept       = "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8";
            string customHeader = "foo,bar,baz";
            string url          = $"http://localhost/api/{functionName}?name=Mathew%20Charles&location=Seattle";
            var    request      = HttpTestHelpers.CreateHttpRequest(
                "GET",
                url,
                new HeaderDictionary()
            {
                ["test-header"] = "Test Request Header",
                ["user-agent"]  = userAgent,
                ["accept"]      = accept,
                ["custom-1"]    = customHeader
            });

            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "request", request }
            };
            await Fixture.Host.CallAsync("HttpTrigger", arguments);

            var result = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];

            Assert.IsType <RawScriptResult>(result);

            var objResult = result as RawScriptResult;

            Assert.Equal(200, objResult.StatusCode);

            Assert.Equal("Test Response Header", objResult.Headers["test-header"]);
            Assert.Equal("application/json; charset=utf-8", objResult.Headers["Content-Type"]);

            Assert.IsType <JObject>(objResult.Content);
            var resultObject = objResult.Content as JObject;

            Assert.Equal("undefined", (string)resultObject["reqBodyType"]);
            Assert.Null((string)resultObject["reqBody"]);
            Assert.Equal("undefined", (string)resultObject["reqRawBodyType"]);
            Assert.Null((string)resultObject["reqRawBody"]);

            // verify binding data was populated from query parameters
            Assert.Equal("Mathew Charles", (string)resultObject["bindingData"]["name"]);
            Assert.Equal("Seattle", (string)resultObject["bindingData"]["location"]);

            // validate input headers
            JObject reqHeaders = (JObject)resultObject["reqHeaders"];

            Assert.Equal("Test Request Header", reqHeaders["test-header"]);
            Assert.Equal(userAgent, reqHeaders["user-agent"]);
            Assert.Equal(accept, reqHeaders["accept"]);
            Assert.Equal(customHeader, reqHeaders["custom-1"]);

            // verify originalUrl is correct
            Assert.Equal(HttpUtility.UrlDecode(url), (string)resultObject["reqOriginalUrl"]);
        }
        protected async Task <string> CreateTest <Req>(Req content, string contentType, bool contentNegotiation, string expectedContentType = null)
        {
            IHeaderDictionary headers = new HeaderDictionary();

            headers.Add("accept", contentType);
            headers.Add("type", contentType);

            if (contentNegotiation)
            {
                headers.Add("negotiation", "true");
            }

            headers.Add("scenario", "content");

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/httptrigger", headers, content);

            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "req", request }
            };
            await Fixture.JobHost.CallAsync("HttpTrigger-Scenarios", arguments);

            var result = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];

            if (contentNegotiation)
            {
                ObjectResult objResult = result as ObjectResult;
                Assert.NotNull(objResult);
                if (contentType == null)
                {
                    Assert.Equal(0, objResult.ContentTypes.Count);
                }
                else
                {
                    Assert.Equal(contentType, objResult.ContentTypes[0]);
                }
                Assert.Equal(200, objResult.StatusCode);
                if (content is byte[])
                {
                    Assert.Equal(System.Text.Encoding.UTF8.GetString(content as byte[]), objResult.Value);
                }
                else
                {
                    Assert.Equal(content.ToString(), objResult.Value);
                }
                return(objResult.Value.ToString());
            }
            else
            {
                RawScriptResult rawResult = result as RawScriptResult;
                Assert.NotNull(rawResult);
                Assert.Equal(contentType, rawResult.Headers["content-type"].ToString());
                Assert.Equal(200, rawResult.StatusCode);
                return(rawResult.Content.ToString());
            }
        }
Exemple #13
0
        public void HttpTrigger_ValidQuery()
        {
            var result = HttpTrigger.Run(
                req: HttpTestHelpers.CreateHttpRequest("POST", uriString: "http://localhost?name=Jeff"),
                log: log);

            var resultObject = (OkObjectResult)result;

            Assert.Equal("Hello, Jeff", resultObject.Value);
        }
        public async Task ScriptReference_LoadsScript()
        {
            var request = HttpTestHelpers.CreateHttpRequest("GET", "http://functions/myfunc");
            Dictionary <string, object> arguments = new Dictionary <string, object>()
            {
                { "req", request }
            };

            await Fixture.Host.CallAsync("LoadScriptReference", arguments);

            Assert.Equal("TestClass", request.HttpContext.Items["LoadedScriptResponse"]);
        }
Exemple #15
0
        public async Task PrivateAssemblyDependenciesAreLoaded()
        {
            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://some.server.com");
            Dictionary <string, object> arguments = new Dictionary <string, object>()
            {
                { "req", request }
            };

            await Fixture.Host.CallAsync("PrivateAssemblyReference", arguments);

            Assert.Equal("Test result", request.HttpContext.Items["DependencyOutput"]);
        }
Exemple #16
0
        public async Task SharedAssemblyDependenciesAreLoaded()
        {
            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://some.server.com");
            Dictionary <string, object> arguments = new Dictionary <string, object>()
            {
                { "req", request }
            };

            await Fixture.Host.CallAsync("AssembliesFromSharedLocation", arguments);

            Assert.Equal("secondary type value", request.HttpContext.Items["DependencyOutput"]);
        }
Exemple #17
0
        public void IsWarmUpRequest_ReturnsExpectedValue()
        {
            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");

            Assert.False(StandbyManager.IsWarmUpRequest(request));

            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, null }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                // in this test we're forcing a transition from non-placeholder mode to placeholder mode
                // which can't happen in the wild, so we force a reset here
                WebScriptHostManager.ResetStandbyMode();

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsiteInstanceId, "12345");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/csharphttpwarmup");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
                request.Headers.Add(ScriptConstants.AntaresLogIdHeaderName, "xyz123");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/foo");
                Assert.False(StandbyManager.IsWarmUpRequest(request));
            }

            vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, null }
            };
            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                WebScriptHostManager.ResetStandbyMode();

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
                _settingsManager.SetSetting(EnvironmentSettingNames.ContainerName, "TestContainer");
                Assert.True(_settingsManager.IsLinuxContainerEnvironment);
                Assert.True(StandbyManager.IsWarmUpRequest(request));
            }
        }
Exemple #18
0
        public void HttpObjects_StringBody(string expectedContentType, object body)
        {
            var headers = new HeaderDictionary();

            headers.Add("content-type", expectedContentType);
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/api/httptrigger-scenarios", headers, body);

            var rpcRequestObject = request.ToRpc();

            Assert.Equal(body.ToString(), rpcRequestObject.Http.Body.String);

            string contentType;

            rpcRequestObject.Http.Headers.TryGetValue("content-type", out contentType);
            Assert.Equal(expectedContentType, contentType);
        }
Exemple #19
0
        [InlineData("say=Hi&to=", new string[] { "say" }, new string[] { "Hi" })] // Removes empty value query params
        public void HttpObjects_Query(string queryString, string[] expectedKeys, string[] expectedValues)
        {
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", $"http://localhost/api/httptrigger-scenarios?{queryString}");

            var rpcRequestObject = request.ToRpc();

            // Same number of expected key value pairs
            Assert.Equal(rpcRequestObject.Http.Query.Count, expectedKeys.Length);
            Assert.Equal(rpcRequestObject.Http.Query.Count, expectedValues.Length);
            // Same key and value strings for each pair
            for (int i = 0; i < expectedKeys.Length; i++)
            {
                Assert.True(rpcRequestObject.Http.Query.ContainsKey(expectedKeys[i]));
                Assert.Equal(rpcRequestObject.Http.Query.GetValueOrDefault(expectedKeys[i]), expectedValues[i]);
            }
        }
Exemple #20
0
        public void HttpObjects_ClaimsPrincipal()
        {
            var logger       = MockNullLoggerFactory.CreateLogger();
            var capabilities = new Capabilities(logger);

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", $"http://localhost/apihttptrigger-scenarios");

            var claimsIdentity1 = MockEasyAuth("facebook", "Connor McMahon", "10241897674253170");
            var claimsIdentity2 = new ClaimsIdentity(new List <Claim>
            {
                new Claim("http://schemas.microsoft.com/2017/07/functions/claims/authlevel", "Function")
            }, "WebJobsAuthLevel");
            var claimsIdentity3  = new ClaimsIdentity();
            var claimsIdentities = new List <ClaimsIdentity> {
                claimsIdentity1, claimsIdentity2, claimsIdentity3
            };

            request.HttpContext.User = new ClaimsPrincipal(claimsIdentities);

            var rpcRequestObject = request.ToRpc(logger, capabilities);

            var identities    = request.HttpContext.User.Identities.ToList();
            var rpcIdentities = rpcRequestObject.Http.Identities.ToList();

            Assert.Equal(claimsIdentities.Count, rpcIdentities.Count);

            for (int i = 0; i < identities.Count; i++)
            {
                var identity    = identities[i];
                var rpcIdentity = rpcIdentities.ElementAtOrDefault(i);

                Assert.NotNull(identity);
                Assert.NotNull(rpcIdentity);

                Assert.Equal(rpcIdentity.AuthenticationType?.Value, identity.AuthenticationType);
                Assert.Equal(rpcIdentity.NameClaimType?.Value, identity.NameClaimType);
                Assert.Equal(rpcIdentity.RoleClaimType?.Value, identity.RoleClaimType);

                var claims = identity.Claims.ToList();
                for (int j = 0; j < claims.Count; j++)
                {
                    Assert.True(rpcIdentity.Claims.ElementAtOrDefault(j) != null);
                    Assert.Equal(rpcIdentity.Claims[j].Type, claims[j].Type);
                    Assert.Equal(rpcIdentity.Claims[j].Value, claims[j].Value);
                }
            }
        }
        public async Task HttpTriggerToBlob()
        {
            var headers = new HeaderDictionary
            {
                { "Prefix", "TestPrefix" },
                { "Value", "TestValue" },
                { "Content-Type", "application/json" },
                { "Accept", "text/plain" }
            };

            var id       = Guid.NewGuid().ToString();
            var metadata = new JObject()
            {
                { "M1", "AAA" },
                { "M2", "BBB" }
            };

            var input = new JObject()
            {
                { "Id", id },
                { "Value", "TestInput" },
                { "Metadata", metadata }
            };

            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/HttpTriggerToBlob?Suffix=TestSuffix", headers, input.ToString());

            var arguments = new Dictionary <string, object>
            {
                { "input", request },
                { ScriptConstants.SystemTriggerParameterName, request }
            };
            await Fixture.Host.CallAsync("HttpTriggerToBlob", arguments);

            var response = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];
            //Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            //string body = await response.Content.ReadAsStringAsync();
            string expectedValue = $"TestInput{id}TestValue";
            //Assert.Equal(expectedValue, body);

            // verify blob was written
            string blobName = $"TestPrefix-{id}-TestSuffix-BBB";
            var    outBlob  = Fixture.TestOutputContainer.GetBlockBlobReference(blobName);
            string result   = await TestHelpers.WaitForBlobAndGetStringAsync(outBlob);

            Assert.Equal(expectedValue, Utility.RemoveUtf8ByteOrderMark(result));
        }
        public async Task ExecutionContext_IsPopulated()
        {
            var request = HttpTestHelpers.CreateHttpRequest("GET", "http://functions/myfunc");
            Dictionary <string, object> arguments = new Dictionary <string, object>()
            {
                { "req", request }
            };

            string functionName = "FunctionExecutionContext";
            await Fixture.Host.CallAsync(functionName, arguments);

            ExecutionContext context = request.HttpContext.Items["ContextValue"] as ExecutionContext;

            Assert.NotNull(context);
            Assert.Equal(functionName, context.FunctionName);
            Assert.Equal(Path.Combine(Fixture.Host.ScriptConfig.RootScriptPath, functionName), context.FunctionDirectory);
        }
Exemple #23
0
        public async Task Proxy_Invoke_Succeeds()
        {
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/mymockhttp");

            //request.SetConfiguration(Fixture.RequestConfiguration);

            Dictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "req", request },
            };
            await Fixture.Host.CallAsync("localFunction", arguments);

            var response = (RawScriptResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey];

            Assert.Equal(StatusCodes.Status200OK, response.StatusCode);
            Assert.Equal("123", response.Headers["myversion"].ToString());
        }
        [InlineData("say=Hi&to=", new string[] { "say" }, new string[] { "Hi" })] // Removes empty value query params
        public async Task HttpObjects_Query(string queryString, string[] expectedKeys, string[] expectedValues)
        {
            var logger       = MockNullLoggerFactory.CreateLogger();
            var capabilities = new Capabilities(logger);

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", $"http://localhost/api/httptrigger-scenarios?{queryString}");

            var rpcRequestObject = await request.ToRpc(logger, capabilities);

            // Same number of expected key value pairs
            Assert.Equal(rpcRequestObject.Http.Query.Count, expectedKeys.Length);
            Assert.Equal(rpcRequestObject.Http.Query.Count, expectedValues.Length);
            // Same key and value strings for each pair
            for (int i = 0; i < expectedKeys.Length; i++)
            {
                Assert.True(rpcRequestObject.Http.Query.ContainsKey(expectedKeys[i]));
                Assert.Equal(rpcRequestObject.Http.Query.GetValueOrDefault(expectedKeys[i]), expectedValues[i]);
            }
        }
        public void InitializeHttpRequestEnvironmentVariables_SetsExpectedVariables()
        {
            var environmentVariables = new Dictionary <string, string>();

            var headers = new HeaderDictionary();

            headers.Add("TEST-A", "a");
            headers.Add("TEST-B", "b");

            var request = HttpTestHelpers.CreateHttpRequest("GET", "http://test.com/test?a=1&b=2&b=3&c=4", headers);

            var routeData = new Dictionary <string, object>
            {
                { "a", 123 },
                { "b", 456 }
            };

            request.HttpContext.Items.Add(HttpExtensionConstants.AzureWebJobsHttpRouteDataKey, routeData);

            ScriptFunctionInvokerBase.InitializeHttpRequestEnvironmentVariables(environmentVariables, request);
            Assert.Equal(11, environmentVariables.Count);

            // verify base request properties
            Assert.Equal(request.GetDisplayUrl(), environmentVariables["REQ_ORIGINAL_URL"]);
            Assert.Equal(request.Method.ToString(), environmentVariables["REQ_METHOD"]);
            Assert.Equal(request.QueryString.ToString(), environmentVariables["REQ_QUERY"]);

            // verify query parameters
            Assert.Equal("1", environmentVariables["REQ_QUERY_A"]);
            Assert.Equal("3", environmentVariables["REQ_QUERY_B"]);
            Assert.Equal("4", environmentVariables["REQ_QUERY_C"]);

            // verify headers
            Assert.Equal("a", environmentVariables["REQ_HEADERS_TEST-A"]);
            Assert.Equal("b", environmentVariables["REQ_HEADERS_TEST-B"]);
            Assert.Equal("test.com", environmentVariables["REQ_HEADERS_HOST"]);

            // verify route parameters
            Assert.Equal("123", environmentVariables["REQ_PARAMS_A"]);
            Assert.Equal("456", environmentVariables["REQ_PARAMS_B"]);
        }
Exemple #26
0
        public void IsWarmUpRequest_ReturnsExpectedValue()
        {
            var environment     = new TestEnvironment();
            var hostEnvironment = new ScriptWebHostEnvironment(environment);
            var request         = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");

            Assert.False(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            // Reset environment
            environment.Clear();
            hostEnvironment = new ScriptWebHostEnvironment(environment);

            environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
            Assert.False(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteInstanceId, "12345");
            Assert.True(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/csharphttpwarmup");
            Assert.True(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
            request.Headers.Add(ScriptConstants.AntaresLogIdHeaderName, "xyz123");
            Assert.False(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/foo");
            Assert.False(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            // Reset environment
            environment.Clear();
            hostEnvironment = new ScriptWebHostEnvironment(environment);

            environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
            Assert.False(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));

            request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
            environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "TestContainer");
            Assert.True(environment.IsLinuxConsumption());
            Assert.True(HostWarmupMiddleware.IsWarmUpRequest(request, hostEnvironment, environment));
        }
Exemple #27
0
        public void HttpObjects_RawBodyBytes_Image_Length(string contentType, string rawBytesEnabled)
        {
            var logger       = MockNullLoggerFactory.CreateLogger();
            var capabilities = new Capabilities(logger);

            if (!string.Equals(rawBytesEnabled, null))
            {
                capabilities.UpdateCapabilities(new MapField <string, string>
                {
                    { LanguageWorkerConstants.RawHttpBodyBytes, rawBytesEnabled.ToString() }
                });
            }

            FileStream image = new FileStream(TestImageLocation, FileMode.Open, FileAccess.Read);

            byte[] imageBytes  = FileStreamToBytes(image);
            string imageString = Encoding.UTF8.GetString(imageBytes);

            long imageBytesLength  = imageBytes.Length;
            long imageStringLength = imageString.Length;

            var headers = new HeaderDictionary();

            headers.Add("content-type", contentType);
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/api/httptrigger-scenarios", headers, imageBytes);

            var rpcRequestObject = request.ToRpc(logger, capabilities);

            if (string.IsNullOrEmpty(rawBytesEnabled))
            {
                Assert.Empty(rpcRequestObject.Http.RawBody.Bytes);
                Assert.Equal(imageStringLength, rpcRequestObject.Http.RawBody.String.Length);
            }
            else
            {
                Assert.Empty(rpcRequestObject.Http.RawBody.String);
                Assert.Equal(imageBytesLength, rpcRequestObject.Http.RawBody.Bytes.ToByteArray().Length);
            }
        }
        public async Task HttpTrigger_Post_ByteArray(string expectedContentType, bool rcpHttpBodyOnly)
        {
            var logger       = MockNullLoggerFactory.CreateLogger();
            var capabilities = new Capabilities(logger);

            if (rcpHttpBodyOnly)
            {
                capabilities.UpdateCapabilities(new MapField <string, string>
                {
                    { RpcWorkerConstants.RpcHttpBodyOnly, rcpHttpBodyOnly.ToString() }
                });
            }

            var headers = new HeaderDictionary();

            headers.Add("content-type", expectedContentType);
            byte[] body = new byte[] { 1, 2, 3, 4, 5 };

            HttpRequest request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/httptrigger-scenarios", headers, body);

            var rpcRequestObject = await request.ToRpc(logger, capabilities);

            if (rcpHttpBodyOnly)
            {
                Assert.Equal(null, rpcRequestObject.Http.RawBody);
                Assert.Equal(body, rpcRequestObject.Http.Body.Bytes);
            }
            else
            {
                Assert.Equal(body, rpcRequestObject.Http.Body.Bytes);
                Assert.Equal(Encoding.UTF8.GetString(body), rpcRequestObject.Http.RawBody.String);
            }

            string contentType;

            rpcRequestObject.Http.Headers.TryGetValue("content-type", out contentType);
            Assert.Equal(expectedContentType, contentType);
        }
        public void HttpObjects_StringBody(string expectedContentType, object body, bool rcpHttpBodyOnly)
        {
            var logger       = MockNullLoggerFactory.CreateLogger();
            var capabilities = new Capabilities(logger);

            if (rcpHttpBodyOnly)
            {
                capabilities.UpdateCapabilities(new MapField <string, string>
                {
                    { RpcWorkerConstants.RpcHttpBodyOnly, rcpHttpBodyOnly.ToString() }
                });
            }

            var headers = new HeaderDictionary();

            headers.Add("content-type", expectedContentType);
            HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/api/httptrigger-scenarios", headers, body);

            var rpcRequestObject = request.ToRpc(logger, capabilities);

            Assert.Equal(body.ToString(), rpcRequestObject.Http.Body.String);
            if (rcpHttpBodyOnly)
            {
                Assert.Equal(null, rpcRequestObject.Http.RawBody);
                Assert.Equal(body.ToString(), rpcRequestObject.Http.Body.String);
            }
            else
            {
                Assert.Equal(body.ToString(), rpcRequestObject.Http.RawBody.String);
                Assert.Equal(body.ToString(), rpcRequestObject.Http.Body.String);
            }

            string contentType;

            rpcRequestObject.Http.Headers.TryGetValue("content-type", out contentType);
            Assert.Equal(expectedContentType, contentType);
        }
        public async Task ValidateProxyFunctionInvoker()
        {
            var proxyFunctionDescriptor = new ProxyFunctionDescriptorProvider(_scriptHost, _scriptHost.ScriptOptions, _host.Services.GetService <ICollection <IScriptBindingProvider> >(), NullLoggerFactory.Instance);

            var(created, functionDescriptor) = await proxyFunctionDescriptor.TryCreate(_metadataCollection[0]);

            var proxyInvoker = functionDescriptor.Invoker as ProxyFunctionInvoker;

            var req = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/myproxy");

            var executionContext = new ExecutionContext
            {
                InvocationId = Guid.NewGuid()
            };
            var parameters = new object[] { req, executionContext };

            await proxyInvoker.Invoke(parameters);

            Assert.NotNull(req.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey]);

            var response = req.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey] as IActionResult;

            Assert.NotNull(response);
        }