86 lines
2.8 KiB
C#
86 lines
2.8 KiB
C#
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;
|
|
using NUnit.Framework;
|
|
|
|
namespace ln.http.tests
|
|
{
|
|
public class Tests
|
|
{
|
|
HttpServer server;
|
|
int testPort;
|
|
|
|
[SetUp]
|
|
public void Setup()
|
|
{
|
|
if (server != null)
|
|
return;
|
|
|
|
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);
|
|
}
|
|
|
|
[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();
|
|
|
|
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();
|
|
}
|
|
}
|
|
} |