83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using ln.json;
|
|
using NUnit.Framework;
|
|
|
|
namespace ln.http.tests
|
|
{
|
|
public class Tests
|
|
{
|
|
private HttpRouter TestRouter;
|
|
private int TestPort;
|
|
private Listener _httpListener;
|
|
|
|
[SetUp]
|
|
public void Setup()
|
|
{
|
|
TestRouter = new HttpRouter();
|
|
TestRouter.Map(new TestApiController());
|
|
FileSystemRouter fileSystemRouter = new FileSystemRouter("/static/", AppContext.BaseDirectory);
|
|
TestRouter.Map(fileSystemRouter);
|
|
|
|
_httpListener = new Listener(TestRouter, IPAddress.Any, 0);
|
|
TestPort = _httpListener.LocalEndpoint.Port;
|
|
TestContext.Error.WriteLine("Using Port {0}", TestPort);
|
|
}
|
|
|
|
[TearDown]
|
|
public void TearDown()
|
|
{
|
|
_httpListener?.Dispose();
|
|
TestRouter?.Dispose();
|
|
}
|
|
|
|
[Test]
|
|
public void Test1()
|
|
{
|
|
HttpClient client = new HttpClient();
|
|
HttpResponseMessage response = client.GetAsync(String.Format("http://localhost:{0}/static/test.txt", TestPort)).Result;
|
|
|
|
Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode);
|
|
|
|
byte[] contentBytes = response.Content.ReadAsByteArrayAsync().Result;
|
|
byte[] fileBytes = File.ReadAllBytes("test.txt");
|
|
|
|
CollectionAssert.AreEqual(fileBytes, contentBytes);
|
|
|
|
Assert.Pass();
|
|
}
|
|
|
|
[Test]
|
|
public void TestPutJson()
|
|
{
|
|
JSONObject jsonPutObject = new JSONObject();
|
|
jsonPutObject["PutTest"] = JSONTrue.Instance;
|
|
System.Net.Http.StringContent jsonStringContent = new System.Net.Http.StringContent(jsonPutObject.ToString());
|
|
jsonStringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
|
|
|
|
HttpClient client = new HttpClient();
|
|
HttpResponseMessage response = client.PutAsync(String.Format("http://localhost:{0}/controller/put", TestPort), jsonStringContent).Result;
|
|
|
|
Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Pass();
|
|
}
|
|
}
|
|
|
|
[Map(HttpMethod.ANY, "/controller")]
|
|
class TestApiController : HttpEndpointController
|
|
{
|
|
[Map(HttpMethod.PUT, "/put")]
|
|
public HttpResponse PutTest(
|
|
[HttpArgumentSource(HttpArgumentSource.CONTENT)]
|
|
JSONObject jObject
|
|
)
|
|
{
|
|
if (jObject.ContainsKey("PutTest") && jObject["PutTest"] is JSONTrue jsonTrue && jsonTrue == JSONTrue.Instance)
|
|
return HttpResponse.OK();
|
|
return HttpResponse.BadRequest();
|
|
}
|
|
}
|
|
} |