This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
java-nio-server/src/test/java/com/jenkov/nioserver/http/HttpUtilTest.java

67 lines
2.4 KiB
Java

package com.jenkov.nioserver.http;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.UnsupportedEncodingException;
import org.junit.jupiter.api.Test;
/**
* Project: <strong>java-nio-server</strong><br>
* File: <strong>HttpUtilTest.java</strong><br>
* Created: <strong>19 Oct 2015</strong><br>
*
* @author jjenkov
*/
public class HttpUtilTest {
@Test
public void testResolveHttpMethod() throws UnsupportedEncodingException {
assertHttpMethod("GET / HTTP/1.1\r\n", HttpHeaders.HTTP_METHOD_GET);
assertHttpMethod("POST / HTTP/1.1\r\n", HttpHeaders.HTTP_METHOD_POST);
assertHttpMethod("PUT / HTTP/1.1\r\n", HttpHeaders.HTTP_METHOD_PUT);
assertHttpMethod("HEAD / HTTP/1.1\r\n", HttpHeaders.HTTP_METHOD_HEAD);
assertHttpMethod("DELETE / HTTP/1.1\r\n", HttpHeaders.HTTP_METHOD_DELETE);
}
private void assertHttpMethod(String httpRequest, int httpMethod) throws UnsupportedEncodingException {
byte[] source = httpRequest.getBytes("UTF-8");
HttpHeaders httpHeaders = new HttpHeaders();
HttpUtil.resolveHttpMethod(source, 0, httpHeaders);
assertEquals(httpMethod, httpHeaders.httpMethod);
}
@Test
public void testParseHttpRequest() throws UnsupportedEncodingException {
String httpRequest = "GET / HTTP/1.1\r\n\r\n";
byte[] source = httpRequest.getBytes("UTF-8");
HttpHeaders httpHeaders = new HttpHeaders();
HttpUtil.parseHttpRequest(source, 0, source.length, httpHeaders);
assertEquals(0, httpHeaders.contentLength);
httpRequest = "GET / HTTP/1.1\r\n" + "Content-Length: 5\r\n" + "\r\n1234";
source = httpRequest.getBytes("UTF-8");
assertEquals(-1, HttpUtil.parseHttpRequest(source, 0, source.length, httpHeaders));
assertEquals(5, httpHeaders.contentLength);
httpRequest = "GET / HTTP/1.1\r\n" + "Content-Length: 5\r\n" + "\r\n12345";
source = httpRequest.getBytes("UTF-8");
assertEquals(42, HttpUtil.parseHttpRequest(source, 0, source.length, httpHeaders));
assertEquals(5, httpHeaders.contentLength);
httpRequest = "GET / HTTP/1.1\r\n" + "Content-Length: 5\r\n" + "\r\n12345" + "GET / HTTP/1.1\r\n" + "Content-Length: 5\r\n" + "\r\n12345";
source = httpRequest.getBytes("UTF-8");
assertEquals(42, HttpUtil.parseHttpRequest(source, 0, source.length, httpHeaders));
assertEquals(5, httpHeaders.contentLength);
assertEquals(37, httpHeaders.bodyStartIndex);
assertEquals(42, httpHeaders.bodyEndIndex);
}
}