8373893: Refactor networking http server tests to use JUnit

Reviewed-by: djelinski
This commit is contained in:
Michael McMahon 2025-12-31 22:05:31 +00:00
parent 481ef1de7a
commit 96e5c270b4
31 changed files with 940 additions and 899 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -28,7 +28,7 @@
* with HttpURLConnection and HttpClient
* @modules jdk.httpserver
* @library /test/lib
* @run testng/othervm BasicAuthenticatorRealm
* @run junit/othervm BasicAuthenticatorRealm
*/
import com.sun.net.httpserver.BasicAuthenticator;
@ -47,12 +47,20 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* The second test @Order(2) must run after the first test because it
* sets a VM wide authenticator and the first test depends on no authenticator
* being set.
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class BasicAuthenticatorRealm {
static final String REALM = "U\u00ffU@realm"; // non-ASCII char
@ -61,7 +69,8 @@ public class BasicAuthenticatorRealm {
static final InetAddress LOOPBACK_ADDR = InetAddress.getLoopbackAddress();
@Test
public static void testURLConnection() throws Exception {
@Order(1)
public void testURLConnection() throws Exception {
var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR, 0), 0);
var handler = HttpHandlers.of(200, Headers.of(), "");
var context = server.createContext("/test", handler);
@ -73,15 +82,16 @@ public class BasicAuthenticatorRealm {
server.start();
var url = uri(server).toURL();
var connection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
assertEquals(connection.getResponseCode(), 401);
assertEquals(connection.getHeaderField("WWW-Authenticate"), EXPECTED_AUTH_HEADER_VALUE);
assertEquals(401, connection.getResponseCode());
assertEquals(EXPECTED_AUTH_HEADER_VALUE, connection.getHeaderField("WWW-Authenticate"));
} finally {
server.stop(0);
}
}
@Test
public static void testURLConnectionAuthenticated() throws Exception {
@Order(2)
public void testURLConnectionAuthenticated() throws Exception {
var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR, 0), 0);
var handler = HttpHandlers.of(200, Headers.of(), "foo");
var context = server.createContext("/test", handler);
@ -94,15 +104,16 @@ public class BasicAuthenticatorRealm {
server.start();
var url = uri(server).toURL();
var connection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
assertEquals(connection.getResponseCode(), 200);
assertEquals(connection.getInputStream().readAllBytes(), "foo".getBytes(UTF_8));
assertEquals(200, connection.getResponseCode());
Assertions.assertArrayEquals("foo".getBytes(UTF_8), connection.getInputStream().readAllBytes());
} finally {
server.stop(0);
}
}
@Test
public static void testHttpClient() throws Exception {
@Order(3)
public void testHttpClient() throws Exception {
var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR, 0), 0);
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server)).build();
@ -115,15 +126,16 @@ public class BasicAuthenticatorRealm {
try {
server.start();
var response = client.send(request, BodyHandlers.ofString(UTF_8));
assertEquals(response.statusCode(), 401);
assertEquals(response.headers().firstValue("WWW-Authenticate").orElseThrow(), EXPECTED_AUTH_HEADER_VALUE);
assertEquals(401, response.statusCode());
assertEquals(EXPECTED_AUTH_HEADER_VALUE, response.headers().firstValue("WWW-Authenticate").orElseThrow());
} finally {
server.stop(0);
}
}
@Test
public static void testHttpClientAuthenticated() throws Exception {
@Order(4)
public void testHttpClientAuthenticated() throws Exception {
var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR, 0), 0);
var request = HttpRequest.newBuilder(uri(server)).build();
var handler = HttpHandlers.of(200, Headers.of(), "foo");
@ -139,8 +151,8 @@ public class BasicAuthenticatorRealm {
try {
server.start();
var response = client.send(request, BodyHandlers.ofString(UTF_8));
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "foo");
assertEquals(200, response.statusCode());
assertEquals("foo", response.body());
} finally {
server.stop(0);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,17 +25,17 @@
* @test
* @bug 8251496
* @summary summary
* @run testng/othervm CreateHttpServerTest
* @run junit/othervm CreateHttpServerTest
*/
import com.sun.net.httpserver.HttpServer;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class CreateHttpServerTest {
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -39,12 +39,13 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* @test
@ -53,19 +54,19 @@ import static org.testng.Assert.fail;
* @modules java.net.http
* @library /test/lib
* @build DateFormatterTest
* @run testng/othervm DateFormatterTest
* @run junit/othervm DateFormatterTest
*/
public class DateFormatterTest {
private HttpServer server;
private static HttpServer server;
static URI httpURI;
static final Integer ITERATIONS = 10;
static String format;
static Pattern pattern;
@BeforeTest
public void setUp() throws IOException, URISyntaxException {
@BeforeAll
public static void setUp() throws IOException, URISyntaxException {
String days = "(Mon|Tue|Wed|Thu|Fri|Sat|Sun)(,)";
String dayNo = "(\\s\\d\\d\\s)";
String month = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
@ -85,8 +86,8 @@ public class DateFormatterTest {
server.start();
}
@AfterTest
public void cleanUp() {
@AfterAll
public static void cleanUp() {
server.stop(0);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,7 +25,7 @@
* @test
* @bug 8267262
* @summary Tests for Filter static factory methods
* @run testng/othervm FilterTest
* @run junit/othervm FilterTest
*/
import java.io.IOException;
@ -49,11 +49,13 @@ import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class FilterTest {
@ -64,8 +66,8 @@ public class FilterTest {
static final boolean ENABLE_LOGGING = true;
static final Logger logger = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() {
@BeforeAll
public static void setup() {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
logger.setLevel(Level.ALL);
@ -76,14 +78,14 @@ public class FilterTest {
@Test
public void testNull() {
expectThrows(NPE, () -> Filter.beforeHandler(null, e -> e.getResponseHeaders().set("X-Foo", "Bar")));
expectThrows(NPE, () -> Filter.beforeHandler("Some description", null));
assertThrows(NPE, () -> Filter.beforeHandler(null, e -> e.getResponseHeaders().set("X-Foo", "Bar")));
assertThrows(NPE, () -> Filter.beforeHandler("Some description", null));
expectThrows(NPE, () -> Filter.afterHandler("Some description", null));
expectThrows(NPE, () -> Filter.afterHandler(null, HttpExchange::getResponseCode));
assertThrows(NPE, () -> Filter.afterHandler("Some description", null));
assertThrows(NPE, () -> Filter.afterHandler(null, HttpExchange::getResponseCode));
expectThrows(NPE, () -> Filter.adaptRequest("Some description", null));
expectThrows(NPE, () -> Filter.adaptRequest(null, r -> r.with("Foo", List.of("Bar"))));
assertThrows(NPE, () -> Filter.adaptRequest("Some description", null));
assertThrows(NPE, () -> Filter.adaptRequest(null, r -> r.with("Foo", List.of("Bar"))));
}
@Test
@ -91,16 +93,15 @@ public class FilterTest {
var desc = "Some description";
var beforeFilter = Filter.beforeHandler(desc, HttpExchange::getRequestBody);
assertEquals(desc, beforeFilter.description());
assertEquals(beforeFilter.description(), desc);
var afterFilter = Filter.afterHandler(desc, HttpExchange::getResponseCode);
assertEquals(desc, afterFilter.description());
assertEquals(afterFilter.description(), desc);
var adaptFilter = Filter.adaptRequest(desc, r -> r.with("Foo", List.of("Bar")));
assertEquals(desc, adaptFilter.description());
assertEquals(adaptFilter.description(), desc);
}
@DataProvider
public static Object[][] throwingFilters() {
return new Object[][] {
{Filter.beforeHandler("before RE", e -> { throw new RuntimeException(); }), IOE},
@ -111,7 +112,8 @@ public class FilterTest {
};
}
@Test(dataProvider = "throwingFilters")
@ParameterizedTest
@MethodSource("throwingFilters")
public void testException(Filter filter, Class<Exception> exception)
throws Exception
{
@ -123,11 +125,11 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
if (exception != null) {
expectThrows(exception, () -> client.send(request, HttpResponse.BodyHandlers.ofString()));
assertThrows(exception, () -> client.send(request, HttpResponse.BodyHandlers.ofString()));
} else {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "hello world");
assertEquals(200, response.statusCode());
assertEquals("hello world", response.body());
}
} finally {
server.stop(0);
@ -146,9 +148,9 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.headers().firstValue("x-foo").orElseThrow(), "bar");
assertEquals(200, response.statusCode());
assertEquals(3, response.headers().map().size());
assertEquals("bar", response.headers().firstValue("x-foo").orElseThrow());
} finally {
server.stop(0);
}
@ -170,9 +172,9 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.headers().firstValue("x-foo").orElseThrow(), "barbar");
assertEquals(200, response.statusCode());
assertEquals(3, response.headers().map().size());
assertEquals("barbar", response.headers().firstValue("x-foo").orElseThrow());
} finally {
server.stop(0);
}
@ -202,9 +204,9 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.headers().firstValue("x-foo").orElseThrow(), "bar");
assertEquals(200, response.statusCode());
assertEquals(3, response.headers().map().size());
assertEquals("bar", response.headers().firstValue("x-foo").orElseThrow());
} finally {
server.stop(0);
}
@ -223,8 +225,8 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.statusCode(), (int)respCode.get());
assertEquals(200, response.statusCode());
assertEquals((int)respCode.get(), response.statusCode());
} finally {
server.stop(0);
}
@ -248,8 +250,8 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(attr.get(), value);
assertEquals(200, response.statusCode());
assertEquals(value, attr.get());
} finally {
server.stop(0);
}
@ -280,8 +282,8 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.statusCode(), (int)respCode.get());
assertEquals(200, response.statusCode());
assertEquals((int)respCode.get(), response.statusCode());
} finally {
server.stop(0);
}
@ -304,10 +306,10 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.headers().firstValue("x-foo").orElseThrow(), "bar");
assertEquals(response.statusCode(), (int)respCode.get());
assertEquals(200, response.statusCode());
assertEquals(3, response.headers().map().size());
assertEquals("bar", response.headers().firstValue("x-foo").orElseThrow());
assertEquals((int)respCode.get(), response.statusCode());
} finally {
server.stop(0);
}
@ -326,8 +328,8 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "foo/bar")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(inspectedURI.get(), URI.create("/foo/bar"));
assertEquals(200, response.statusCode());
assertEquals(URI.create("/foo/bar"), inspectedURI.get());
} finally {
server.stop(0);
}
@ -348,9 +350,9 @@ public class FilterTest {
});
var adaptFilter = Filter.adaptRequest("Add x-foo request header", r -> {
// Confirm request state is unchanged
assertEquals(r.getRequestHeaders(), originalExchange.getRequestHeaders());
assertEquals(r.getRequestURI(), originalExchange.getRequestURI());
assertEquals(r.getRequestMethod(), originalExchange.getRequestMethod());
assertEquals(originalExchange.getRequestHeaders(), r.getRequestHeaders());
assertEquals(originalExchange.getRequestURI(), r.getRequestURI());
assertEquals(originalExchange.getRequestMethod(), r.getRequestMethod());
return r.with("x-foo", List.of("bar"));
});
var server = HttpServer.create(new InetSocketAddress(LOOPBACK_ADDR,0), 10);
@ -362,8 +364,8 @@ public class FilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "bar");
assertEquals(200, response.statusCode());
assertEquals("bar", response.body());
} finally {
server.stop(0);
}
@ -398,22 +400,22 @@ public class FilterTest {
static class CompareStateAndEchoHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
assertEquals(exchange.getLocalAddress(), originalExchange.getLocalAddress());
assertEquals(exchange.getRemoteAddress(), originalExchange.getRemoteAddress());
assertEquals(exchange.getProtocol(), originalExchange.getProtocol());
assertEquals(exchange.getPrincipal(), originalExchange.getPrincipal());
assertEquals(exchange.getHttpContext(), originalExchange.getHttpContext());
assertEquals(exchange.getRequestMethod(), originalExchange.getRequestMethod());
assertEquals(exchange.getRequestURI(), originalExchange.getRequestURI());
assertEquals(exchange.getRequestBody(), originalExchange.getRequestBody());
assertEquals(exchange.getResponseHeaders(), originalExchange.getResponseHeaders());
assertEquals(exchange.getResponseCode(), originalExchange.getResponseCode());
assertEquals(exchange.getResponseBody(), originalExchange.getResponseBody());
assertEquals(exchange.getAttribute("foo"), originalExchange.getAttribute("foo"));
assertEquals(originalExchange.getLocalAddress(), exchange.getLocalAddress());
assertEquals(originalExchange.getRemoteAddress(), exchange.getRemoteAddress());
assertEquals(originalExchange.getProtocol(), exchange.getProtocol());
assertEquals(originalExchange.getPrincipal(), exchange.getPrincipal());
assertEquals(originalExchange.getHttpContext(), exchange.getHttpContext());
assertEquals(originalExchange.getRequestMethod(), exchange.getRequestMethod());
assertEquals(originalExchange.getRequestURI(), exchange.getRequestURI());
assertEquals(originalExchange.getRequestBody(), exchange.getRequestBody());
assertEquals(originalExchange.getResponseHeaders(), exchange.getResponseHeaders());
assertEquals(originalExchange.getResponseCode(), exchange.getResponseCode());
assertEquals(originalExchange.getResponseBody(), exchange.getResponseBody());
assertEquals(originalExchange.getAttribute("foo"), exchange.getAttribute("foo"));
assertFalse(exchange.getRequestHeaders().equals(originalExchange.getRequestHeaders()));
exchange.setAttribute("foo", "barbar");
assertEquals(exchange.getAttribute("foo"), originalExchange.getAttribute("foo"));
assertEquals(originalExchange.getAttribute("foo"), exchange.getAttribute("foo"));
try (InputStream is = exchange.getRequestBody();
OutputStream os = exchange.getResponseBody()) {

View File

@ -29,7 +29,7 @@
* jdk.httpserver/sun.net.httpserver:+open
* @library /test/lib
* @build jdk.test.lib.net.URIBuilder
* @run testng/othervm HeadersTest
* @run junit/othervm HeadersTest
*/
import java.io.IOException;
@ -57,18 +57,20 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import sun.net.httpserver.UnmodifiableHeaders;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HeadersTest {
@ -77,13 +79,13 @@ public class HeadersTest {
static final Class<NullPointerException> NPE = NullPointerException.class;
@Test
public static void testDefaultConstructor() {
public void testDefaultConstructor() {
var headers = new Headers();
assertTrue(headers.isEmpty());
}
@Test
public static void testNull() {
public void testNull() {
final Headers h = new Headers();
h.put("Foo", List.of("Bar"));
@ -157,8 +159,7 @@ public class HeadersTest {
assertThrows(NPE, () -> h.set("Foo", null));
}
@DataProvider
public Object[][] responseHeaders() {
public static Object[][] responseHeaders() {
final var listWithNull = new LinkedList<String>();
listWithNull.add(null);
return new Object[][] {
@ -172,7 +173,8 @@ public class HeadersTest {
* Confirms HttpExchange::sendResponseHeaders throws NPE if response headers
* contain a null key or value.
*/
@Test(dataProvider = "responseHeaders")
@ParameterizedTest
@MethodSource("responseHeaders")
public void testNullResponseHeaders(String headerKey, List<String> headerVal)
throws Exception {
var handler = new Handler(headerKey, headerVal);
@ -183,7 +185,7 @@ public class HeadersTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
assertThrows(IOE, () -> client.send(request, HttpResponse.BodyHandlers.ofString()));
assertEquals(throwable.get().getClass(), NPE);
assertEquals(NPE, throwable.get().getClass());
assertTrue(Arrays.stream(throwable.get().getStackTrace())
.anyMatch(e -> e.getClassName().equals("sun.net.httpserver.HttpExchangeImpl")
|| e.getMethodName().equals("sendResponseHeaders")));
@ -240,7 +242,6 @@ public class HeadersTest {
}
}
@DataProvider
public static Object[][] headerPairs() {
final var h1 = new Headers();
final var h2 = new Headers();
@ -259,16 +260,16 @@ public class HeadersTest {
.toArray(Object[][]::new);
}
@Test(dataProvider = "headerPairs")
public static void testEqualsAndHashCode(Headers h1, Headers h2) {
// avoid testng's asserts(Map, Map) as they don't call Headers::equals
@ParameterizedTest
@MethodSource("headerPairs")
public void testEqualsAndHashCode(Headers h1, Headers h2) {
assertTrue(h1.equals(h2), "Headers differ");
assertEquals(h1.hashCode(), h2.hashCode(), "hashCode differ for "
assertEquals(h2.hashCode(), h1.hashCode(), "hashCode differ for "
+ List.of(h1, h2));
}
@Test
public static void testEqualsMap() {
public void testEqualsMap() {
final var h = new Headers();
final var m = new HashMap<String, List<String>>();
assertTrue(h.equals(m));
@ -277,14 +278,14 @@ public class HeadersTest {
}
@Test
public static void testToString() {
public void testToString() {
final var h = new Headers();
h.put("Accept-Encoding", List.of("gzip, deflate"));
assertTrue(h.toString().equals("Headers { {Accept-encoding=[gzip, deflate]} }"));
}
@Test
public static void testPutAll() {
public void testPutAll() {
final var h0 = new Headers();
final var map = new HashMap<String, List<String>>();
map.put("a", null);
@ -311,7 +312,7 @@ public class HeadersTest {
}
@Test
public static void testReplaceAll() {
public void testReplaceAll() {
final var h1 = new Headers();
h1.put("a", List.of("1"));
h1.put("b", List.of("2"));
@ -331,7 +332,7 @@ public class HeadersTest {
}
@Test
public static void test1ArgConstructorNull() {
public void test1ArgConstructorNull() {
assertThrows(NPE, () -> new Headers(null));
{
final var m = new HashMap<String, List<String>>();
@ -353,35 +354,35 @@ public class HeadersTest {
}
@Test
public static void test1ArgConstructor() {
public void test1ArgConstructor() {
{
var h = new Headers(new Headers());
assertTrue(h.isEmpty());
}
{
var h = new Headers(Map.of("Foo", List.of("Bar")));
assertEquals(h.get("Foo"), List.of("Bar"));
assertEquals(h.size(), 1);
assertEquals(List.of("Bar"), h.get("Foo"));
assertEquals(1, h.size());
}
{
var h1 = new Headers(new UnmodifiableHeaders(new Headers()));
assertTrue(h1.isEmpty());
h1.put("Foo", List.of("Bar")); // modifiable
assertEquals(h1.get("Foo"), List.of("Bar"));
assertEquals(h1.size(), 1);
assertEquals(List.of("Bar"), h1.get("Foo"));
assertEquals(1, h1.size());
var h2 = new Headers(h1);
assertEquals(h2.get("Foo"), List.of("Bar"));
assertEquals(h2.size(), 1);
assertEquals(List.of("Bar"), h2.get("Foo"));
assertEquals(1, h2.size());
assertEquals(h1, h2);
assertEquals(h2, h1);
h1.set("Foo", "Barbar");
assertNotEquals(h1, h2);
assertNotEquals(h2, h1);
}
}
@Test
public static void testMutableHeaders() {
public void testMutableHeaders() {
{
var h = new Headers();
h.add("Foo", "Bar");
@ -400,7 +401,7 @@ public class HeadersTest {
}
@Test
public static void testOfNull() {
public void testOfNull() {
assertThrows(NPE, () -> Headers.of((String[])null));
assertThrows(NPE, () -> Headers.of(null, "Bar"));
assertThrows(NPE, () -> Headers.of("Foo", null));
@ -426,41 +427,40 @@ public class HeadersTest {
}
@Test
public static void testOf() {
public void testOf() {
final var h = Headers.of("a", "1", "b", "2");
assertEquals(h.size(), 2);
assertEquals(2, h.size());
List.of("a", "b").forEach(n -> assertTrue(h.containsKey(n)));
List.of("1", "2").forEach(v -> assertTrue(h.containsValue(List.of(v))));
}
@Test
public static void testOfEmpty() {
public void testOfEmpty() {
for (var h : List.of(Headers.of(), Headers.of(new String[] { }))) {
assertEquals(h.size(), 0);
assertEquals(0, h.size());
assertTrue(h.isEmpty());
}
}
@Test
public static void testOfNumberOfElements() {
public void testOfNumberOfElements() {
assertThrows(IAE, () -> Headers.of("a"));
assertThrows(IAE, () -> Headers.of("a", "1", "b"));
}
@Test
public static void testOfMultipleValues() {
public void testOfMultipleValues() {
final var h = Headers.of("a", "1", "b", "1", "b", "2", "b", "3");
assertEquals(h.size(), 2);
assertEquals(2, h.size());
List.of("a", "b").forEach(n -> assertTrue(h.containsKey(n)));
List.of(List.of("1"), List.of("1", "2", "3")).forEach(v -> assertTrue(h.containsValue(v)));
}
@Test
public static void testNormalizeOnNull() {
public void testNormalizeOnNull() {
assertThrows(NullPointerException.class, () -> normalize(null));
}
@DataProvider
public static Object[][] illegalKeys() {
var illegalChars = List.of('\r', '\n');
var illegalStrings = Stream
@ -478,12 +478,12 @@ public class HeadersTest {
.toArray(Object[][]::new);
}
@Test(dataProvider = "illegalKeys")
public static void testNormalizeOnIllegalKeys(String illegalKey) {
@ParameterizedTest
@MethodSource("illegalKeys")
public void testNormalizeOnIllegalKeys(String illegalKey) {
assertThrows(IllegalArgumentException.class, () -> normalize(illegalKey));
}
@DataProvider
public static Object[][] normalizedKeys() {
return new Object[][]{
// Empty string
@ -501,13 +501,13 @@ public class HeadersTest {
};
}
@Test(dataProvider = "normalizedKeys")
public static void testNormalizeOnNormalizedKeys(String normalizedKey) {
@ParameterizedTest
@MethodSource("normalizedKeys")
public void testNormalizeOnNormalizedKeys(String normalizedKey) {
// Verify that the fast-path is taken
assertSame(normalize(normalizedKey), normalizedKey);
}
@DataProvider
public static Object[][] notNormalizedKeys() {
return new Object[][]{
{"a"},
@ -517,14 +517,15 @@ public class HeadersTest {
};
}
@Test(dataProvider = "notNormalizedKeys")
public static void testNormalizeOnNotNormalizedKeys(String notNormalizedKey) {
@ParameterizedTest
@MethodSource("notNormalizedKeys")
public void testNormalizeOnNotNormalizedKeys(String notNormalizedKey) {
var normalizedKey = normalize(notNormalizedKey);
// Verify that the fast-path is *not* taken
assertNotSame(normalizedKey, notNormalizedKey);
// Verify the result
var expectedNormalizedKey = normalizedKey.substring(0, 1).toUpperCase() + normalizedKey.substring(1);
assertEquals(normalizedKey, expectedNormalizedKey);
assertEquals(expectedNormalizedKey, normalizedKey);
}
private static String normalize(String key) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,7 +26,7 @@
* @bug 8269692
* @summary HttpContext::createContext should throw IllegalArgumentException
* if context already exists
* @run testng/othervm HttpContextTest
* @run junit/othervm HttpContextTest
*/
import java.io.IOException;
@ -34,22 +34,23 @@ import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class HttpContextTest {
static final Class<IllegalArgumentException> IAE = IllegalArgumentException.class;
@Test
public static void test() throws IOException {
public void test() throws IOException {
final var server = HttpServer.create(null, 0);
final var path = "/foo/";
assertThrows(IAE, () -> server.removeContext(path));
HttpContext context = server.createContext(path);
assertEquals(context.getPath(), path);
assertEquals(path, context.getPath());
assertThrows(IAE, () -> server.createContext(path));
assertThrows(IAE, () -> server.createContext(path, new Handler()));
@ -60,7 +61,7 @@ public class HttpContextTest {
assertThrows(IAE, () -> server.removeContext(path));
context = server.createContext(path, new Handler());
assertEquals(context.getPath(), path);
assertEquals(path, context.getPath());
assertThrows(IAE, () -> server.createContext(path));
assertThrows(IAE, () -> server.createContext(path, new Handler()));
server.removeContext(path);
@ -72,7 +73,7 @@ public class HttpContextTest {
* shares the prefix of an existing context.
*/
@Test
public static void testSubcontext() throws IOException {
public void testSubcontext() throws IOException {
final var server = HttpServer.create(null, 0);
server.createContext("/foo/bar/");
server.createContext("/foo/");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,13 +25,13 @@
* @test
* @bug 8251496
* @summary Tests for methods in HttpPrincipal
* @run testng/othervm HttpPrincipalTest
* @run junit/othervm HttpPrincipalTest
*/
import com.sun.net.httpserver.HttpPrincipal;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class HttpPrincipalTest {
@ -39,10 +39,10 @@ public class HttpPrincipalTest {
public void testGetters() {
var principal = new HttpPrincipal("test", "123");
assertEquals(principal.getUsername(), "test");
assertEquals(principal.getRealm(), "123");
assertEquals(principal.getName(), "123:test");
assertEquals(principal.toString(), principal.getName());
assertEquals(("test"+"123").hashCode(), principal.hashCode());
assertEquals("test", principal.getUsername());
assertEquals("123", principal.getRealm());
assertEquals("123:test", principal.getName());
assertEquals(principal.getName(), principal.toString());
assertEquals(principal.hashCode(), ("test"+"123").hashCode());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,19 +25,19 @@
* @test
* @bug 8270286
* @summary Test for HttpServerProvider::loadProviderFromProperty
* @run testng/othervm
* @run junit/othervm
* -Dcom.sun.net.httpserver.HttpServerProvider=HttpServerProviderTest$ProviderP
* HttpServerProviderTest
* @run testng/othervm
* @run junit/othervm
* -Dcom.sun.net.httpserver.HttpServerProvider=HttpServerProviderTest$ProviderPNPC
* HttpServerProviderTest
* @run testng/othervm
* @run junit/othervm
* -Dcom.sun.net.httpserver.HttpServerProvider=HttpServerProviderTest$ProviderNP
* HttpServerProviderTest
* @run testng/othervm
* @run junit/othervm
* -Dcom.sun.net.httpserver.HttpServerProvider=HttpServerProviderTest$ProviderT
* HttpServerProviderTest
* @run testng/othervm
* @run junit/othervm
* -Dcom.sun.net.httpserver.HttpServerProvider=DoesNotExist
* HttpServerProviderTest
*/
@ -48,10 +48,11 @@ import java.util.ServiceConfigurationError;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.expectThrows;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
public class HttpServerProviderTest {
public final static String PROPERTY_KEY = "com.sun.net.httpserver.HttpServerProvider";
@ -70,7 +71,7 @@ public class HttpServerProviderTest {
private void testPublic() throws Exception {
var n = ProviderP.class.getName();
assertEquals(System.getProperty(PROPERTY_KEY), n);
assertEquals(n, System.getProperty(PROPERTY_KEY));
var p = HttpServerProvider.provider();
assertNull(p.createHttpServer(null, 0));
@ -79,39 +80,39 @@ public class HttpServerProviderTest {
private void testPublicNonPublicConstructor() {
var n = ProviderPNPC.class.getName();
assertEquals(System.getProperty(PROPERTY_KEY), n);
assertEquals(n, System.getProperty(PROPERTY_KEY));
var e = expectThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(e.getClass(), ServiceConfigurationError.class);
assertEquals(e.getCause().getClass(), IllegalAccessException.class);
var e = Assertions.assertThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(ServiceConfigurationError.class, e.getClass());
assertEquals(IllegalAccessException.class, e.getCause().getClass());
}
private void testNonPublic() {
var n = ProviderNP.class.getName();
assertEquals(System.getProperty(PROPERTY_KEY), n);
assertEquals(n, System.getProperty(PROPERTY_KEY));
var e = expectThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(e.getClass(), ServiceConfigurationError.class);
assertEquals(e.getCause().getClass(), IllegalAccessException.class);
var e = Assertions.assertThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(ServiceConfigurationError.class, e.getClass());
assertEquals(IllegalAccessException.class, e.getCause().getClass());
}
private void testThrowingConstructor() {
var cn = ProviderT.class.getName();
assertEquals(System.getProperty(PROPERTY_KEY), cn);
assertEquals(cn, System.getProperty(PROPERTY_KEY));
var e = expectThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(e.getClass(), ServiceConfigurationError.class);
assertEquals(e.getCause().getClass(), InvocationTargetException.class);
assertEquals(e.getCause().getCause().getMessage(), "throwing constructor");
var e = Assertions.assertThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(ServiceConfigurationError.class, e.getClass());
assertEquals(InvocationTargetException.class, e.getCause().getClass());
assertEquals("throwing constructor", e.getCause().getCause().getMessage());
}
private void testBadData() {
var cn = "DoesNotExist";
assertEquals(System.getProperty(PROPERTY_KEY), cn);
assertEquals(cn, System.getProperty(PROPERTY_KEY));
var e = expectThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(e.getClass(), ServiceConfigurationError.class);
assertEquals(e.getCause().getClass(), ClassNotFoundException.class);
var e = Assertions.assertThrows(ServiceConfigurationError.class, HttpServerProvider::provider);
assertEquals(ServiceConfigurationError.class, e.getClass());
assertEquals(ClassNotFoundException.class, e.getCause().getClass());
}
/**

View File

@ -28,8 +28,8 @@
* read the request body and sends back a reply with no content, or when
* the client closes its outputstream while the server tries to drains
* its content.
* @run testng/othervm InputNotRead
* @run testng/othervm -Djava.net.preferIPv6Addresses=true InputNotRead
* @run junit/othervm InputNotRead
* @run junit/othervm -Djava.net.preferIPv6Addresses=true InputNotRead
*/
import java.io.BufferedReader;
@ -51,11 +51,12 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.testng.annotations.Test;
import static java.nio.charset.StandardCharsets.*;
import static com.sun.net.httpserver.HttpExchange.RSPBODY_EMPTY;
import org.junit.jupiter.api.Test;
public class InputNotRead {
private static final int msgCode = 200;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,7 +26,7 @@
* @bug 8251496 8333590
* @summary Test that UnmodifiableHeaders is in fact immutable
* @modules jdk.httpserver/sun.net.httpserver:+open
* @run testng/othervm UnmodifiableHeadersTest
* @run junit/othervm UnmodifiableHeadersTest
*/
import java.io.InputStream;
@ -36,73 +36,75 @@ import java.net.URI;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import sun.net.httpserver.UnmodifiableHeaders;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class UnmodifiableHeadersTest {
@Test
public static void testEquality() {
public void testEquality() {
var headers = new Headers();
var unmodifiableHeaders1 = new UnmodifiableHeaders(headers);
assertEquals(unmodifiableHeaders1, headers);
assertEquals(unmodifiableHeaders1.hashCode(), headers.hashCode());
assertEquals(unmodifiableHeaders1.get("Foo"), headers.get("Foo"));
assertEquals(headers, unmodifiableHeaders1);
assertEquals(headers.hashCode(), unmodifiableHeaders1.hashCode());
assertEquals(headers.get("Foo"), unmodifiableHeaders1.get("Foo"));
headers.add("Foo", "Bar");
var unmodifiableHeaders2 = new UnmodifiableHeaders(headers);
assertEquals(unmodifiableHeaders2, headers);
assertEquals(unmodifiableHeaders2.hashCode(), headers.hashCode());
assertEquals(unmodifiableHeaders2.get("Foo"), headers.get("Foo"));
assertEquals(headers, unmodifiableHeaders2);
assertEquals(headers.hashCode(), unmodifiableHeaders2.hashCode());
assertEquals(headers.get("Foo"), unmodifiableHeaders2.get("Foo"));
}
@DataProvider
public Object[][] headers() {
public static Stream<Headers> headers() {
var headers = new Headers();
headers.add("Foo", "Bar");
var exchange = new TestHttpExchange(headers);
return new Object[][] {
{ exchange.getRequestHeaders() },
{ Headers.of("Foo", "Bar") },
{ Headers.of(Map.of("Foo", List.of("Bar"))) },
};
return Stream.of(exchange.getRequestHeaders(),
Headers.of("Foo", "Bar"),
Headers.of(Map.of("Foo", List.of("Bar"))));
}
@Test(dataProvider = "headers")
public static void testUnmodifiableHeaders(Headers headers) {
@ParameterizedTest
@MethodSource("headers")
public void testUnmodifiableHeaders(Headers headers) {
assertUnsupportedOperation(headers);
assertUnmodifiableCollection(headers);
assertUnmodifiableList(headers);
}
@DataProvider
public Object[][] toStringHeaders() {
public static Stream<Headers> toStringHeaders() {
final Headers headers = new Headers();
headers.add("hello", "World");
return new Object[][] {
{ headers },
{ Headers.of("abc", "XYZ") },
{ Headers.of(Map.of("foo", List.of("Bar"))) },
{ Headers.of(Map.of("Hello", List.of())) },
{ Headers.of(Map.of("one", List.of("two", "THREE"))) },
};
return Stream.of(
headers,
Headers.of("abc", "XYZ"),
Headers.of(Map.of("foo", List.of("Bar"))),
Headers.of(Map.of("Hello", List.of())),
Headers.of(Map.of("one", List.of("two", "THREE")))
);
}
/*
* Verify that the String returned by Headers.toString() contains the expected
* key/value(s)
*/
@Test(dataProvider = "toStringHeaders")
@ParameterizedTest
@MethodSource("toStringHeaders")
public void testToString(final Headers headers) {
final Headers copy = Headers.of(headers);
assertNotNull(copy, "Headers.of() returned null");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -27,18 +27,20 @@
* @library /test/lib
* @summary Ensure that correct exceptions are being thrown in
* BasicAuthenticator constructor
* @run testng BasicAuthenticatorExceptionCheck
* @run junit BasicAuthenticatorExceptionCheck
*/
import java.nio.charset.Charset;
import com.sun.net.httpserver.BasicAuthenticator;
import org.testng.annotations.Test;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class BasicAuthenticatorExceptionCheck {
static final Class<NullPointerException> NPE = NullPointerException.class;
@ -62,42 +64,42 @@ public class BasicAuthenticatorExceptionCheck {
@Test
public void testAuthenticationException() {
Throwable ex = expectThrows(NPE, () ->
Throwable ex = Assertions.assertThrows(NPE, () ->
createBasicAuthenticator("/test", null));
System.out.println("Valid realm and Null charset provided - " +
"NullPointerException thrown as expected: " + ex);
ex = expectThrows(NPE, () ->
ex = Assertions.assertThrows(NPE, () ->
createBasicAuthenticator(null, UTF_8));
System.out.println("Null realm and valid charset provided - " +
"NullPointerException thrown as expected: " + ex);
ex = expectThrows(IAE, () ->
ex = Assertions.assertThrows(IAE, () ->
createBasicAuthenticator("", UTF_8));
assertEquals(ex.getMessage(), "realm must not be empty");
assertEquals("realm must not be empty", ex.getMessage());
System.out.println("Empty string for realm and valid charset provided - " +
"IllegalArgumentException thrown as expected: " + ex);
ex = expectThrows(NPE, () ->
ex = Assertions.assertThrows(NPE, () ->
createBasicAuthenticator(null));
System.out.println("Null realm provided - " +
"NullPointerException thrown as expected: " + ex);
ex = expectThrows(IAE, () ->
ex = Assertions.assertThrows(IAE, () ->
createBasicAuthenticator(""));
assertEquals(ex.getMessage(), "realm must not be empty");
assertEquals("realm must not be empty", ex.getMessage());
System.out.println("Empty string for realm provided - " +
"IllegalArgumentException thrown as expected: " + ex);
ex = expectThrows(IAE, () ->
ex = Assertions.assertThrows(IAE, () ->
createBasicAuthenticator("\"/test\""));
assertEquals(ex.getMessage(), "realm invalid: \"/test\"");
assertEquals("realm invalid: \"/test\"", ex.getMessage());
System.out.println("Invalid string for realm provided - " +
"IllegalArgumentException thrown as expected: " + ex);
ex = expectThrows(IAE, () ->
ex = Assertions.assertThrows(IAE, () ->
createBasicAuthenticator("\""));
assertEquals(ex.getMessage(), "realm invalid: \"");
assertEquals("realm invalid: \"", ex.getMessage());
System.out.println("Invalid string for realm provided - " +
"IllegalArgumentException thrown as expected: " + ex);

View File

@ -26,7 +26,7 @@
* @summary Negative tests for java -m jdk.httpserver command
* @library /test/lib
* @modules jdk.httpserver
* @run testng/othervm CommandLineNegativeTest
* @run junit/othervm CommandLineNegativeTest
*/
import java.io.IOException;
@ -37,13 +37,14 @@ import jdk.test.lib.Platform;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static org.testng.Assert.assertFalse;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CommandLineNegativeTest {
@ -55,8 +56,8 @@ public class CommandLineNegativeTest {
static final Path TEST_FILE = TEST_DIR.resolve("file.txt");
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}
@ -64,15 +65,15 @@ public class CommandLineNegativeTest {
Files.createFile(TEST_FILE);
}
@DataProvider
public Object[][] unknownOption() {
public static Object[][] unknownOption() {
return new Object[][] {
{"--unknownOption"},
{"null"}
};
}
@Test(dataProvider = "unknownOption")
@ParameterizedTest
@MethodSource("unknownOption")
public void testBadOption(String opt) throws Throwable {
out.println("\n--- testUnknownOption, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt)
@ -80,8 +81,7 @@ public class CommandLineNegativeTest {
.shouldContain("Error: unknown option: " + opt);
}
@DataProvider
public Object[][] tooManyOptionArgs() {
public static Object[][] tooManyOptionArgs() {
return new Object[][] {
{"-b", "localhost"},
{"-d", "/some/path"},
@ -95,7 +95,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "tooManyOptionArgs")
@ParameterizedTest
@MethodSource("tooManyOptionArgs")
public void testTooManyOptionArgs(String opt, String arg) throws Throwable {
out.println("\n--- testTooManyOptionArgs, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt, arg, arg)
@ -103,8 +104,7 @@ public class CommandLineNegativeTest {
.shouldContain("Error: unknown option: " + arg);
}
@DataProvider
public Object[][] noArg() {
public static Object[][] noArg() {
return new Object[][] {
{"-b", """
-b, --bind-address - Address to bind to. Default: %s (loopback).
@ -122,7 +122,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "noArg")
@ParameterizedTest
@MethodSource("noArg")
public void testNoArg(String opt, String msg) throws Throwable {
out.println("\n--- testNoArg, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt)
@ -131,8 +132,7 @@ public class CommandLineNegativeTest {
.shouldContain(msg);
}
@DataProvider
public Object[][] invalidValue() {
public static Object[][] invalidValue() {
return new Object[][] {
{"-b", "[127.0.0.1]"},
{"-b", "badhost"},
@ -146,7 +146,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "invalidValue")
@ParameterizedTest
@MethodSource("invalidValue")
public void testInvalidValue(String opt, String val) throws Throwable {
out.println("\n--- testInvalidValue, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt, val)
@ -154,10 +155,10 @@ public class CommandLineNegativeTest {
.shouldContain("Error: invalid value given for " + opt + ": " + val);
}
@DataProvider
public Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
public static Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testPortOutOfRange(String opt) throws Throwable {
out.println("\n--- testPortOutOfRange, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt, "65536") // range 0 to 65535
@ -165,10 +166,10 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "port out of range:65536");
}
@DataProvider
public Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
public static Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootNotADirectory(String opt) throws Throwable {
out.println("\n--- testRootNotADirectory, opt=\"%s\" ".formatted(opt));
var file = TEST_FILE.toString();
@ -178,7 +179,8 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "Path is not a directory: " + file);
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootDoesNotExist(String opt) throws Throwable {
out.println("\n--- testRootDoesNotExist, opt=\"%s\" ".formatted(opt));
Path root = TEST_DIR.resolve("not/existent/dir");
@ -188,14 +190,12 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "Path does not exist: " + root.toString());
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootNotReadable(String opt) throws Throwable {
out.println("\n--- testRootNotReadable, opt=\"%s\" ".formatted(opt));
if (Platform.isWindows()) {
// Not applicable to Windows. Reason: cannot revoke an owner's read
// access to a directory that was created by that owner
throw new SkipException("cannot run on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "cannot run on Windows"); // Not applicable to Windows. Reason: cannot revoke an owner's read
// access to a directory that was created by that owner
Path root = Files.createDirectories(TEST_DIR.resolve("not/readable/dir"));
try {
root.toFile().setReadable(false, false);
@ -208,8 +208,8 @@ public class CommandLineNegativeTest {
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -27,7 +27,7 @@
* @summary Tests the java -m jdk.httpserver command with port not specified
* @modules jdk.httpserver
* @library /test/lib
* @run testng/othervm/manual CommandLinePortNotSpecifiedTest
* @run junit/othervm/manual CommandLinePortNotSpecifiedTest
*/
import java.io.IOException;
@ -39,11 +39,12 @@ import jdk.test.lib.Platform;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.lang.System.out;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CommandLinePortNotSpecifiedTest {
static final Path JAVA_HOME = Path.of(System.getProperty("java.home"));
@ -55,8 +56,8 @@ public class CommandLinePortNotSpecifiedTest {
static final String TEST_DIR_STR = TEST_DIR.toString();
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}
@ -92,8 +93,8 @@ public class CommandLinePortNotSpecifiedTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -27,7 +27,7 @@
* @library /test/lib
* @build jdk.test.lib.net.IPSupport
* @modules jdk.httpserver
* @run testng/othervm CommandLinePositiveTest
* @run junit/othervm CommandLinePositiveTest
*/
import java.io.IOException;
@ -41,12 +41,13 @@ import jdk.test.lib.net.IPSupport;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CommandLinePositiveTest {
static final String JAVA_VERSION = System.getProperty("java.version");
@ -84,8 +85,8 @@ public class CommandLinePositiveTest {
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(ROOT_DIR)) {
FileUtils.deleteFileTreeWithRetry(ROOT_DIR);
}
@ -105,16 +106,17 @@ public class CommandLinePositiveTest {
}
}
@DataProvider
public Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
public static Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testAbsDirectory(String opt) throws Throwable {
out.printf("\n--- testAbsDirectory, opt=\"%s\"%n", opt);
testDirectory(opt, ROOT_DIR_STR);
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRelDirectory(String opt) throws Throwable {
out.printf("\n--- testRelDirectory, opt=\"%s\"%n", opt);
Path rootRelDir = CWD.relativize(ROOT_DIR);
@ -129,10 +131,10 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
public static Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testPort(String opt) throws Throwable {
out.println("\n--- testPort, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt, "0")
@ -142,8 +144,7 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] helpOptions() { return new Object[][] {{"-h"}, {"-?"}, {"--help"}}; }
public static Object[][] helpOptions() { return new Object[][] {{"-h"}, {"-?"}, {"--help"}}; }
static final String USAGE_TEXT = """
Usage: java -m jdk.httpserver [-b bind address] [-p port] [-d directory]
@ -161,7 +162,8 @@ public class CommandLinePositiveTest {
-version, --version - Prints version information and exits.
To stop the server, press Ctrl + C.""".formatted(LOOPBACK_ADDR);
@Test(dataProvider = "helpOptions")
@ParameterizedTest
@MethodSource("helpOptions")
public void testHelp(String opt) throws Throwable {
out.println("\n--- testHelp, opt=\"%s\" ".formatted(opt));
simpleserver(WaitForLine.HELP_STARTUP_LINE,
@ -172,10 +174,10 @@ public class CommandLinePositiveTest {
.shouldContain(OPTIONS_TEXT);
}
@DataProvider
public Object[][] versionOptions() { return new Object[][] {{"-version"}, {"--version"}}; }
public static Object[][] versionOptions() { return new Object[][] {{"-version"}, {"--version"}}; }
@Test(dataProvider = "versionOptions")
@ParameterizedTest
@MethodSource("versionOptions")
public void testVersion(String opt) throws Throwable {
out.println("\n--- testVersion, opt=\"%s\" ".formatted(opt));
simpleserver(WaitForLine.VERSION_STARTUP_LINE,
@ -184,10 +186,10 @@ public class CommandLinePositiveTest {
.shouldHaveExitValue(0);
}
@DataProvider
public Object[][] bindOptions() { return new Object[][] {{"-b"}, {"--bind-address"}}; }
public static Object[][] bindOptions() { return new Object[][] {{"-b"}, {"--bind-address"}}; }
@Test(dataProvider = "bindOptions")
@ParameterizedTest
@MethodSource("bindOptions")
public void testBindAllInterfaces(String opt) throws Throwable {
out.println("\n--- testBindAllInterfaces, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", "-p", "0", opt, "0.0.0.0")
@ -202,7 +204,8 @@ public class CommandLinePositiveTest {
}
}
@Test(dataProvider = "bindOptions")
@ParameterizedTest
@MethodSource("bindOptions")
public void testLastOneWinsBindAddress(String opt) throws Throwable {
out.println("\n--- testLastOneWinsBindAddress, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", "-p", "0", opt, "123.4.5.6", opt, LOOPBACK_ADDR)
@ -212,7 +215,8 @@ public class CommandLinePositiveTest {
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testLastOneWinsDirectory(String opt) throws Throwable {
out.println("\n--- testLastOneWinsDirectory, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", "-p", "0", opt, ROOT_DIR_STR, opt, ROOT_DIR_STR)
@ -222,10 +226,10 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] outputOptions() { return new Object[][] {{"-o"}, {"--output"}}; }
public static Object[][] outputOptions() { return new Object[][] {{"-o"}, {"--output"}}; }
@Test(dataProvider = "outputOptions")
@ParameterizedTest
@MethodSource("outputOptions")
public void testLastOneWinsOutput(String opt) throws Throwable {
out.println("\n--- testLastOneWinsOutput, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", "-p", "0", opt, "none", opt, "verbose")
@ -235,7 +239,8 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testLastOneWinsPort(String opt) throws Throwable {
out.println("\n--- testLastOneWinsPort, opt=\"%s\" ".formatted(opt));
simpleserver(JAVA, LOCALE_OPT, "-m", "jdk.httpserver", opt, "-999", opt, "0")
@ -245,8 +250,8 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(ROOT_DIR)) {
FileUtils.deleteFileTreeWithRetry(ROOT_DIR);
}

View File

@ -27,7 +27,7 @@
* file system
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
* @run testng/othervm CustomFileSystemTest
* @run junit/othervm CustomFileSystemTest
*/
import java.io.IOException;
@ -71,16 +71,18 @@ import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.Platform;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.SkipException;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CustomFileSystemTest {
static final InetSocketAddress LOOPBACK_ADDR = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
@ -88,8 +90,8 @@ public class CustomFileSystemTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -111,11 +113,11 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "some text");
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(200, response.statusCode());
assertEquals("some text", response.body());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
} finally {
server.stop(0);
}
@ -140,11 +142,11 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -164,11 +166,11 @@ public class CustomFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, "aFile.txt"))
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -194,18 +196,17 @@ public class CustomFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, ""))
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
}
@DataProvider
public Object[][] indexFiles() {
public static Object[][] indexFiles() {
var fileContent = openHTML + """
<h1>This is an index file</h1>
""" + closeHTML;
@ -221,7 +222,8 @@ public class CustomFileSystemTest {
};
}
@Test(dataProvider = "indexFiles")
@ParameterizedTest
@MethodSource("indexFiles")
public void testDirectoryWithIndexGET(String id,
String filename,
String contentType,
@ -241,11 +243,11 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), contentType);
assertEquals(response.headers().firstValue("content-length").get(), contentLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals(contentType, response.headers().firstValue("content-type").get());
assertEquals(contentLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
if (serveIndexFile) {
@ -256,9 +258,7 @@ public class CustomFileSystemTest {
@Test
public void testNotReadableFileGET() throws Exception {
if (Platform.isWindows()) {
throw new SkipException("Not applicable on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "Not applicable on Windows");
var expectedBody = openHTML + """
<h1>File not found</h1>
<p>&#x2F;aFile.txt</p>
@ -276,9 +276,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
file.toFile().setReadable(true, false);
@ -287,9 +287,7 @@ public class CustomFileSystemTest {
@Test
public void testNotReadableSegmentGET() throws Exception {
if (Platform.isWindows()) {
throw new SkipException("Not applicable on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "Not applicable on Windows");
var expectedBody = openHTML + """
<h1>File not found</h1>
<p>&#x2F;dir&#x2F;aFile.txt</p>
@ -309,9 +307,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
dir.toFile().setReadable(true, false);
@ -333,9 +331,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile?#.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -356,9 +354,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -380,9 +378,9 @@ public class CustomFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt"))
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), "");
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -406,9 +404,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "symlink")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -433,21 +431,21 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "symlink/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
}
private void createSymLink(Path symlink, Path target) {
private static void createSymLink(Path symlink, Path target) {
try {
Files.createSymbolicLink(symlink, target);
} catch (UnsupportedOperationException uoe) {
throw new SkipException("sym link creation not supported", uoe);
Assumptions.abort("sym link creation not supported");
} catch (IOException ioe) {
throw new SkipException("probably insufficient privileges to create sym links (Windows)", ioe);
Assumptions.abort("probably insufficient privileges to create sym links (Windows)");
}
}
@ -470,9 +468,9 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, fileName)).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -494,15 +492,15 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, ".hiddenDirectory/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
}
private Path createHiddenFile(Path root) throws IOException {
private static Path createHiddenFile(Path root) throws IOException {
Path file;
if (Platform.isWindows()) {
file = Files.createFile(root.resolve("aFile.txt"));
@ -514,7 +512,7 @@ public class CustomFileSystemTest {
return file;
}
private Path createFileInHiddenDirectory(Path root) throws IOException {
private static Path createFileInHiddenDirectory(Path root) throws IOException {
Path dir;
Path file;
if (Platform.isWindows()) {
@ -549,17 +547,17 @@ public class CustomFileSystemTest {
var uri = uri(server, "aDirectory");
var request = HttpRequest.newBuilder(uri).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 301);
assertEquals(response.headers().firstValue("content-length").get(), "0");
assertEquals(response.headers().firstValue("location").get(), "/aDirectory/");
assertEquals(301, response.statusCode());
assertEquals("0", response.headers().firstValue("content-length").get());
assertEquals("/aDirectory/", response.headers().firstValue("location").get());
// tests that query component is preserved during redirect
var uri2 = uri(server, "aDirectory", "query");
var req2 = HttpRequest.newBuilder(uri2).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 301);
assertEquals(res2.headers().firstValue("content-length").get(), "0");
assertEquals(res2.headers().firstValue("location").get(), "/aDirectory/?query");
assertEquals(301, res2.statusCode());
assertEquals("0", res2.headers().firstValue("content-length").get());
assertEquals("/aDirectory/?query", res2.headers().firstValue("location").get());
}
{ // tests that redirect to returned relative URI works
@ -568,10 +566,10 @@ public class CustomFileSystemTest {
var uri = uri(server, "aDirectory");
var request = HttpRequest.newBuilder(uri).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), expectedBody);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(200, response.statusCode());
assertEquals(expectedBody, response.body());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
}
} finally {
server.stop(0);
@ -588,7 +586,7 @@ public class CustomFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "beginDelim%3C%3EEndDelim")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(404, response.statusCode());
assertTrue(response.body().contains("beginDelim%3C%3EEndDelim"));
assertTrue(response.body().contains("File not found"));
} finally {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -24,7 +24,7 @@
/*
* @test
* @summary Tests for FileServerHandler
* @run testng FileServerHandlerTest
* @run junit FileServerHandlerTest
*/
import java.io.ByteArrayInputStream;
@ -44,42 +44,44 @@ import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class FileServerHandlerTest {
static final Path CWD = Path.of(".").toAbsolutePath();
static final Class<RuntimeException> RE = RuntimeException.class;
@DataProvider
public Object[][] notAllowedMethods() {
public static Object[][] notAllowedMethods() {
var l = List.of("POST", "PUT", "DELETE", "TRACE", "OPTIONS");
return l.stream().map(s -> new Object[] { s }).toArray(Object[][]::new);
}
@Test(dataProvider = "notAllowedMethods")
@ParameterizedTest
@MethodSource("notAllowedMethods")
public void testNotAllowedRequestMethod(String requestMethod) throws Exception {
var handler = SimpleFileServer.createFileHandler(CWD);
var exchange = new MethodHttpExchange(requestMethod);
handler.handle(exchange);
assertEquals(exchange.rCode, 405);
assertEquals(exchange.getResponseHeaders().getFirst("allow"), "HEAD, GET");
assertEquals(405, exchange.rCode);
assertEquals("HEAD, GET", exchange.getResponseHeaders().getFirst("allow"));
}
@DataProvider
public Object[][] notImplementedMethods() {
public static Object[][] notImplementedMethods() {
var l = List.of("GARBAGE", "RUBBISH", "TRASH", "FOO", "BAR");
return l.stream().map(s -> new Object[] { s }).toArray(Object[][]::new);
}
@Test(dataProvider = "notImplementedMethods")
@ParameterizedTest
@MethodSource("notImplementedMethods")
public void testNotImplementedRequestMethod(String requestMethod) throws Exception {
var handler = SimpleFileServer.createFileHandler(CWD);
var exchange = new MethodHttpExchange(requestMethod);
handler.handle(exchange);
assertEquals(exchange.rCode, 501);
assertEquals(501, exchange.rCode);
}
// 301 and 404 response codes tested in SimpleFileServerTest
@ -93,8 +95,8 @@ public class FileServerHandlerTest {
throw new RuntimeException("getRequestBody");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getRequestBody");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getRequestBody", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange("GET") {
@ -102,8 +104,8 @@ public class FileServerHandlerTest {
throw new RuntimeException("getResponseHeaders");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getResponseHeaders");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getResponseHeaders", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange("GET") {
@ -111,8 +113,8 @@ public class FileServerHandlerTest {
throw new RuntimeException("sendResponseHeaders");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "sendResponseHeaders");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("sendResponseHeaders", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange("GET") {
@ -120,8 +122,8 @@ public class FileServerHandlerTest {
throw new RuntimeException("getResponseBody");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getResponseBody");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getResponseBody", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange("GET") {
@ -129,8 +131,8 @@ public class FileServerHandlerTest {
throw new RuntimeException("close");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "close");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("close", t.getMessage());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,7 +26,7 @@
* @summary Tests for HttpHandlers
* @library /test/lib
* @build jdk.test.lib.net.URIBuilder
* @run testng/othervm HttpHandlersTest
* @run junit/othervm HttpHandlersTest
*/
import java.io.IOException;
@ -44,12 +44,14 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import jdk.test.lib.net.URIBuilder;
import com.sun.net.httpserver.*;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HttpHandlersTest {
@ -61,8 +63,8 @@ public class HttpHandlersTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() {
@BeforeAll
public static void setup() {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -103,11 +105,11 @@ public class HttpHandlersTest {
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertTrue(response.headers().map().containsKey("date"));
assertEquals(response.headers().firstValue("foo").get(), "bar");
assertEquals(response.headers().firstValue("content-length").get(), "0");
assertEquals(response.headers().map().size(), 3);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "");
assertEquals("bar", response.headers().firstValue("foo").get());
assertEquals("0", response.headers().firstValue("content-length").get());
assertEquals(3, response.headers().map().size());
assertEquals(200, response.statusCode());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -125,11 +127,11 @@ public class HttpHandlersTest {
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertTrue(response.headers().map().containsKey("date"));
assertEquals(response.headers().firstValue("foo").get(), "bar");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "hello world");
assertEquals("bar", response.headers().firstValue("foo").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(3, response.headers().map().size());
assertEquals(200, response.statusCode());
assertEquals("hello world", response.body());
} finally {
server.stop(0);
}
@ -148,9 +150,9 @@ public class HttpHandlersTest {
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertTrue(response.headers().map().containsKey("date"));
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().map().size(), 2);
assertEquals(response.statusCode(), 200);
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(2, response.headers().map().size());
assertEquals(200, response.statusCode());
} finally {
server.stop(0);
}
@ -168,22 +170,22 @@ public class HttpHandlersTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertNotEquals(response.headers().firstValue("date").get(), "12345");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().map().size(), 2);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "hello world");
assertNotEquals("12345", response.headers().firstValue("date").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(2, response.headers().map().size());
assertEquals(200, response.statusCode());
assertEquals("hello world", response.body());
} finally {
server.stop(0);
}
}
@DataProvider
public Object[][] responseBodies() {
public static Object[][] responseBodies() {
return new Object[][] { {"hello world"}, {""} };
}
@Test(dataProvider = "responseBodies")
@ParameterizedTest
@MethodSource("responseBodies")
public void testOfThrowingExchange(String body) {
var h = HttpHandlers.of(200, Headers.of(), body);
{
@ -192,8 +194,8 @@ public class HttpHandlersTest {
throw new RuntimeException("getRequestBody");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getRequestBody");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getRequestBody", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange() {
@ -201,8 +203,8 @@ public class HttpHandlersTest {
throw new RuntimeException("getResponseHeaders");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getResponseHeaders");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getResponseHeaders", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange() {
@ -210,8 +212,8 @@ public class HttpHandlersTest {
throw new RuntimeException("sendResponseHeaders");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "sendResponseHeaders");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("sendResponseHeaders", t.getMessage());
}
{
var exchange = new ThrowingHttpExchange() {
@ -220,8 +222,8 @@ public class HttpHandlersTest {
}
};
if (!body.isEmpty()) { // getResponseBody not called if no responseBody
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "getResponseBody");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("getResponseBody", t.getMessage());
}
}
{
@ -230,8 +232,8 @@ public class HttpHandlersTest {
throw new RuntimeException("close");
}
};
var t = expectThrows(RE, () -> h.handle(exchange));
assertEquals(t.getMessage(), "close");
var t = assertThrows(RE, () -> h.handle(exchange));
assertEquals("close", t.getMessage());
}
}
@ -247,8 +249,8 @@ public class HttpHandlersTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "TestHandler-1");
assertEquals(200, response.statusCode());
assertEquals("TestHandler-1", response.body());
} finally {
server.stop(0);
}
@ -266,8 +268,8 @@ public class HttpHandlersTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "TestHandler-2");
assertEquals(200, response.statusCode());
assertEquals("TestHandler-2", response.body());
} finally {
server.stop(0);
}
@ -287,8 +289,8 @@ public class HttpHandlersTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "TestHandler-2");
assertEquals(200, response.statusCode());
assertEquals("TestHandler-2", response.body());
} finally {
server.stop(0);
}

View File

@ -27,15 +27,13 @@
* @summary Test if HttpsServer sends the TLS alerts produced
* @library /test/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm HttpsServerAlertTest
* @run junit/othervm HttpsServerAlertTest
*/
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
@ -50,7 +48,9 @@ import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.testng.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class HttpsServerAlertTest {
@ -65,8 +65,8 @@ public class HttpsServerAlertTest {
SSLContext.setDefault(sslContext);
}
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);

View File

@ -26,7 +26,7 @@
* @summary Test for HttpsServer::create
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
* @run testng/othervm HttpsServerTest
* @run junit/othervm HttpsServerTest
*/
import java.io.IOException;
@ -51,12 +51,13 @@ import com.sun.net.httpserver.HttpsServer;
import javax.net.ssl.SSLContext;
import jdk.test.lib.net.SimpleSSLContext;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class HttpsServerTest {
@ -72,8 +73,8 @@ public class HttpsServerTest {
SSLContext.setDefault(sslContext);
}
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -97,12 +98,12 @@ public class HttpsServerTest {
final var s1 = HttpsServer.create(null, 0);
assertNull(s1.getAddress());
s1.bind((LOOPBACK_ADDR), 0);
assertEquals(s1.getAddress().getAddress(), LOOPBACK_ADDR.getAddress());
assertEquals(LOOPBACK_ADDR.getAddress(), s1.getAddress().getAddress());
final var s2 = HttpsServer.create(null, 0, "/foo/", new Handler());
assertNull(s2.getAddress());
s2.bind(LOOPBACK_ADDR, 0);
assertEquals(s2.getAddress().getAddress(), LOOPBACK_ADDR.getAddress());
assertEquals(LOOPBACK_ADDR.getAddress(), s2.getAddress().getAddress());
s2.removeContext("/foo/"); // throws if context doesn't exist
}
@ -119,11 +120,10 @@ public class HttpsServerTest {
.build();
var request = HttpRequest.newBuilder(uri(server, "/test")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "hello world");
assertEquals(response.headers().firstValue("content-length").get(),
Integer.toString("hello world".length()));
assertEquals(response.statusCode(), filter.responseCode.get().intValue());
assertEquals(200, response.statusCode());
assertEquals("hello world", response.body());
assertEquals( Integer.toString("hello world".length()), response.headers().firstValue("content-length").get());
assertEquals(filter.responseCode.get().intValue(), response.statusCode());
} finally {
server.stop(0);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -37,14 +37,15 @@ import java.util.logging.Logger;
import jdk.test.lib.net.URIBuilder;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -52,7 +53,7 @@ import static org.testng.Assert.assertTrue;
* set of binary request sequences
* @library /test/lib
* @build jdk.test.lib.net.URIBuilder
* @run testng/othervm IdempotencyAndCommutativityTest
* @run junit/othervm IdempotencyAndCommutativityTest
*/
public class IdempotencyAndCommutativityTest {
@ -69,8 +70,8 @@ public class IdempotencyAndCommutativityTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -89,8 +90,7 @@ public class IdempotencyAndCommutativityTest {
record ExchangeValues(String method, String resource, int respCode, String contentType) {}
// Creates an exhaustive set of binary exchange sequences
@DataProvider
public Object[][] allBinarySequences() {
public static Object[][] allBinarySequences() {
final List<ExchangeValues> sequences = List.of(
new ExchangeValues("GET", FILE_NAME, 200, "text/plain"),
new ExchangeValues("GET", DIR_NAME, 200, "text/html; charset=UTF-8"),
@ -108,7 +108,8 @@ public class IdempotencyAndCommutativityTest {
.toArray(Object[][]::new);
}
@Test(dataProvider = "allBinarySequences")
@ParameterizedTest
@MethodSource("allBinarySequences")
public void testBinarySequences(ExchangeValues e1, ExchangeValues e2) throws Exception {
System.out.println("---");
System.out.println(e1);
@ -122,15 +123,15 @@ public class IdempotencyAndCommutativityTest {
.method(e.method(), HttpRequest.BodyPublishers.noBody())
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), e.respCode());
assertEquals(e.respCode(), response.statusCode());
if (e.contentType != null) {
assertEquals(response.headers().firstValue("content-type").get(), e.contentType());
assertEquals(e.contentType(), response.headers().firstValue("content-type").get());
} else {
assertTrue(response.headers().firstValue("content-type").isEmpty());
}
}
@AfterTest
@AfterAll
public static void teardown() {
server.stop(0);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -27,7 +27,7 @@
* system path
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
* @run testng/othervm MapToPathTest
* @run junit/othervm MapToPathTest
*/
import java.io.IOException;
@ -55,13 +55,14 @@ import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class MapToPathTest {
@ -74,8 +75,8 @@ public class MapToPathTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -88,7 +89,7 @@ public class MapToPathTest {
createDirectories(TEST_DIR);
}
private void createDirectories(Path testDir) throws IOException {
private static void createDirectories(Path testDir) throws IOException {
// Create directory tree:
//
// |-- TEST_DIR
@ -124,40 +125,40 @@ public class MapToPathTest {
try {
var req1 = HttpRequest.newBuilder(uri(server, "/")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(res1.headers().firstValue("content-length").get(), Long.toString(257L));
assertEquals(res1.headers().firstValue("last-modified").get(), getLastModified(TEST_DIR));
assertEquals(200, res1.statusCode());
assertEquals("text/html; charset=UTF-8", res1.headers().firstValue("content-type").get());
assertEquals(Long.toString(257L), res1.headers().firstValue("content-length").get());
assertEquals(getLastModified(TEST_DIR), res1.headers().firstValue("last-modified").get());
var req2 = HttpRequest.newBuilder(uri(server, "/../")).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 404); // cannot escape root
assertEquals(404, res2.statusCode()); // cannot escape root
var req3 = HttpRequest.newBuilder(uri(server, "/foo/bar/baz/c://")).build();
var res3 = client.send(req3, BodyHandlers.ofString());
assertEquals(res3.statusCode(), 404); // not found
assertEquals(404, res3.statusCode()); // not found
var req4 = HttpRequest.newBuilder(uri(server, "/foo/bar/baz/c:.//")).build();
var res4 = client.send(req4, BodyHandlers.ofString());
assertEquals(res4.statusCode(), 404); // not found
assertEquals(404, res4.statusCode()); // not found
var req5 = HttpRequest.newBuilder(uri(server, "/foo/bar/baz/c:..//")).build();
var res5 = client.send(req5, BodyHandlers.ofString());
assertEquals(res5.statusCode(), 404); // not found
assertEquals(404, res5.statusCode()); // not found
var req6 = HttpRequest.newBuilder(uri(server, "/foo/file:" + TEST_DIR.getParent())).build();
var res6 = client.send(req6, BodyHandlers.ofString());
assertEquals(res6.statusCode(), 404); // not found
assertEquals(404, res6.statusCode()); // not found
var req7 = HttpRequest.newBuilder(uri(server, "/foo/bar/\\..\\../")).build();
var res7 = client.send(req7, BodyHandlers.ofString());
assertEquals(res7.statusCode(), 404); // not found
assertEquals(404, res7.statusCode()); // not found
var req8 = HttpRequest.newBuilder(uri(server, "/foo")).build();
var res8 = client.send(req8, BodyHandlers.ofString());
assertEquals(res8.statusCode(), 301); // redirect
assertEquals(res8.headers().firstValue("content-length").get(), "0");
assertEquals(res8.headers().firstValue("location").get(), "/foo/");
assertEquals(301, res8.statusCode()); // redirect
assertEquals("0", res8.headers().firstValue("content-length").get());
assertEquals("/foo/", res8.headers().firstValue("location").get());
} finally {
server.stop(0);
}
@ -169,15 +170,15 @@ public class MapToPathTest {
try {
var req1 = HttpRequest.newBuilder(uri(server, "/browse/file.txt")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "testdir");
assertEquals(res1.headers().firstValue("content-type").get(), "text/plain");
assertEquals(res1.headers().firstValue("content-length").get(), Long.toString(7L));
assertEquals(res1.headers().firstValue("last-modified").get(), getLastModified(TEST_DIR.resolve("file.txt")));
assertEquals(200, res1.statusCode());
assertEquals("testdir", res1.body());
assertEquals("text/plain", res1.headers().firstValue("content-type").get());
assertEquals(Long.toString(7L), res1.headers().firstValue("content-length").get());
assertEquals(getLastModified(TEST_DIR.resolve("file.txt")), res1.headers().firstValue("last-modified").get());
var req2 = HttpRequest.newBuilder(uri(server, "/store/file.txt")).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 404); // no context found
assertEquals(404, res2.statusCode()); // no context found
} finally {
server.stop(0);
}
@ -190,29 +191,29 @@ public class MapToPathTest {
try {
var req1 = HttpRequest.newBuilder(uri(server, "/foo/file.txt")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "foo");
assertEquals(res1.headers().firstValue("content-type").get(), "text/plain");
assertEquals(res1.headers().firstValue("content-length").get(), Long.toString(3L));
assertEquals(res1.headers().firstValue("last-modified").get(), getLastModified(TEST_DIR.resolve("foo").resolve("file.txt")));
assertEquals(200, res1.statusCode());
assertEquals("foo", res1.body());
assertEquals("text/plain", res1.headers().firstValue("content-type").get());
assertEquals(Long.toString(3L), res1.headers().firstValue("content-length").get());
assertEquals(getLastModified(TEST_DIR.resolve("foo").resolve("file.txt")), res1.headers().firstValue("last-modified").get());
var req2 = HttpRequest.newBuilder(uri(server, "/foobar/file.txt")).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 404); // no context found
assertEquals(404, res2.statusCode()); // no context found
var req3 = HttpRequest.newBuilder(uri(server, "/foo/../foobar/file.txt")).build();
var res3 = client.send(req3, BodyHandlers.ofString());
assertEquals(res3.statusCode(), 404); // cannot escape context
assertEquals(404, res3.statusCode()); // cannot escape context
var req4 = HttpRequest.newBuilder(uri(server, "/foo/../..")).build();
var res4 = client.send(req4, BodyHandlers.ofString());
assertEquals(res4.statusCode(), 404); // cannot escape root
assertEquals(404, res4.statusCode()); // cannot escape root
var req5 = HttpRequest.newBuilder(uri(server, "/foo/bar")).build();
var res5 = client.send(req5, BodyHandlers.ofString());
assertEquals(res5.statusCode(), 301); // redirect
assertEquals(res5.headers().firstValue("content-length").get(), "0");
assertEquals(res5.headers().firstValue("location").get(), "/foo/bar/");
assertEquals(301, res5.statusCode()); // redirect
assertEquals("0", res5.headers().firstValue("content-length").get());
assertEquals("/foo/bar/", res5.headers().firstValue("location").get());
} finally {
server.stop(0);
}
@ -225,35 +226,35 @@ public class MapToPathTest {
try {
var req1 = HttpRequest.newBuilder(uri(server, "/foo/file.txt")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "foo");
assertEquals(res1.headers().firstValue("content-type").get(), "text/plain");
assertEquals(res1.headers().firstValue("content-length").get(), Long.toString(3L));
assertEquals(res1.headers().firstValue("last-modified").get(), getLastModified(TEST_DIR.resolve("foo").resolve("file.txt")));
assertEquals(200, res1.statusCode());
assertEquals("foo", res1.body());
assertEquals("text/plain", res1.headers().firstValue("content-type").get());
assertEquals(Long.toString(3L), res1.headers().firstValue("content-length").get());
assertEquals(getLastModified(TEST_DIR.resolve("foo").resolve("file.txt")), res1.headers().firstValue("last-modified").get());
var req2 = HttpRequest.newBuilder(uri(server, "/foobar/")).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 404); // handler prevents mapping to /foo/bar
assertEquals(404, res2.statusCode()); // handler prevents mapping to /foo/bar
var req3 = HttpRequest.newBuilder(uri(server, "/foobar/file.txt")).build();
var res3 = client.send(req3, BodyHandlers.ofString());
assertEquals(res3.statusCode(), 404); // handler prevents mapping to /foo/bar/file.txt
assertEquals(404, res3.statusCode()); // handler prevents mapping to /foo/bar/file.txt
var req4 = HttpRequest.newBuilder(uri(server, "/file.txt")).build();
var res4 = client.send(req4, BodyHandlers.ofString());
assertEquals(res4.statusCode(), 404);
assertEquals(404, res4.statusCode());
var req5 = HttpRequest.newBuilder(uri(server, "/foo/bar")).build();
var res5 = client.send(req5, BodyHandlers.ofString());
assertEquals(res5.statusCode(), 301); // redirect
assertEquals(res5.headers().firstValue("content-length").get(), "0");
assertEquals(res5.headers().firstValue("location").get(), "/foo/bar/");
assertEquals(301, res5.statusCode()); // redirect
assertEquals("0", res5.headers().firstValue("content-length").get());
assertEquals("/foo/bar/", res5.headers().firstValue("location").get());
var req6 = HttpRequest.newBuilder(uri(server, "/foo")).build();
var res6 = client.send(req6, BodyHandlers.ofString());
assertEquals(res6.statusCode(), 301); // redirect
assertEquals(res6.headers().firstValue("content-length").get(), "0");
assertEquals(res6.headers().firstValue("location").get(), "/foo/");
assertEquals(301, res6.statusCode()); // redirect
assertEquals("0", res6.headers().firstValue("content-length").get());
assertEquals("/foo/", res6.headers().firstValue("location").get());
} finally {
server.stop(0);
}
@ -276,7 +277,7 @@ public class MapToPathTest {
try {
var req1 = HttpRequest.newBuilder(uri(server, "/foo/bar/c:/baz/")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 404); // not found
assertEquals(404, res1.statusCode()); // not found
} finally {
server.stop(0);
}
@ -303,32 +304,32 @@ public class MapToPathTest {
out.println("uri.Path=" + uriPath);
var req1 = HttpRequest.newBuilder(uri(server, uriPath)).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "root response body");
assertEquals(200, res1.statusCode());
assertEquals("root response body", res1.body());
}
{
var req1 = HttpRequest.newBuilder(uri(server, "/foo/file.txt")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "foo");
assertEquals(200, res1.statusCode());
assertEquals("foo", res1.body());
var req2 = HttpRequest.newBuilder(uri(server, "/foo/bar/baz/file.txt")).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 200);
assertEquals(res2.body(), "foo/bar/baz");
assertEquals(200, res2.statusCode());
assertEquals("foo/bar/baz", res2.body());
}
{
var req1 = HttpRequest.newBuilder(uri(server, "/foobar/file.txt")).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "foobar");
assertEquals(200, res1.statusCode());
assertEquals("foobar", res1.body());
}
for (String uriPath : List.of("/bar/", "/bar/t", "/bar/t/z", "/bar/index.html") ) {
out.println("uri.Path=" + uriPath);
var req1 = HttpRequest.newBuilder(uri(server, uriPath)).build();
var res1 = client.send(req1, BodyHandlers.ofString());
assertEquals(res1.statusCode(), 200);
assertEquals(res1.body(), "bar response body");
assertEquals(200, res1.statusCode());
assertEquals("bar response body", res1.body());
}
} finally {
server.stop(0);
@ -347,18 +348,18 @@ public class MapToPathTest {
out.println("uri.Query=" + query);
var req = HttpRequest.newBuilder(uri(server, "", query)).build();
var res = client.send(req, BodyHandlers.ofString());
assertEquals(res.statusCode(), 200);
assertEquals(res.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(res.headers().firstValue("content-length").get(), Long.toString(257L));
assertEquals(res.headers().firstValue("last-modified").get(), getLastModified(TEST_DIR));
assertEquals(200, res.statusCode());
assertEquals("text/html; charset=UTF-8", res.headers().firstValue("content-type").get());
assertEquals(Long.toString(257L), res.headers().firstValue("content-length").get());
assertEquals(getLastModified(TEST_DIR), res.headers().firstValue("last-modified").get());
}
} finally {
server.stop(0);
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -27,7 +27,7 @@
* @modules java.base/sun.net.www:+open
* @library /test/lib
* @build jdk.test.lib.net.URIBuilder
* @run testng/othervm -Djdk.httpclient.redirects.retrylimit=1 OutputFilterTest
* @run junit/othervm -Djdk.httpclient.redirects.retrylimit=1 OutputFilterTest
*/
import java.io.ByteArrayOutputStream;
@ -53,15 +53,17 @@ import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.*;
import static com.sun.net.httpserver.SimpleFileServer.OutputLevel.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class OutputFilterTest {
static final Class<NullPointerException> NPE = NullPointerException.class;
@ -74,8 +76,8 @@ public class OutputFilterTest {
static final boolean ENABLE_LOGGING = true;
static final Logger logger = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() {
@BeforeAll
public static void setup() {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
logger.setLevel(Level.ALL);
@ -94,10 +96,10 @@ public class OutputFilterTest {
@Test
public void testDescription() {
var filter = SimpleFileServer.createOutputFilter(OUT, VERBOSE);
assertEquals(filter.description(), "HttpExchange OutputFilter (outputLevel: VERBOSE)");
assertEquals("HttpExchange OutputFilter (outputLevel: VERBOSE)", filter.description());
filter = SimpleFileServer.createOutputFilter(OUT, INFO);
assertEquals(filter.description(), "HttpExchange OutputFilter (outputLevel: INFO)");
assertEquals("HttpExchange OutputFilter (outputLevel: INFO)", filter.description());
}
@Test
@ -120,9 +122,9 @@ public class OutputFilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 3);
assertEquals(response.body(), "hello world");
assertEquals(200, response.statusCode());
assertEquals(3, response.headers().map().size());
assertEquals("hello world", response.body());
} finally {
server.stop(0);
baos.flush();
@ -172,9 +174,9 @@ public class OutputFilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().map().size(), 2);
assertEquals(response.body(), "hello world");
assertEquals(200, response.statusCode());
assertEquals(2, response.headers().map().size());
assertEquals("hello world", response.body());
} finally {
server.stop(0);
baos.flush();
@ -207,8 +209,7 @@ public class OutputFilterTest {
}
}
@DataProvider
public Object[][] throwingHandler() {
public static Object[][] throwingHandler() {
return new Object[][] {
{VERBOSE, "Error: server exchange handling failed: IOE ThrowingHandler" + System.lineSeparator()},
{INFO, "Error: server exchange handling failed: IOE ThrowingHandler" + System.lineSeparator()},
@ -223,7 +224,8 @@ public class OutputFilterTest {
* prevent retries on the client side, which would result in more than one
* error message.
*/
@Test(dataProvider = "throwingHandler")
@ParameterizedTest
@MethodSource("throwingHandler")
public void testExchangeThrowingHandler(OutputLevel level,
String expectedOutput) throws Exception {
var baos = new ByteArrayOutputStream();
@ -243,7 +245,7 @@ public class OutputFilterTest {
} finally {
server.stop(0);
baos.flush();
assertEquals(baos.toString(UTF_8), expectedOutput);
assertEquals(expectedOutput, baos.toString(UTF_8));
}
}
@ -264,8 +266,8 @@ public class OutputFilterTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile\u0000.txt")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().map().size(), 3);
assertEquals(404, response.statusCode());
assertEquals(3, response.headers().map().size());
} finally {
server.stop(0);
baos.flush();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -24,7 +24,7 @@
/*
* @test
* @summary Tests for Request
* @run testng RequestTest
* @run junit RequestTest
*/
import java.io.InputStream;
@ -35,9 +35,10 @@ import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import com.sun.net.httpserver.*;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class RequestTest {
@ -46,8 +47,8 @@ public class RequestTest {
var headers = new Headers();
Request request = new TestHttpExchange(headers);
request = request.with("Foo", List.of("Bar"));
assertEquals(request.getRequestHeaders().size(), 1);
assertEquals(request.getRequestHeaders().get("Foo"), List.of("Bar"));
assertEquals(1, request.getRequestHeaders().size());
assertEquals(List.of("Bar"), request.getRequestHeaders().get("Foo"));
assertReadOnly(request.getRequestHeaders());
}
@ -57,9 +58,9 @@ public class RequestTest {
headers.add("Foo", "Bar");
Request request = new TestHttpExchange(headers);
request = request.with("X-Foo", List.of("Bar"));
assertEquals(request.getRequestHeaders().size(), 2);
assertEquals(request.getRequestHeaders().get("Foo"), List.of("Bar"));
assertEquals(request.getRequestHeaders().get("X-Foo"), List.of("Bar"));
assertEquals(2, request.getRequestHeaders().size());
assertEquals(List.of("Bar"), request.getRequestHeaders().get("Foo"));
assertEquals(List.of("Bar"), request.getRequestHeaders().get("X-Foo"));
assertReadOnly(request.getRequestHeaders());
}
@ -70,8 +71,8 @@ public class RequestTest {
headers.add(headerName, "Bar");
Request request = new TestHttpExchange(headers);
request = request.with(headerName, List.of("blahblahblah"));
assertEquals(request.getRequestHeaders().size(), 1);
assertEquals(request.getRequestHeaders().get(headerName), List.of("Bar"));
assertEquals(1, request.getRequestHeaders().size());
assertEquals(List.of("Bar"), request.getRequestHeaders().get(headerName));
assertReadOnly(request.getRequestHeaders());
}
@ -83,11 +84,11 @@ public class RequestTest {
request = request.with("Larry", List.of("a"))
.with("Curly", List.of("b"))
.with("Moe", List.of("c"));
assertEquals(request.getRequestHeaders().size(), 4);
assertEquals(request.getRequestHeaders().getFirst("Foo"), "Bar");
assertEquals(request.getRequestHeaders().getFirst("Larry"), "a");
assertEquals(request.getRequestHeaders().getFirst("Curly"), "b");
assertEquals(request.getRequestHeaders().getFirst("Moe" ), "c");
assertEquals(4, request.getRequestHeaders().size());
assertEquals("Bar", request.getRequestHeaders().getFirst("Foo"));
assertEquals("a", request.getRequestHeaders().getFirst("Larry"));
assertEquals("b", request.getRequestHeaders().getFirst("Curly"));
assertEquals("c", request.getRequestHeaders().getFirst("Moe" ));
assertReadOnly(request.getRequestHeaders());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -39,14 +39,14 @@ import java.util.stream.Collectors;
import jdk.test.lib.net.URIBuilder;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import sun.net.www.MimeTable;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/*
* @test
@ -54,7 +54,7 @@ import static org.testng.Assert.assertTrue;
* @modules java.base/sun.net.www:+open
* @library /test/lib
* @build jdk.test.lib.net.URIBuilder
* @run testng/othervm ServerMimeTypesResolutionTest
* @run junit/othervm ServerMimeTypesResolutionTest
*/
public class ServerMimeTypesResolutionTest {
@ -70,8 +70,8 @@ public class ServerMimeTypesResolutionTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -139,7 +139,7 @@ public class ServerMimeTypesResolutionTest {
}
@Test
public static void testMimeTypeHeaders() throws Exception {
public void testMimeTypeHeaders() throws Exception {
final var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, SimpleFileServer.OutputLevel.VERBOSE);
server.start();
try {
@ -163,8 +163,8 @@ public class ServerMimeTypesResolutionTest {
final var uri = uri(server, toFileName(extension));
final var request = HttpRequest.newBuilder(uri).build();
final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(),expectedMimeType);
assertEquals(200, response.statusCode());
assertEquals(expectedMimeType, response.headers().firstValue("content-type").get());
}
static URI uri(HttpServer server, String path) {
@ -176,7 +176,6 @@ public class ServerMimeTypesResolutionTest {
.buildUnchecked();
}
@DataProvider
public static Object[][] commonExtensions() {
Set<String> extensions = Set.of(".aac", ".abw", ".arc", ".avi", ".azw", ".bin", ".bmp", ".bz",
".bz2", ".csh", ".css", ".csv", ".doc", ".docx",".eot", ".epub", ".gz", ".gif", ".htm", ".html", ".ico",

View File

@ -26,7 +26,7 @@
* @summary Tests for SimpleFileServer
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
* @run testng/othervm SimpleFileServerTest
* @run junit/othervm SimpleFileServerTest
*/
import java.io.IOException;
@ -52,15 +52,17 @@ import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.Platform;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.SkipException;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class SimpleFileServerTest {
@ -78,8 +80,8 @@ public class SimpleFileServerTest {
static final String EXPECTED_LAST_MODIFIED_OF_FAVICON = "Mon, 23 May 1995 11:11:11 GMT";
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -105,11 +107,11 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "some text");
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(200, response.statusCode());
assertEquals("some text", response.body());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
} finally {
server.stop(0);
}
@ -134,11 +136,11 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -155,9 +157,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "favicon.ico")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "image/x-icon");
assertEquals(response.headers().firstValue("last-modified").get(), EXPECTED_LAST_MODIFIED_OF_FAVICON);
assertEquals(200, response.statusCode());
assertEquals("image/x-icon", response.headers().firstValue("content-type").get());
assertEquals(EXPECTED_LAST_MODIFIED_OF_FAVICON, response.headers().firstValue("last-modified").get());
// expect custom (and broken) icon
var file = Files.writeString(root.resolve("favicon.ico"), "broken icon", CREATE);
@ -165,19 +167,19 @@ public class SimpleFileServerTest {
var lastModified = getLastModified(file);
var expectedLength = Long.toString(Files.size(file));
response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "application/octet-stream");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(200, response.statusCode());
assertEquals("application/octet-stream", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
} finally {
Files.delete(file);
}
// expect built-in icon
response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "image/x-icon");
assertEquals(response.headers().firstValue("last-modified").get(), EXPECTED_LAST_MODIFIED_OF_FAVICON);
assertEquals(200, response.statusCode());
assertEquals("image/x-icon", response.headers().firstValue("content-type").get());
assertEquals(EXPECTED_LAST_MODIFIED_OF_FAVICON, response.headers().firstValue("last-modified").get());
} finally {
server.stop(0);
}
@ -194,10 +196,10 @@ public class SimpleFileServerTest {
var request = HttpRequest.newBuilder(uri(server, "favicon.ico"))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "image/x-icon");
assertEquals(response.headers().firstValue("last-modified").get(), EXPECTED_LAST_MODIFIED_OF_FAVICON);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("image/x-icon", response.headers().firstValue("content-type").get());
assertEquals(EXPECTED_LAST_MODIFIED_OF_FAVICON, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -217,11 +219,11 @@ public class SimpleFileServerTest {
var request = HttpRequest.newBuilder(uri(server, "aFile.txt"))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -247,18 +249,17 @@ public class SimpleFileServerTest {
var request = HttpRequest.newBuilder(uri(server, ""))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
}
@DataProvider
public Object[][] indexFiles() {
public static Object[][] indexFiles() {
var fileContent = openHTML + """
<h1>This is an index file</h1>
""" + closeHTML;
@ -274,7 +275,8 @@ public class SimpleFileServerTest {
};
}
@Test(dataProvider = "indexFiles")
@ParameterizedTest
@MethodSource("indexFiles")
public void testDirectoryWithIndexGET(String id,
String filename,
String contentType,
@ -294,11 +296,11 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), contentType);
assertEquals(response.headers().firstValue("content-length").get(), contentLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals(contentType, response.headers().firstValue("content-type").get());
assertEquals(contentLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
if (serveIndexFile) {
@ -309,9 +311,7 @@ public class SimpleFileServerTest {
@Test
public void testNotReadableFileGET() throws Exception {
if (Platform.isWindows()) {
throw new SkipException("Not applicable on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "Not applicable on Windows");
var expectedBody = openHTML + """
<h1>File not found</h1>
<p>&#x2F;aFile.txt</p>
@ -329,9 +329,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
file.toFile().setReadable(true, false);
@ -340,9 +340,7 @@ public class SimpleFileServerTest {
@Test
public void testNotReadableSegmentGET() throws Exception {
if (Platform.isWindows()) {
throw new SkipException("Not applicable on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "Not applicable on Windows");
var expectedBody = openHTML + """
<h1>File not found</h1>
<p>&#x2F;dir&#x2F;aFile.txt</p>
@ -362,9 +360,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
dir.toFile().setReadable(true, false);
@ -386,9 +384,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile?#.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -409,9 +407,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -433,9 +431,9 @@ public class SimpleFileServerTest {
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt"))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), "");
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals("", response.body());
} finally {
server.stop(0);
}
@ -459,9 +457,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "symlink")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -486,21 +484,21 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "symlink/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
}
private void createSymLink(Path symlink, Path target) {
private static void createSymLink(Path symlink, Path target) {
try {
Files.createSymbolicLink(symlink, target);
} catch (UnsupportedOperationException uoe) {
throw new SkipException("sym link creation not supported", uoe);
Assumptions.abort("sym link creation not supported");
} catch (IOException ioe) {
throw new SkipException("probably insufficient privileges to create sym links (Windows)", ioe);
Assumptions.abort("probably insufficient privileges to create sym links (Windows)");
}
}
@ -523,9 +521,9 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, fileName)).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
@ -547,15 +545,15 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, ".hiddenDirectory/aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
}
}
private Path createHiddenFile(Path root) throws IOException {
private static Path createHiddenFile(Path root) throws IOException {
Path file;
if (Platform.isWindows()) {
file = Files.createFile(root.resolve("aFile.txt"));
@ -567,7 +565,7 @@ public class SimpleFileServerTest {
return file;
}
private Path createFileInHiddenDirectory(Path root) throws IOException {
private static Path createFileInHiddenDirectory(Path root) throws IOException {
Path dir;
Path file;
if (Platform.isWindows()) {
@ -602,17 +600,17 @@ public class SimpleFileServerTest {
var uri = uri(server, "aDirectory");
var request = HttpRequest.newBuilder(uri).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 301);
assertEquals(response.headers().firstValue("content-length").get(), "0");
assertEquals(response.headers().firstValue("location").get(), "/aDirectory/");
assertEquals(301, response.statusCode());
assertEquals("0", response.headers().firstValue("content-length").get());
assertEquals("/aDirectory/", response.headers().firstValue("location").get());
// tests that query component is preserved during redirect
var uri2 = uri(server, "aDirectory", "query");
var req2 = HttpRequest.newBuilder(uri2).build();
var res2 = client.send(req2, BodyHandlers.ofString());
assertEquals(res2.statusCode(), 301);
assertEquals(res2.headers().firstValue("content-length").get(), "0");
assertEquals(res2.headers().firstValue("location").get(), "/aDirectory/?query");
assertEquals(301, res2.statusCode());
assertEquals("0", res2.headers().firstValue("content-length").get());
assertEquals("/aDirectory/?query", res2.headers().firstValue("location").get());
}
{ // tests that redirect to returned relative URI works
@ -621,10 +619,10 @@ public class SimpleFileServerTest {
var uri = uri(server, "aDirectory");
var request = HttpRequest.newBuilder(uri).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), expectedBody);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(200, response.statusCode());
assertEquals(expectedBody, response.body());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
}
} finally {
server.stop(0);
@ -673,28 +671,26 @@ public class SimpleFileServerTest {
{ // not a directory
Path p = Files.createFile(TEST_DIR.resolve("aFile"));
assert !Files.isDirectory(p);
var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
var iae = assertThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
assertTrue(iae.getMessage().contains("not a directory"));
}
{ // does not exist
Path p = TEST_DIR.resolve("doesNotExist");
assert !Files.exists(p);
var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
var iae = assertThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
assertTrue(iae.getMessage().contains("does not exist"));
}
}
@Test
public void testNonReadablePath() throws Exception {
if (Platform.isWindows()) {
throw new SkipException("Not applicable on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "Not applicable on Windows");
var addr = LOOPBACK_ADDR;
Path p = Files.createDirectory(TEST_DIR.resolve("aDir"));
p.toFile().setReadable(false, false);
assert !Files.isReadable(p);
try {
var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
var iae = assertThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO));
assertTrue(iae.getMessage().contains("not readable"));
} finally {
p.toFile().setReadable(true, false);
@ -718,7 +714,7 @@ public class SimpleFileServerTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "beginDelim%3C%3EEndDelim")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(404, response.statusCode());
assertTrue(response.body().contains("beginDelim%3C%3EEndDelim"));
assertTrue(response.body().contains("File not found"));
} finally {
@ -726,8 +722,8 @@ public class SimpleFileServerTest {
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,7 +25,7 @@
* @test
* @summary Test to stress directory listings
* @library /test/lib
* @run testng/othervm/timeout=180 StressDirListings
* @run junit/othervm/timeout=180 StressDirListings
*/
import java.io.IOException;
@ -43,12 +43,13 @@ import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class StressDirListings {
@ -66,10 +67,10 @@ public class StressDirListings {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
HttpServer simpleFileServer;
static HttpServer simpleFileServer;
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
out.println(now() + " creating server");
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
@ -82,8 +83,8 @@ public class StressDirListings {
out.println(now() + " server started");
}
@AfterTest
public void teardown() {
@AfterAll
public static void teardown() {
out.println(now() + " stopping server");
simpleFileServer.stop(0);
out.println(now() + " server stopped");
@ -105,7 +106,7 @@ public class StressDirListings {
var request = HttpRequest.newBuilder(uri(simpleFileServer)).build();
for (int i=0; i<TIMES; i++) {
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
if (i % 100 == 0) {
out.print(" " + i + " ");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,7 +26,7 @@
* @summary Tests for SimpleFileServer with a root that is of a zip file system
* @library /test/lib
* @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
* @run testng/othervm ZipFileSystemTest
* @run junit/othervm ZipFileSystemTest
*/
import java.io.IOException;
@ -51,15 +51,17 @@ import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ZipFileSystemTest {
@ -71,8 +73,8 @@ public class ZipFileSystemTest {
static final boolean ENABLE_LOGGING = true;
static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
if (ENABLE_LOGGING) {
ConsoleHandler ch = new ConsoleHandler();
LOGGER.setLevel(Level.ALL);
@ -98,11 +100,11 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), "some text");
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(200, response.statusCode());
assertEquals("some text", response.body());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -127,11 +129,11 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -153,11 +155,11 @@ public class ZipFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, "aFile.txt"))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/plain", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -183,11 +185,11 @@ public class ZipFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, ""))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals("text/html; charset=UTF-8", response.headers().firstValue("content-type").get());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals("", response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -195,8 +197,7 @@ public class ZipFileSystemTest {
}
}
@DataProvider
public Object[][] indexFiles() {
public static Object[][] indexFiles() {
var fileContent = openHTML + """
<h1>This is an index file</h1>
""" + closeHTML;
@ -212,7 +213,8 @@ public class ZipFileSystemTest {
};
}
@Test(dataProvider = "indexFiles")
@ParameterizedTest
@MethodSource("indexFiles")
public void testDirectoryWithIndexGET(String id,
String filename,
String contentType,
@ -232,11 +234,11 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.headers().firstValue("content-type").get(), contentType);
assertEquals(response.headers().firstValue("content-length").get(), contentLength);
assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
assertEquals(response.body(), expectedBody);
assertEquals(200, response.statusCode());
assertEquals(contentType, response.headers().firstValue("content-type").get());
assertEquals(contentLength, response.headers().firstValue("content-length").get());
assertEquals(lastModified, response.headers().firstValue("last-modified").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
if (serveIndexFile) {
@ -265,9 +267,9 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "aFile?#.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -290,9 +292,9 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), expectedBody);
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals(expectedBody, response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -317,9 +319,9 @@ public class ZipFileSystemTest {
var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt"))
.method("HEAD", BodyPublishers.noBody()).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
assertEquals(response.body(), "");
assertEquals(404, response.statusCode());
assertEquals(expectedLength, response.headers().firstValue("content-length").get());
assertEquals("", response.body());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -339,9 +341,9 @@ public class ZipFileSystemTest {
var uri = uri(server, "aDirectory");
var request = HttpRequest.newBuilder(uri).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 301);
assertEquals(response.headers().firstValue("content-length").get(), "0");
assertEquals(response.headers().firstValue("location").get(), "/aDirectory/");
assertEquals(301, response.statusCode());
assertEquals("0", response.headers().firstValue("content-length").get());
assertEquals("/aDirectory/", response.headers().firstValue("location").get());
} finally {
server.stop(0);
root.getFileSystem().close();
@ -366,7 +368,7 @@ public class ZipFileSystemTest {
var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
var request = HttpRequest.newBuilder(uri(server, "beginDelim%3C%3EEndDelim")).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
assertEquals(404, response.statusCode());
assertTrue(response.body().contains("beginDelim%3C%3EEndDelim"));
assertTrue(response.body().contains("File not found"));
} finally {
@ -376,8 +378,8 @@ public class ZipFileSystemTest {
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -26,7 +26,7 @@
* @summary Negative tests for the jwebserver command-line tool
* @library /test/lib
* @modules jdk.httpserver
* @run testng/othervm CommandLineNegativeTest
* @run junit/othervm CommandLineNegativeTest
*/
import java.io.IOException;
@ -37,13 +37,14 @@ import jdk.test.lib.Platform;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static org.testng.Assert.assertFalse;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CommandLineNegativeTest {
@ -55,8 +56,8 @@ public class CommandLineNegativeTest {
static final Path TEST_FILE = TEST_DIR.resolve("file.txt");
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}
@ -64,15 +65,15 @@ public class CommandLineNegativeTest {
Files.createFile(TEST_FILE);
}
@DataProvider
public Object[][] unknownOption() {
public static Object[][] unknownOption() {
return new Object[][] {
{"--unknownOption"},
{"null"}
};
}
@Test(dataProvider = "unknownOption")
@ParameterizedTest
@MethodSource("unknownOption")
public void testBadOption(String opt) throws Throwable {
out.println("\n--- testUnknownOption, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt)
@ -80,8 +81,7 @@ public class CommandLineNegativeTest {
.shouldContain("Error: unknown option: " + opt);
}
@DataProvider
public Object[][] tooManyOptionArgs() {
public static Object[][] tooManyOptionArgs() {
return new Object[][] {
{"-b", "localhost"},
{"-d", "/some/path"},
@ -95,7 +95,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "tooManyOptionArgs")
@ParameterizedTest
@MethodSource("tooManyOptionArgs")
public void testTooManyOptionArgs(String opt, String arg) throws Throwable {
out.println("\n--- testTooManyOptionArgs, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt, arg, arg)
@ -103,8 +104,7 @@ public class CommandLineNegativeTest {
.shouldContain("Error: unknown option: " + arg);
}
@DataProvider
public Object[][] noArg() {
public static Object[][] noArg() {
return new Object[][] {
{"-b", """
-b, --bind-address - Address to bind to. Default: %s (loopback).
@ -122,7 +122,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "noArg")
@ParameterizedTest
@MethodSource("noArg")
public void testNoArg(String opt, String msg) throws Throwable {
out.println("\n--- testNoArg, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt)
@ -131,8 +132,7 @@ public class CommandLineNegativeTest {
.shouldContain(msg);
}
@DataProvider
public Object[][] invalidValue() {
public static Object[][] invalidValue() {
return new Object[][] {
{"-b", "[127.0.0.1]"},
{"-b", "badhost"},
@ -146,7 +146,8 @@ public class CommandLineNegativeTest {
};
}
@Test(dataProvider = "invalidValue")
@ParameterizedTest
@MethodSource("invalidValue")
public void testInvalidValue(String opt, String val) throws Throwable {
out.println("\n--- testInvalidValue, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt, val)
@ -154,10 +155,10 @@ public class CommandLineNegativeTest {
.shouldContain("Error: invalid value given for " + opt + ": " + val);
}
@DataProvider
public Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
public static Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testPortOutOfRange(String opt) throws Throwable {
out.println("\n--- testPortOutOfRange, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt, "65536") // range 0 to 65535
@ -165,10 +166,10 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "port out of range:65536");
}
@DataProvider
public Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
public static Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootNotADirectory(String opt) throws Throwable {
out.println("\n--- testRootNotADirectory, opt=\"%s\" ".formatted(opt));
var file = TEST_FILE.toString();
@ -178,7 +179,8 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "Path is not a directory: " + file);
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootDoesNotExist(String opt) throws Throwable {
out.println("\n--- testRootDoesNotExist, opt=\"%s\" ".formatted(opt));
Path root = TEST_DIR.resolve("not/existent/dir");
@ -188,14 +190,12 @@ public class CommandLineNegativeTest {
.shouldContain("Error: server config failed: " + "Path does not exist: " + root.toString());
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRootNotReadable(String opt) throws Throwable {
out.println("\n--- testRootNotReadable, opt=\"%s\" ".formatted(opt));
if (Platform.isWindows()) {
// Not applicable to Windows. Reason: cannot revoke an owner's read
// access to a directory that was created by that owner
throw new SkipException("cannot run on Windows");
}
Assumptions.assumeFalse(Platform.isWindows(), "cannot run on Windows"); // Not applicable to Windows. Reason: cannot revoke an owner's read
// access to a directory that was created by that owner
Path root = Files.createDirectories(TEST_DIR.resolve("not/readable/dir"));
try {
root.toFile().setReadable(false, false);
@ -208,8 +208,8 @@ public class CommandLineNegativeTest {
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -27,7 +27,7 @@
* @summary Tests the jwebserver tool with port not specified
* @modules jdk.httpserver
* @library /test/lib
* @run testng/othervm/manual CommandLinePortNotSpecifiedTest
* @run junit/othervm/manual CommandLinePortNotSpecifiedTest
*/
import java.io.IOException;
@ -39,11 +39,12 @@ import jdk.test.lib.Platform;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.lang.System.out;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class CommandLinePortNotSpecifiedTest {
static final Path JAVA_HOME = Path.of(System.getProperty("java.home"));
@ -55,8 +56,8 @@ public class CommandLinePortNotSpecifiedTest {
static final String TEST_DIR_STR = TEST_DIR.toString();
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}
@ -92,8 +93,8 @@ public class CommandLinePortNotSpecifiedTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}

View File

@ -27,7 +27,7 @@
* @library /test/lib
* @build jdk.test.lib.net.IPSupport
* @modules jdk.httpserver
* @run testng/othervm CommandLinePositiveTest
* @run junit/othervm CommandLinePositiveTest
*/
import java.io.IOException;
@ -41,12 +41,13 @@ import jdk.test.lib.net.IPSupport;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CommandLinePositiveTest {
static final String JAVA_VERSION = System.getProperty("java.version");
@ -84,8 +85,8 @@ public class CommandLinePositiveTest {
static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(ROOT_DIR)) {
FileUtils.deleteFileTreeWithRetry(ROOT_DIR);
}
@ -105,16 +106,17 @@ public class CommandLinePositiveTest {
}
}
@DataProvider
public Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
public static Object[][] directoryOptions() { return new Object[][] {{"-d"}, {"--directory"}}; }
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testAbsDirectory(String opt) throws Throwable {
out.printf("\n--- testAbsDirectory, opt=\"%s\"%n", opt);
testDirectory(opt, ROOT_DIR_STR);
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testRelDirectory(String opt) throws Throwable {
out.printf("\n--- testRelDirectory, opt=\"%s\"%n", opt);
Path rootRelDir = CWD.relativize(ROOT_DIR);
@ -129,10 +131,10 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
public static Object[][] portOptions() { return new Object[][] {{"-p"}, {"--port"}}; }
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testPort(String opt) throws Throwable {
out.println("\n--- testPort, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt, "0")
@ -142,8 +144,7 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] helpOptions() { return new Object[][] {{"-h"}, {"-?"}, {"--help"}}; }
public static Object[][] helpOptions() { return new Object[][] {{"-h"}, {"-?"}, {"--help"}}; }
static final String USAGE_TEXT = """
Usage: jwebserver [-b bind address] [-p port] [-d directory]
@ -161,7 +162,8 @@ public class CommandLinePositiveTest {
-version, --version - Prints version information and exits.
To stop the server, press Ctrl + C.""".formatted(LOOPBACK_ADDR);
@Test(dataProvider = "helpOptions")
@ParameterizedTest
@MethodSource("helpOptions")
public void testHelp(String opt) throws Throwable {
out.println("\n--- testHelp, opt=\"%s\" ".formatted(opt));
simpleserver(WaitForLine.HELP_STARTUP_LINE,
@ -172,10 +174,10 @@ public class CommandLinePositiveTest {
.shouldContain(OPTIONS_TEXT);
}
@DataProvider
public Object[][] versionOptions() { return new Object[][] {{"-version"}, {"--version"}}; }
public static Object[][] versionOptions() { return new Object[][] {{"-version"}, {"--version"}}; }
@Test(dataProvider = "versionOptions")
@ParameterizedTest
@MethodSource("versionOptions")
public void testVersion(String opt) throws Throwable {
out.println("\n--- testVersion, opt=\"%s\" ".formatted(opt));
simpleserver(WaitForLine.VERSION_STARTUP_LINE,
@ -184,10 +186,10 @@ public class CommandLinePositiveTest {
.shouldHaveExitValue(0);
}
@DataProvider
public Object[][] bindOptions() { return new Object[][] {{"-b"}, {"--bind-address"}}; }
public static Object[][] bindOptions() { return new Object[][] {{"-b"}, {"--bind-address"}}; }
@Test(dataProvider = "bindOptions")
@ParameterizedTest
@MethodSource("bindOptions")
public void testBindAllInterfaces(String opt) throws Throwable {
out.println("\n--- testBindAllInterfaces, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, "-p", "0", opt, "0.0.0.0")
@ -202,7 +204,8 @@ public class CommandLinePositiveTest {
}
}
@Test(dataProvider = "bindOptions")
@ParameterizedTest
@MethodSource("bindOptions")
public void testLastOneWinsBindAddress(String opt) throws Throwable {
out.println("\n--- testLastOneWinsBindAddress, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, "-p", "0", opt, "123.4.5.6", opt, LOOPBACK_ADDR)
@ -212,7 +215,8 @@ public class CommandLinePositiveTest {
}
@Test(dataProvider = "directoryOptions")
@ParameterizedTest
@MethodSource("directoryOptions")
public void testLastOneWinsDirectory(String opt) throws Throwable {
out.println("\n--- testLastOneWinsDirectory, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, "-p", "0", opt, CWD_STR, opt, CWD_STR)
@ -222,10 +226,10 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@DataProvider
public Object[][] outputOptions() { return new Object[][] {{"-o"}, {"--output"}}; }
public static Object[][] outputOptions() { return new Object[][] {{"-o"}, {"--output"}}; }
@Test(dataProvider = "outputOptions")
@ParameterizedTest
@MethodSource("outputOptions")
public void testLastOneWinsOutput(String opt) throws Throwable {
out.println("\n--- testLastOneWinsOutput, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, "-p", "0", opt, "none", opt, "verbose")
@ -235,7 +239,8 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@Test(dataProvider = "portOptions")
@ParameterizedTest
@MethodSource("portOptions")
public void testLastOneWinsPort(String opt) throws Throwable {
out.println("\n--- testLastOneWinsPort, opt=\"%s\" ".formatted(opt));
simpleserver(JWEBSERVER, LOCALE_OPT, opt, "-999", opt, "0")
@ -245,8 +250,8 @@ public class CommandLinePositiveTest {
.shouldContain("URL http://" + LOOPBACK_ADDR);
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(ROOT_DIR)) {
FileUtils.deleteFileTreeWithRetry(ROOT_DIR);
}

View File

@ -27,7 +27,7 @@
* @summary Tests the jwebserver's maximum request time
* @modules jdk.httpserver
* @library /test/lib
* @run testng/othervm MaxRequestTimeTest
* @run junit/othervm MaxRequestTimeTest
*/
import java.io.IOException;
@ -47,12 +47,13 @@ import jdk.test.lib.net.SimpleSSLContext;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.FileUtils;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* This test confirms that the jwebserver does not wait indefinitely for
@ -80,8 +81,8 @@ public class MaxRequestTimeTest {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}
@ -118,17 +119,17 @@ public class MaxRequestTimeTest {
</html>
""";
void sendHTTPRequest() throws IOException, InterruptedException {
static void sendHTTPRequest() throws IOException, InterruptedException {
out.println("\n--- sendHTTPRequest");
var client = HttpClient.newBuilder()
.proxy(NO_PROXY)
.build();
var request = HttpRequest.newBuilder(URI.create("http://localhost:" + PORT.get() + "/")).build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.body(), expectedBody);
assertEquals(expectedBody, response.body());
}
void sendHTTPSRequest() throws IOException, InterruptedException {
static void sendHTTPSRequest() throws IOException, InterruptedException {
out.println("\n--- sendHTTPSRequest");
var client = HttpClient.newBuilder()
.sslContext(sslContext)
@ -143,8 +144,8 @@ public class MaxRequestTimeTest {
}
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
if (Files.exists(TEST_DIR)) {
FileUtils.deleteFileTreeWithRetry(TEST_DIR);
}