ln.http/ln.http.tests/UnitTest1.cs

86 lines
2.8 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using ln.http.router;
using ln.json;
using ln.type;
2020-11-26 00:09:03 +01:00
using NUnit.Framework;
namespace ln.http.tests
{
public class Tests
{
2022-05-28 20:04:52 +02:00
HttpServer server;
int testPort;
2020-11-26 00:09:03 +01:00
[SetUp]
public void Setup()
{
if (server != null)
return;
2022-05-28 20:04:52 +02:00
server = new HttpServer();
HttpRouter testRouter = new HttpRouter(server);
testRouter.Map(HttpMethod.ANY, "/controller/*", HttpRoutePriority.NORMAL, new TestApiController().Route);
StaticRouter staticRouter = new StaticRouter(AppContext.BaseDirectory);
testRouter.Map(HttpMethod.ANY, "/static/*", staticRouter.Route);
HttpListener.DefaultPort = 0;
HttpListener httpListener = new HttpListener(server);
testPort = httpListener.LocalEndpoint.Port;
TestContext.Error.WriteLine("Using Port {0}", testPort);
2020-11-26 00:09:03 +01:00
}
[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);
//server.Stop();
2020-11-26 00:09:03 +01:00
Assert.Pass();
}
[Test]
public void TestPutJson()
{
JSONObject jsonPutObject = new JSONObject();
jsonPutObject["PutTest"] = JSONTrue.Instance;
StringContent jsonStringContent = new 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();
}
}
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();
}
2020-11-26 00:09:03 +01:00
}
}