summaryrefslogtreecommitdiffstats
path: root/jdisc_http_service/src/test/java/com/yahoo/jdisc/http/AssertHttp.java
blob: b60c269ac985216b80d8dcb78ab4bfc895bf5a6d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http;

import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.http.test.RemoteClient;
import com.yahoo.jdisc.http.test.ServerTestDriver;

import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;

/**
 * @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen Hult</a>
 */
public abstract class AssertHttp {

    public static void assertChunk(String expected, String actual) {
        if (expected.startsWith("HTTP/1.")) {
            expected = sortChunk(expected);
            actual = sortChunk(actual);
        }
        Pattern pattern = Pattern.compile(expected, Pattern.DOTALL | Pattern.MULTILINE);
        if (pattern.matcher(actual).matches()) {
            return;
        }
        assertEquals(expected, actual);
    }

    public static void assertResponse(RequestHandler requestHandler, String request,
                                      String... expectedChunks) throws IOException {
        ServerTestDriver driver = ServerTestDriver.newInstance(requestHandler);
        assertResponse(driver, request, expectedChunks);
        assertTrue(driver.close());
    }

    public static void assertResponse(ServerTestDriver driver, String request, String... expectedChunks)
            throws IOException {
        assertResponse(driver.client(), request, expectedChunks);
    }

    public static void assertResponse(RemoteClient client, String request, String... expectedChunks)
            throws IOException {
        client.writeRequest(request);
        for (String expected : expectedChunks) {
            assertChunk(expected, client.readChunk());
        }
    }

    private static String sortChunk(String chunk) {
        String[] lines = chunk.split("\r\n");
        if (lines.length > 2) {
            int prev = 1, next = 2;
            for ( ; next < lines.length && !lines[next].isEmpty(); ++next) {
                if (!Character.isLetterOrDigit(lines[next].charAt(0))) {
                    Arrays.sort(lines, prev, next);
                    prev = next + 1;
                }
            }
            if (prev < next) {
                Arrays.sort(lines, prev, next);
            }
        }
        StringBuilder out = new StringBuilder();
        for (String line : lines) {
            out.append(line).append("\r\n");
        }
        return out.toString();
    }
}