http-client-branch: clean up and expand push promise tests http-client-branch
authorchegar
Tue, 23 Jan 2018 13:54:34 +0000
branchhttp-client-branch
changeset 56037 c026ce4a1a81
parent 56036 89a688549f5d
child 56038 e663f24e3020
http-client-branch: clean up and expand push promise tests
test/jdk/java/net/httpclient/http2/ServerPush.java
test/jdk/java/net/httpclient/http2/ServerPushWithDiffTypes.java
test/jdk/java/net/httpclient/http2/server/PushHandler.java
--- a/test/jdk/java/net/httpclient/http2/ServerPush.java	Tue Jan 23 13:21:59 2018 +0000
+++ b/test/jdk/java/net/httpclient/http2/ServerPush.java	Tue Jan 23 13:54:34 2018 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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,16 +39,19 @@
 import java.nio.file.*;
 import jdk.incubator.http.*;
 import jdk.incubator.http.HttpResponse.BodyHandler;
+import jdk.incubator.http.HttpResponse.BodySubscriber;
 import jdk.incubator.http.HttpResponse.PushPromiseHandler;
 import java.util.*;
 import java.util.concurrent.*;
 import java.util.function.Consumer;
 import java.util.function.UnaryOperator;
-
 import org.testng.annotations.AfterTest;
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.Test;
 import static java.nio.charset.StandardCharsets.UTF_8;
+import static jdk.incubator.http.HttpResponse.BodyHandler.asByteArrayConsumer;
+import static jdk.incubator.http.HttpResponse.BodyHandler.asFile;
+import static jdk.incubator.http.HttpResponse.BodyHandler.asString;
 import static org.testng.Assert.*;
 
 
@@ -64,9 +67,9 @@
 
     @BeforeTest
     public void setup() throws Exception {
+        tempFile = TestUtil.getAFile(FILE_SIZE);
         server = new Http2TestServer(false, 0);
-        server.addHandler(new PushHandler(FILE_SIZE, LOOPS), "/");
-        tempFile = TestUtil.getAFile(FILE_SIZE);
+        server.addHandler(new PushHandler(tempFile, LOOPS), "/");
         System.out.println("Using temp file:" + tempFile);
 
         System.err.println("Server listening on port " + server.getAddress().getPort());
@@ -80,61 +83,58 @@
         server.stop();
     }
 
-    static final UnaryOperator<HttpResponse<?>>
-            assert200ResponseCode = (response) -> {
-                assertEquals(response.statusCode(), 200);
-                return response;
-    };
-
-    interface Peeker<T> extends UnaryOperator<T> {
-        void peek(T t);
-
-        default T apply(T t)
-        {
-            peek(t);
-            return t;
-        }
-    }
-
+    // Test 1 - custom written push promise handler, everything as a String
     @Test
     public void testTypeString() throws Exception {
-        // use multi-level path
-        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
-
         String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<String>>>
+                resultMap = new ConcurrentHashMap<>();
 
-        // Attempt 2
-        HttpClient client = HttpClient.newBuilder()
-                .version(HttpClient.Version.HTTP_2)
-                .build();
-
-        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<String>>> results = new ConcurrentHashMap<>();
-
-
-        // Example 2 - of(...) building your own Map, everything as a String
         PushPromiseHandler<String> pph = (initial, pushRequest, acceptor) -> {
             BodyHandler<String> s = BodyHandler.asString(UTF_8);
             CompletableFuture<HttpResponse<String>> cf = acceptor.apply(s);
-            results.put(pushRequest, cf);
+            resultMap.put(pushRequest, cf);
         };
 
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
         CompletableFuture<HttpResponse<String>> cf =
-                client.sendAsync(request, BodyHandler.asString(), pph);
+                client.sendAsync(request, asString(UTF_8), pph);
         cf.join();
-        results.put(request, cf);
-
-        System.err.println(results.size());
-        Set<HttpRequest> requests = results.keySet();
+        resultMap.put(request, cf);
+        System.err.println("results.size: " + resultMap.size());
+        for (HttpRequest r : resultMap.keySet()) {
+            HttpResponse<String> response = resultMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
+            assertEquals(response.body(), tempFileAsString);
+        }
+        assertEquals(resultMap.size(), LOOPS + 1);
+    }
 
-        System.err.println("results.size: " + results.size());
-        for (HttpRequest r : requests) {
-            String result = results.get(r).get().body();
-            if (!result.equals(tempFileAsString)) {
-                System.err.println("Got [" + result + ", expected [" + tempFileAsString + "]");
-            }
+    // Test 2 - of(...) populating the given Map, everything as a String
+    @Test
+    public void testTypeStringOfMap() throws Exception {
+        String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<String>>>
+                resultMap = new ConcurrentHashMap<>();
+
+        PushPromiseHandler<String> pph =
+                PushPromiseHandler.of(pushPromise -> asString(UTF_8),
+                                      resultMap);
+
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
+        CompletableFuture<HttpResponse<String>> cf =
+                client.sendAsync(request, asString(UTF_8), pph);
+        cf.join();
+        resultMap.put(request, cf);
+        System.err.println("results.size: " + resultMap.size());
+        for (HttpRequest r : resultMap.keySet()) {
+            HttpResponse<String> response = resultMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
+            assertEquals(response.body(), tempFileAsString);
         }
-        if (requests.size() != LOOPS + 1)
-            throw new RuntimeException("Some results missing, expected:" + LOOPS + 1 + ", got:" + results.size());
+        assertEquals(resultMap.size(), LOOPS + 1);
     }
 
     // --- Path ---
@@ -148,37 +148,63 @@
         } catch (IOException ee) {
             throw new UncheckedIOException(ee);
         }
-        return BodyHandler.asFile(path);
-    };
+        return asFile(path);
+    }
 
+    // Test 3 - custom written push promise handler, everything as a Path
     @Test
     public void testTypePath() throws Exception {
-        HttpClient client = HttpClient.newHttpClient();
-        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
-
-        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Path>>> map
+        String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Path>>> resultsMap
                 = new ConcurrentHashMap<>();
 
-        // Example 4 - of(...) building your own Map, everything as a Path
         PushPromiseHandler<Path> pushPromiseHandler = (initial, pushRequest, acceptor) -> {
             BodyHandler<Path> pp = requestToPath(pushRequest);
             CompletableFuture<HttpResponse<Path>> cf = acceptor.apply(pp);
-            map.put(pushRequest, cf);
+            resultsMap.put(pushRequest, cf);
         };
 
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
         CompletableFuture<HttpResponse<Path>> cf =
                 client.sendAsync(request, requestToPath(request), pushPromiseHandler);
         cf.join();
-        map.put(request, cf);
+        resultsMap.put(request, cf);
 
-        System.err.println("map.size: " + map.size());
-        for (HttpRequest r : map.keySet()) {
-            Path path = map.get(r).get().body();
-            String fileAsString = new String(Files.readAllBytes(path), UTF_8);
-            String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        for (HttpRequest r : resultsMap.keySet()) {
+            HttpResponse<Path> response = resultsMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
+            String fileAsString = new String(Files.readAllBytes(response.body()), UTF_8);
             assertEquals(fileAsString, tempFileAsString);
         }
-        assertEquals(map.size(),  LOOPS + 1);
+        assertEquals(resultsMap.size(),  LOOPS + 1);
+    }
+
+    // Test 4 - of(...) populating the given Map, everything as a Path
+    @Test
+    public void testTypePathOfMap() throws Exception {
+        String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Path>>> resultsMap
+                = new ConcurrentHashMap<>();
+
+        PushPromiseHandler<Path> pushPromiseHandler =
+                PushPromiseHandler.of(pushRequest -> requestToPath(pushRequest),
+                        resultsMap);
+
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
+        CompletableFuture<HttpResponse<Path>> cf =
+                client.sendAsync(request, requestToPath(request), pushPromiseHandler);
+        cf.join();
+        resultsMap.put(request, cf);
+
+        for (HttpRequest r : resultsMap.keySet()) {
+            HttpResponse<Path> response = resultsMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
+            String fileAsString = new String(Files.readAllBytes(response.body()), UTF_8);
+            assertEquals(fileAsString, tempFileAsString);
+        }
+        assertEquals(resultsMap.size(),  LOOPS + 1);
     }
 
     // ---  Consumer<byte[]> ---
@@ -203,47 +229,79 @@
         }
     }
 
+    // Test 5 - custom written handler, everything as a consumer of optional byte[]
     @Test
     public void testTypeByteArrayConsumer() throws Exception {
-        HttpClient client = HttpClient.newHttpClient();
-        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
-
-        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Void>>> resultMap
+        String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Void>>> resultsMap
                 = new ConcurrentHashMap<>();
         Map<HttpRequest,ByteArrayConsumer> byteArrayConsumerMap
                 = new ConcurrentHashMap<>();
 
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
         ByteArrayConsumer bac = new ByteArrayConsumer();
         byteArrayConsumerMap.put(request, bac);
 
-        // Example 5 - withXXX and everything as a consumer of optional byte[]
-        PushPromiseHandler<Void> pushPromiseHandler =
-                PushPromiseHandler.of(pushRequest -> {
-                                                       ByteArrayConsumer bc = new ByteArrayConsumer();
-                                                       byteArrayConsumerMap.put(pushRequest, bc);
-                                                       return BodyHandler.asByteArrayConsumer(bc);
-                                                    },
-                                                    resultMap);
+        PushPromiseHandler<Void> pushPromiseHandler = (initial, pushRequest, acceptor) -> {
+            CompletableFuture<HttpResponse<Void>> cf = acceptor.apply(
+                    (statusCode, headers) -> {
+                        ByteArrayConsumer bc = new ByteArrayConsumer();
+                        byteArrayConsumerMap.put(pushRequest, bc);
+                        return BodySubscriber.asByteArrayConsumer(bc); } );
+            resultsMap.put(pushRequest, cf);
+        };
 
         CompletableFuture<HttpResponse<Void>> cf =
-                client.sendAsync(request, BodyHandler.asByteArrayConsumer(bac), pushPromiseHandler);
+                client.sendAsync(request, asByteArrayConsumer(bac), pushPromiseHandler);
         cf.join();
-        resultMap.put(request, cf);
+        resultsMap.put(request, cf);
 
-        System.err.println("map.size: " + resultMap.size());
-        for (HttpRequest r : resultMap.keySet()) {
-            resultMap.get(r).join();
+        for (HttpRequest r : resultsMap.keySet()) {
+            HttpResponse<Void> response = resultsMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
             byte[] ba = byteArrayConsumerMap.get(r).getAccumulatedBytes();
             String result = new String(ba, UTF_8);
-            System.out.println("HEGO result=" + result);
-            System.out.println("HEGO result.length=" + result.length());
-            System.err.printf("%s -> %s\n", r.uri().toString(), result);
-            String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
-            System.out.println("HEGO tempFileAsString=" + tempFileAsString);
-            System.out.println("HEGO tempFileAsString.length=" + tempFileAsString.length());
             assertEquals(result, tempFileAsString);
         }
+        assertEquals(resultsMap.size(), LOOPS + 1);
+    }
 
-        assertEquals(resultMap.size(), LOOPS + 1);
+    // Test 6 - of(...) populating the given Map, everything as a consumer of optional byte[]
+    @Test
+    public void testTypeByteArrayConsumerOfMap() throws Exception {
+        String tempFileAsString = new String(Files.readAllBytes(tempFile), UTF_8);
+        ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<Void>>> resultsMap
+                = new ConcurrentHashMap<>();
+        Map<HttpRequest,ByteArrayConsumer> byteArrayConsumerMap
+                = new ConcurrentHashMap<>();
+
+        HttpClient client = HttpClient.newHttpClient();
+        HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
+        ByteArrayConsumer bac = new ByteArrayConsumer();
+        byteArrayConsumerMap.put(request, bac);
+
+        PushPromiseHandler<Void> pushPromiseHandler =
+                PushPromiseHandler.of(
+                        pushRequest -> {
+                            ByteArrayConsumer bc = new ByteArrayConsumer();
+                            byteArrayConsumerMap.put(pushRequest, bc);
+                            return BodyHandler.asByteArrayConsumer(bc);
+                        },
+                        resultsMap);
+
+        CompletableFuture<HttpResponse<Void>> cf =
+                client.sendAsync(request, asByteArrayConsumer(bac), pushPromiseHandler);
+        cf.join();
+        resultsMap.put(request, cf);
+
+        for (HttpRequest r : resultsMap.keySet()) {
+            HttpResponse<Void> response = resultsMap.get(r).join();
+            assertEquals(response.statusCode(), 200);
+            byte[] ba = byteArrayConsumerMap.get(r).getAccumulatedBytes();
+            String result = new String(ba, UTF_8);
+            assertEquals(result, tempFileAsString);
+        }
+        assertEquals(resultsMap.size(), LOOPS + 1);
     }
 }
--- a/test/jdk/java/net/httpclient/http2/ServerPushWithDiffTypes.java	Tue Jan 23 13:21:59 2018 +0000
+++ b/test/jdk/java/net/httpclient/http2/ServerPushWithDiffTypes.java	Tue Jan 23 13:54:34 2018 +0000
@@ -35,7 +35,6 @@
 import java.io.*;
 import java.net.*;
 import java.nio.ByteBuffer;
-import java.nio.charset.StandardCharsets;
 import java.nio.file.*;
 import jdk.incubator.http.*;
 import jdk.incubator.http.HttpResponse.BodyHandler;
@@ -46,19 +45,20 @@
 import jdk.incubator.http.internal.common.HttpHeadersImpl;
 import org.testng.annotations.Test;
 import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.testng.Assert.assertEquals;
 
 public class ServerPushWithDiffTypes {
 
     static Map<String,String> PUSH_PROMISES = Map.of(
-        "/x/y/z/1", "the first push promise body",
-        "/x/y/z/2", "the second push promise body",
-        "/x/y/z/3", "the third push promise body",
-        "/x/y/z/4", "the fourth push promise body",
-        "/x/y/z/5", "the fifth push promise body",
-        "/x/y/z/6", "the sixth push promise body",
-        "/x/y/z/7", "the seventh push promise body",
-        "/x/y/z/8", "the eight push promise body",
-        "/x/y/z/9", "the ninth push promise body"
+            "/x/y/z/1", "the first push promise body",
+            "/x/y/z/2", "the second push promise body",
+            "/x/y/z/3", "the third push promise body",
+            "/x/y/z/4", "the fourth push promise body",
+            "/x/y/z/5", "the fifth push promise body",
+            "/x/y/z/6", "the sixth push promise body",
+            "/x/y/z/7", "the seventh push promise body",
+            "/x/y/z/8", "the eight push promise body",
+            "/x/y/z/9", "the ninth push promise body"
     );
 
     @Test
@@ -66,8 +66,9 @@
         Http2TestServer server = null;
         try {
             server = new Http2TestServer(false, 0);
-            Http2Handler handler = new ServerPushHandler("the main response body",
-                                                         PUSH_PROMISES);
+            Http2Handler handler =
+                    new ServerPushHandler("the main response body",
+                                          PUSH_PROMISES);
             server.addHandler(handler, "/");
             server.start();
             int port = server.getAddress().getPort();
@@ -78,18 +79,17 @@
             URI uri = new URI("http://127.0.0.1:" + port + "/foo/a/b/c");
             HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
 
-            ConcurrentMap<HttpRequest,CompletableFuture<HttpResponse<BodyAndType<?>>>> results = new ConcurrentHashMap<>();
+            ConcurrentMap<HttpRequest,CompletableFuture<HttpResponse<BodyAndType<?>>>>
+                    results = new ConcurrentHashMap<>();
             PushPromiseHandler<BodyAndType<?>> bh = PushPromiseHandler.of(
-                (pushRequest) -> new BodyAndTypeHandler(pushRequest), results);
+                    (pushRequest) -> new BodyAndTypeHandler(pushRequest), results);
 
-            CompletableFuture<HttpResponse<BodyAndType<?>>> cf = client.sendAsync(request, new BodyAndTypeHandler(request), bh);
+            CompletableFuture<HttpResponse<BodyAndType<?>>> cf =
+                    client.sendAsync(request, new BodyAndTypeHandler(request), bh);
             results.put(request, cf);
             cf.join();
-            System.err.println("CHEGAR: results.size: " + results.size());
 
-            if (results.size() != PUSH_PROMISES.size() + 1)
-                throw new RuntimeException("Some results missing, expected:"
-                        + (PUSH_PROMISES.size() + 1) + ", got:" + results.size());
+            assertEquals(results.size(), PUSH_PROMISES.size() + 1);
 
             for (HttpRequest r : results.keySet()) {
                 URI u = r.uri();
@@ -112,17 +112,14 @@
                 String expected = PUSH_PROMISES.get(r.uri().getPath());
                 if (expected == null)
                     expected = "the main response body";
-                System.err.println("For " + r + ", got [" + result + "], expected [" + expected +"]");
-                if (!result.equals(expected)) {
-                    throw new RuntimeException("For " + r + ", got [" + result + "], expected [" + expected +"]");
-                }
+                assertEquals(result, expected);
             }
         } finally {
             server.stop();
         }
     }
 
-    static interface BodyAndType<T> {
+    interface BodyAndType<T> {
         Class<T> type();
         T getBody();
     }
@@ -143,7 +140,7 @@
             int whichType = count++ % 3;  // real world may base this on the request metadata
             switch (whichType) {
                 case 0: // String
-                    return new BodyAndTypeSubscriber(BodySubscriber.asString(StandardCharsets.UTF_8));
+                    return new BodyAndTypeSubscriber(BodySubscriber.asString(UTF_8));
                 case 1: // byte[]
                     return new BodyAndTypeSubscriber(BodySubscriber.asByteArray());
                 case 2: // Path
@@ -161,8 +158,9 @@
         }
     }
 
-    static class BodyAndTypeSubscriber<T> implements HttpResponse.BodySubscriber<BodyAndType<T>> {
-
+    static class BodyAndTypeSubscriber<T>
+        implements HttpResponse.BodySubscriber<BodyAndType<T>>
+    {
         private static class BodyAndTypeImpl<T> implements BodyAndType<T> {
             private final Class<T> type;
             private final T body;
@@ -177,7 +175,8 @@
         BodyAndTypeSubscriber(BodySubscriber bodySubscriber) {
             this.bodySubscriber = bodySubscriber;
             cf = new CompletableFuture<>();
-            bodySubscriber.getBody().whenComplete((r,t) -> cf.complete(new BodyAndTypeImpl(r.getClass(), r)));
+            bodySubscriber.getBody().whenComplete(
+                    (r,t) -> cf.complete(new BodyAndTypeImpl(r.getClass(), r)));
         }
 
         @Override
@@ -213,7 +212,10 @@
         private final String mainResponseBody;
         private final Map<String,String> promises;
 
-        public ServerPushHandler(String mainResponseBody, Map<String,String> promises) throws Exception {
+        public ServerPushHandler(String mainResponseBody,
+                                 Map<String,String> promises)
+            throws Exception
+        {
             Objects.requireNonNull(promises);
             this.mainResponseBody = mainResponseBody;
             this.promises = promises;
@@ -243,7 +245,8 @@
                 URI uri = requestURI.resolve(promise.getKey());
                 InputStream is = new ByteArrayInputStream(promise.getValue().getBytes(UTF_8));
                 HttpHeadersImpl headers = new HttpHeadersImpl();
-                headers.addHeader("X-Promise-"+promise.getKey(), promise.getKey()); // todo: add some check on headers, maybe
+                // TODO: add some check on headers, maybe
+                headers.addHeader("X-Promise-"+promise.getKey(), promise.getKey());
                 exchange.serverPush(uri, headers, is);
             }
             System.err.println("Server: All pushes sent");
--- a/test/jdk/java/net/httpclient/http2/server/PushHandler.java	Tue Jan 23 13:21:59 2018 +0000
+++ b/test/jdk/java/net/httpclient/http2/server/PushHandler.java	Tue Jan 23 13:54:34 2018 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -30,12 +30,12 @@
 
     final Path tempFile;
     final int loops;
-    final int file_size;
+    final long file_size;
 
-    public PushHandler(int file_size, int loops) throws Exception {
-        tempFile = TestUtil.getAFile(file_size);
+    public PushHandler(Path file, int loops) throws Exception {
+        tempFile = file;
         this.loops = loops;
-        this.file_size = file_size;
+        this.file_size = Files.size(file);
     }
 
     int invocation = 0;