org.takes.rs.RsPrint Java Examples

The following examples show how to use org.takes.rs.RsPrint. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TkAuthTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkAuth can logout a user when a login cookie is present.
 * @throws Exception If some problem inside
 */
@Test
public void logsUserOutWithCookiePresent() throws Exception {
    new Assertion<>(
        "Response with header setting empty cookie",
        new RsPrint(
            new TkAuth(
                new TkText(),
                new PsChain(
                    new PsLogout(),
                    new PsCookie(new CcPlain())
                )
            ).act(
                new RqWithHeader(
                    new RqFake(),
                    String.format(
                        "Cookie: %s=%s",
                        PsCookie.class.getSimpleName(),
                        "urn%3Atest%3A5"
                    )
                )
            )
        ),
        new TextHasString("Set-Cookie: PsCookie=")
    ).affirm();
}
 
Example #2
Source File: RsForkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsFork can route by the Accept header.
 * @throws IOException If some problem inside
 */
@Test
public void negotiatesContentWithComplexHeader() throws IOException {
    final Request req = new RqFake(
        Arrays.asList(
            "GET /hell-1o.html",
            "Accept: text/xml"
        ),
        ""
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new RsFork(
                req,
                new FkTypes(
                    "application/xml,text/xml",
                    new RsText("how are you?")
                )
            )
        ).printBody(),
        Matchers.endsWith("you?")
    );
}
 
Example #3
Source File: TkAppTest.java    From jare with MIT License 6 votes vote down vote up
/**
 * App can render front page.
 * @throws Exception If some problem inside
 */
@Test
public void rendersHomePage() throws Exception {
    final Take take = new TkApp(new FkBase());
    MatcherAssert.assertThat(
        XhtmlMatchers.xhtml(
            new RsPrint(
                take.act(
                    new RqWithHeader(
                        new RqFake("GET", "/"),
                        // @checkstyle MultipleStringLiteralsCheck (1 line)
                        "Accept",
                        "text/xml"
                    )
                )
            ).printBody()
        ),
        XhtmlMatchers.hasXPaths(
            "/page/@date",
            "/page/@sla",
            "/page/millis",
            "/page/links/link[@rel='takes:logout']"
        )
    );
}
 
Example #4
Source File: TkHtmlTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkHTML can create a text.
 * @throws Exception If some problem inside
 */
@Test
public void createsTextResponse() throws Exception {
    final String body = "<html>hello, world!</html>";
    MatcherAssert.assertThat(
        new RsPrint(new TkHtml(body).act(new RqFake())),
        new TextIs(
            new Joined(
                "\r\n",
                "HTTP/1.1 200 OK",
                String.format("Content-Length: %s", body.length()),
                "Content-Type: text/html",
                "",
                body
            )
        )
    );
}
 
Example #5
Source File: TkTextTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkText can create a text.
 * @throws Exception If some problem inside
 */
@Test
public void createsTextResponse() throws Exception {
    final String body = "hello, world!";
    MatcherAssert.assertThat(
        new RsPrint(new TkText(body).act(new RqFake())),
        new TextIs(
            new Joined(
                "\r\n",
                "HTTP/1.1 200 OK",
                String.format("Content-Length: %s", body.length()),
                "Content-Type: text/plain",
                "",
                body
            )
        )
    );
}
 
Example #6
Source File: TkMistakesTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
public void rendersMistakesPageInXml() throws IOException {
    new Assertion<>(
        "Must render mistake page in xml",
        XhtmlMatchers.xhtml(
            new RsPrint(
                new TkMistakes().act(
                    new RqWithHeaders(
                        new RqFake(),
                        "Accept: application/vnd.jpeek+xml"
                    )
                )
            ).printBody()
        ),
        XhtmlMatchers.hasXPath("/page/worst")
    ).affirm();
}
 
Example #7
Source File: TkIndexTest.java    From jare with MIT License 6 votes vote down vote up
/**
 * TkIndex can render home page in HTML.
 * @throws Exception If some problem inside
 */
@Test
public void rendersHomePageInHtml() throws Exception {
    final Take take = new TkAppAuth(new TkIndex(new FkBase()));
    MatcherAssert.assertThat(
        XhtmlMatchers.xhtml(
            new RsPrint(
                take.act(new RqFake("GET", "/"))
            ).printBody()
        ),
        XhtmlMatchers.hasXPaths(
            "/xhtml:html",
            "/xhtml:html/xhtml:body"
        )
    );
}
 
Example #8
Source File: TkCorsTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkCors can't handle connections with wrong domain on origin.
 * @throws Exception If some problem inside
 */
@Test
public void cantHandleConnectionsWithWrongDomainOnOrigin()
    throws Exception {
    MatcherAssert.assertThat(
        "Wrong value on header.",
        new RsPrint(
            new TkCors(
                new TkFixed(new RsText()),
                "http://www.teamed.io",
                "http://sample.com"
            ).act(
                new RqWithHeaders(
                    new RqFake(),
                    "Origin: http://wrong.teamed.io"
                )
            )
        ).printHead(),
        Matchers.allOf(
            Matchers.containsString("HTTP/1.1 403"),
            Matchers.containsString(
                "Access-Control-Allow-Credentials: false"
            )
        )
    );
}
 
Example #9
Source File: TkWithHeadersTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkWithHeaders can add headers.
 * @throws java.lang.Exception If some problem inside
 */
@Test
public void addHeaders() throws Exception {
    final String host = "Host: www.example.com";
    final String type = "Content-Type: text/xml";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkWithHeaders(
                new TkEmpty(),
                host,
                type
            ).act(new RqFake())
        ),
        new TextIs(
            new Joined(
                "\r\n",
                "HTTP/1.1 204 No Content",
                host,
                type,
                "",
                ""
            )
        )
    );
}
 
Example #10
Source File: TkReportTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
public void rendersEmptySvgBadge(@TempDir final File folder)
    throws IOException {
    new Assertion<>(
        "Must render the badge",
        XhtmlMatchers.xhtml(
            new RsPrint(
                new TkReport(
                    new AsyncReports(
                        new Futures(
                            new Reports(folder.toPath())
                        )
                    ),
                    new Results()
                ).act(
                    new RqRegex.Fake(
                        new RqFake(),
                        "/([^/]+)/([^/]+)/([^/]+)",
                        "/org.jpeek/jpeek/badge.svg"
                    )
                )
            ).printBody()
        ),
        XhtmlMatchers.hasXPath("//svg:svg")
    ).affirm();
}
 
Example #11
Source File: TkFilesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkFiles can dispatch by file name.
 * @throws Exception If some problem inside
 */
@Test
public void dispatchesByFileName() throws Exception {
    FileUtils.write(
        this.temp.newFile("a.txt"), "hello, world!", StandardCharsets.UTF_8
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new TkFiles(this.temp.getRoot()).act(
                new RqFake(
                    "GET", "/a.txt?hash=a1b2c3", ""
                )
            )
        ),
        new StartsWith("HTTP/1.1 200 OK")
    );
}
 
Example #12
Source File: TkGzipTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkGzip can compress on demand only.
 * @throws Exception If some problem inside
 */
@Test
public void compressesOnDemandOnly() throws Exception {
    MatcherAssert.assertThat(
        new RsPrint(
            new TkGzip(new TkClasspath()).act(
                new RqFake(
                    Arrays.asList(
                        "GET /org/takes/tk/TkGzip.class HTTP/1.1",
                        "Host: www.example.com",
                        "Accept-Encoding: gzip"
                    ),
                    ""
                )
            )
        ),
        new StartsWith("HTTP/1.1 200 OK")
    );
}
 
Example #13
Source File: PsBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsBasic can authenticate a user.
 * @throws Exception If some problem inside
 */
@Test
public void authenticatesUser() throws Exception {
    final Take take = new TkAuth(
        new TkSecure(
            new TkText("secured")
        ),
        new PsBasic(
            "myrealm",
            new PsBasic.Default("mike secret11 urn:users:michael")
        )
    );
    new Assertion<>(
        "PsBasic should authenticate mike",
        new RsPrint(
            take.act(
                new RqWithHeader(
                    new RqFake(),
                    PsBasicTest.header("mike", "secret11")
                )
            )
        ),
        new TextHasString("HTTP/1.1 200 OK")
    ).affirm();
}
 
Example #14
Source File: PsBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsBasic can request authentication.
 * @throws Exception If some problem inside
 */
@Test
public void requestAuthentication() throws Exception {
    final Take take = new TkForward(
        new TkAuth(
            new TkSecure(
                new TkText("secured area...")
            ),
            new PsBasic(
                "the realm 5",
                new PsBasic.Default("bob pwd88 urn:users:bob")
            )
        )
    );
    new Assertion<>(
        "Response with 401 Unauthorized status",
        new RsPrint(
            take.act(new RqFake())
        ),
        new TextHasString("HTTP/1.1 401 Unauthorized\r\n")
    ).affirm();
}
 
Example #15
Source File: TkRedirectTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkRedirect can create a response with HTTP status code and url string.
 * @throws Exception If some problem inside
 */
@Test
public void createsRedirectResponseWithUrlAndStatus() throws Exception {
    final String url = "/";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkRedirect(url, HttpURLConnection.HTTP_MOVED_TEMP).act(
                new RqFake()
            )
        ),
        new TextIs(
            new Joined(
                TkRedirectTest.NEWLINE,
                "HTTP/1.1 302 Found",
                String.format(TkRedirectTest.LOCATION, url),
                "",
                ""
            )
        )
    );
}
 
Example #16
Source File: TkRetryTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkRetry can retry when initial take fails with IOException,
 * till get successful result.
 *
 * @throws Exception if something is wrong
 */
@Test
public void retriesOnExceptionTillSuccess() throws Exception {
    final int count = Tv.THREE;
    final int delay = Tv.THOUSAND;
    final String data = "data";
    final Take take = Mockito.mock(Take.class);
    Mockito
        .when(take.act(Mockito.any(Request.class)))
        .thenThrow(new IOException())
        .thenReturn(new RsText(data));
    final long start = System.nanoTime();
    final RsPrint response = new RsPrint(
        new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET))
    );
    final long spent = System.nanoTime() - start;
    MatcherAssert.assertThat(
        Long.valueOf(delay - Tv.HUNDRED) * Tv.MILLION,
        Matchers.lessThanOrEqualTo(spent)
    );
    MatcherAssert.assertThat(
        response,
        new TextHasString(data)
    );
}
 
Example #17
Source File: RsReturnTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsReturn can add cookies.
 * @throws IOException If some problem inside
 */
@Test
public void addsCookieToResponse() throws IOException {
    final String destination = "/return/to";
    MatcherAssert.assertThat(
        new RsPrint(
            new RsReturn(new RsEmpty(), destination)
        ),
        new TextHasString(
            new FormattedText(
                "Set-Cookie: RsReturn=%s;Path=/",
                URLEncoder.encode(
                    destination,
                    Charset.defaultCharset().name()
                )
            )
        )
    );
}
 
Example #18
Source File: TkPreviousTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkPrevious can redirect.
 * @throws Exception If some problem inside
 */
@Test
public void redirectsOnCookie() throws Exception {
    MatcherAssert.assertThat(
        new RsPrint(
            new TkPrevious(new TkText("")).act(
                new RqWithHeader(
                    new RqFake(),
                    "Cookie",
                    "TkPrevious=/home"
                )
            )
        ),
        new StartsWith("HTTP/1.1 303 See Other")
    );
}
 
Example #19
Source File: TkRedirectTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkRedirect can create a response with url string.
 * @throws Exception If some problem inside
 */
@Test
public void createsRedirectResponseWithUrl() throws Exception {
    final String url = "/about";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkRedirect(url).act(new RqFake())
        ),
        new TextIs(
            new Joined(
                TkRedirectTest.NEWLINE,
                "HTTP/1.1 303 See Other",
                String.format(TkRedirectTest.LOCATION, url),
                "",
                ""
            )
        )
    );
}
 
Example #20
Source File: RsFlashTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsFlash can add cookies.
 * @throws IOException If some problem inside
 */
@Test
public void addsCookieToResponse() throws IOException {
    final String msg = "hey, how are you?";
    new Assertion<>(
        "Response must contain a flash cookie",
        new RsPrint(
            new RsFlash(msg)
        ),
        new TextHasString(
            new FormattedText(
                "Set-Cookie: RsFlash=%s/%s",
                URLEncoder.encode(
                    msg,
                    Charset.defaultCharset().name()
                ),
                Level.INFO.getName()
            )
        )
    ).affirm();
}
 
Example #21
Source File: TkJoinedCookiesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkJoinedCookies can join cookies.
 * @throws Exception If some problem inside
 */
@Test
public void joinsCookies() throws Exception {
    new Assertion<>(
        "Response with joined cookies",
        new RsPrint(
            new TkJoinedCookies(
                new TkFixed(
                    new RsWithHeaders(
                        new RsText(),
                        "Set-Cookie: a=1",
                        "Set-cookie: b=1; Path=/"
                    )
                )
            ).act(new RqFake())
        ),
        new TextHasString("Set-Cookie: a=1, b=1; Path=/")
    ).affirm();
}
 
Example #22
Source File: RsWithCookieTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsWithCookie can add cookies.
 */
@Test
public void addsCookieToResponse() {
    new Assertion<>(
        "Response should contain \"Set-Cookie\" header",
        new RsPrint(
            new RsWithCookie(
                "foo",
                "works?",
                "Path=/"
            )
        ),
        new TextHasString(
            new Joined(
                RsWithCookieTest.CRLF,
                "Set-Cookie: foo=works?;Path=/;",
                ""
            )
        )
    ).affirm();
}
 
Example #23
Source File: RsWithCookieTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsWithCookie can add several cookies (with several decorations).
 */
@Test
public void addsMultipleCookies() {
    new Assertion<>(
        "Response should contain \"Set-Cookie\" headers",
        new RsPrint(
            new RsWithCookie(
                new RsWithCookie(
                    "qux",
                    "value?",
                    "Path=/qux"
                ),
                "bar", "worksToo?", "Path=/2nd/path/"
            )
        ),
        new TextHasString(
            new Joined(
                RsWithCookieTest.CRLF,
                "Set-Cookie: qux=value?;Path=/qux;",
                "Set-Cookie: bar=worksToo?;Path=/2nd/path/;",
                ""
            )
        )
    ).affirm();
}
 
Example #24
Source File: FbStatusTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FbStatus can react to Condition.
 * @throws Exception If some problem inside
 */
@Test
public void reactsToCondition() throws Exception {
    final RqFallback req = new RqFallback.Fake(
        HttpURLConnection.HTTP_MOVED_PERM
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new FbStatus(
                new Filtered<>(
                    status -> {
                        return status == HttpURLConnection.HTTP_MOVED_PERM
                            || status == HttpURLConnection.HTTP_MOVED_TEMP;
                    },
                    new ListOf<>(
                        HttpURLConnection.HTTP_MOVED_PERM,
                        HttpURLConnection.HTTP_MOVED_TEMP
                    )
                ),
                new FbFixed(new RsText("response text"))
            ).route(req).get()
        ).printBody(),
        Matchers.startsWith("response")
    );
}
 
Example #25
Source File: FbStatusTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FbStatus can send correct default response with text/plain
 * body consisting of a status code, status message and message
 * from an exception.
 * @throws Exception If some problem inside
 */
@Test
public void sendsCorrectDefaultResponse() throws Exception {
    final int code = HttpURLConnection.HTTP_NOT_FOUND;
    final RqFallback req = new RqFallback.Fake(
        code,
        new IOException("Exception message")
    );
    final RsPrint response = new RsPrint(
        new FbStatus(code).route(req).get()
    );
    MatcherAssert.assertThat(
        response.printBody(),
        Matchers.equalTo("404 Not Found: Exception message")
    );
    MatcherAssert.assertThat(
        response.printHead(),
        Matchers.both(
            Matchers.containsString("Content-Type: text/plain")
        ).and(Matchers.containsString("404 Not Found"))
    );
}
 
Example #26
Source File: FbChainTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FbChain can chain fallbacks.
 * @throws Exception If some problem inside
 */
@Test
public void chainsFallbacks() throws Exception {
    final RqFallback req = new RqFallback.Fake(
        HttpURLConnection.HTTP_NOT_FOUND
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new FbChain(
                new FbEmpty(),
                new FbFixed(new RsText("first rs")),
                new FbFixed(new RsText("second rs"))
            ).route(req).get()
        ).printBody(),
        Matchers.startsWith("first")
    );
}
 
Example #27
Source File: TkFallbackTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkFallback can fall back.
 * @throws Exception If some problem inside
 */
@Test
public void fallsBack() throws Exception {
    final String err = "message";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkFallback(
                new TkFailure(err),
                new Fallback() {
                    @Override
                    public Opt<Response> route(final RqFallback req) {
                        return new Opt.Single<Response>(
                            new RsText(req.throwable().getMessage())
                        );
                    }
                }
            ).act(new RqFake())
        ).printBody(),
        Matchers.endsWith(err)
    );
}
 
Example #28
Source File: TkForwardTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkForward can catch RsForward.
 * @throws Exception If some problem inside
 */
@Test
public void catchesExceptionCorrectly() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws RsForward {
            throw new RsForward("/");
        }
    };
    MatcherAssert.assertThat(
        new RsPrint(
            new TkForward(take).act(new RqFake())
        ),
        new StartsWith("HTTP/1.1 303 See Other")
    );
}
 
Example #29
Source File: TkForwardTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkForward can catch RsForward throws by Response.
 * @throws Exception If some problem inside
 */
@Test
public void catchesExceptionThrownByResponse() throws Exception {
    final Take take =
        request -> new ResponseOf(
            () -> new RsEmpty().head(),
            () -> {
                throw new RsForward("/b");
            }
        );
    MatcherAssert.assertThat(
        new RsPrint(
            new TkForward(take).act(new RqFake())
        ),
        new StartsWith("HTTP/1.1 303")
    );
}
 
Example #30
Source File: TkProxyTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkProxy can just work.
 * @throws Exception If some problem inside
 */
@Test
public void justWorks() throws Exception {
    new FtRemote(
        new TkFork(
            new FkMethods(this.method, new TkFixed(this.expected))
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws Exception {
                MatcherAssert.assertThat(
                    new RsPrint(
                        new TkProxy(home).act(
                            new RqFake(TkProxyTest.this.method)
                        )
                    ),
                    new TextHasString(
                        TkProxyTest.this.expected
                    )
                );
            }
        }
    );
}