using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace HelloHttp.Tests
{
public class FunctionUnitTest
{
[Fact]
public async Task GetRequest_NoParameters()
{
DefaultHttpContext context = new DefaultHttpContext();
string text = await ExecuteRequest(context);
Assert.Equal("Hello world!", text);
}
[Fact]
public async Task GetRequest_UrlParameters()
{
DefaultHttpContext context = new DefaultHttpContext
{
Request = { QueryString = new QueryString("?name=Cho") }
};
string text = await ExecuteRequest(context);
Assert.Equal("Hello Cho!", text);
}
[Fact]
public async Task PostRequest_BodyParameters()
{
string json = "{\"name\":\"Julie\"}";
DefaultHttpContext context = new DefaultHttpContext
{
Request =
{
Method = HttpMethods.Post,
Body = new MemoryStream(Encoding.UTF8.GetBytes(json))
}
};
string text = await ExecuteRequest(context);
Assert.Equal("Hello Julie!", text);
}
/// <summary>
/// Executes the given request in the function, validates that the response
/// status code is 200, and returns the text of the response body.
/// </summary>
private static async Task<string> ExecuteRequest(HttpContext context)
{
MemoryStream responseStream = new MemoryStream();
context.Response.Body = responseStream;
Function function = new Function(new NullLogger<Function>());
await function.HandleAsync(context);
Assert.Equal(200, context.Response.StatusCode);
context.Response.BodyWriter.Complete();
context.Response.Body.Position = 0;
TextReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}
}
require "minitest/autorun"
require "functions_framework/testing"
describe "functions_helloworld_http" do
include FunctionsFramework::Testing
it "prints a name" do
load_temporary "helloworld/http/app.rb" do
request = make_post_request "http://example.com:8080/", '{"name": "Ruby"}'
response = call_http "hello_http", request
assert_equal 200, response.status
assert_equal "Hello Ruby!", response.body.join
end
end
it "prints hello world" do
load_temporary "helloworld/http/app.rb" do
request = make_post_request "http://example.com:8080/", ""
response = call_http "hello_http", request
assert_equal 200, response.status
assert_equal "Hello World!", response.body.join
end
end
end