org.takes.rq.RqFake Java Examples

The following examples show how to use org.takes.rq.RqFake. 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: RqFormBaseTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RqFormBase can return the same (cached) instances in every call.
 * @throws IOException if fails
 */
@Test
public void sameInstance() throws IOException {
    final RqForm req = new RqFormBase(
        new RqBuffered(
            new RqFake(
                Arrays.asList(
                    "GET /path?a=3",
                    "Host: www.example2.com"
                ),
                "alpha=a+b+c&beta=%20No%20"
            )
        )
    );
    MatcherAssert.assertThat(
        req.names() == req.names(),
        Matchers.is(Boolean.TRUE)
    );
}
 
Example #2
Source File: XeFacebookLinkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * XeFacebookLink can create a correct link.
 * @throws IOException If some problem inside
 */
@Test
public void generatesCorrectLink() throws IOException {
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                new XeAppend(
                    "root",
                    new XeFacebookLink(new RqFake(), "abcdef")
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPaths(
            "/root/links/link[@rel='takes:facebook']"
        )
    );
}
 
Example #3
Source File: TkRetryTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkRetry can retry when initial take fails once
 * with IOException, till retry count is reached.
 *
 * @throws Exception if something is wrong
 */
@Test(expected = IOException.class)
public void retriesOnExceptionTillCount() throws Exception {
    final int count = Tv.THREE;
    final int delay = Tv.THOUSAND;
    final Take take = Mockito.mock(Take.class);
    Mockito
        .when(take.act(Mockito.any(Request.class)))
        .thenThrow(new IOException());
    final long start = System.nanoTime();
    try {
        new TkRetry(count, delay, take).act(
            new RqFake(RqMethod.GET)
        );
    } catch (final IOException exception) {
        final long spent = System.nanoTime() - start;
        MatcherAssert.assertThat(
            Long.valueOf(count * delay - Tv.HUNDRED) * Tv.MILLION,
            Matchers.lessThanOrEqualTo(spent)
        );
        throw exception;
    }
}
 
Example #4
Source File: TkRelayTest.java    From jare with MIT License 6 votes vote down vote up
/**
 * Fake request.
 * @param home Base URI
 * @param path Path
 * @return Request
 * @throws UnsupportedEncodingException If fails
 */
private static Request fake(final URI home, final String path)
    throws UnsupportedEncodingException {
    return new RqFake(
        Arrays.asList(
            String.format(
                "GET /?u=%s",
                URLEncoder.encode(
                    home.resolve(path).toString(),
                    "UTF-8"
                )
            ),
            "Host: localhost"
        ),
        ""
    );
}
 
Example #5
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 #6
Source File: TkAppTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public void pingsSimplePages(@TempDir final Path temp) throws Exception {
    final String[] pages = {
        "/org/jpeek/web/layout.xsl",
        "/org/jpeek/web/index.xsl",
        "/jpeek.css",
        "/",
        "/mistakes",
        "/robots.txt",
    };
    final Take app = new TkApp(temp);
    for (final String page : pages) {
        final Response response = app.act(new RqFake("GET", page));
        new Assertion<>(
            new RsPrint(response).print(),
            response,
            new HmRsStatus(HttpURLConnection.HTTP_OK)
        ).affirm();
    }
}
 
Example #7
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 #8
Source File: TkSecureTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkSecure can pass on registered user.
 * @throws Exception If some problem inside
 */
@Test
public void passesOnRegisteredUser() throws Exception {
    MatcherAssert.assertThat(
        new TkSecure(
            new Take() {
                @Override
                public Response act(final Request request) {
                    return new RsEmpty();
                }
            }
        ).act(
            new RqWithHeader(
                new RqFake(),
                TkAuth.class.getSimpleName(),
                new String(
                    new CcPlain().encode(new Identity.Simple("urn:test:2"))
                )
            )
        ),
        Matchers.instanceOf(RsEmpty.class)
    );
}
 
Example #9
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 #10
Source File: HmBodyTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * HmRqBody can describe mismatch in readable way.
 */
@Test
public void describesMismatchInReadableWay() {
    final Request request = new RqFake(
        Collections.<String>emptyList(),
        "other"
    );
    final HmBody<Body> matcher = new HmBody<>("some");
    matcher.matchesSafely(request);
    final StringDescription description = new StringDescription();
    matcher.describeMismatchSafely(request, description);
    MatcherAssert.assertThat(
        description.toString(),
        new IsEqual<>(
            "body was: [111, 116, 104, 101, 114]"
        )
    );
}
 
Example #11
Source File: RqCookiesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RqCookies can parse a query with empty cookie.
 * @throws IOException If some problem inside
 */
@Test
public void parsesHttpQueryWithEmptyCookie() throws IOException {
    MatcherAssert.assertThat(
        new RqCookies.Base(
            new RqFake(
                Arrays.asList(
                    "GET /hzzz",
                    "Host: abc.example.com",
                    "Cookie: test="
                ),
                ""
            )
        ).cookie("test"),
        Matchers.emptyIterable()
    );
}
 
Example #12
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
                    )
                );
            }
        }
    );
}
 
Example #13
Source File: TkConsumesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkConsumes can fail on unsupported Content-Type header.
 * @throws Exception If some problem inside
 */
@Test(expected = HttpException.class)
public void failsOnUnsupportedAcceptHeader() throws Exception {
    final Take consumes = new TkConsumes(
        new TkFixed(new RsJson(new RsEmpty())),
        TkConsumesTest.APPLICATION_JSON
    );
    consumes.act(
        new RqFake(
            Arrays.asList(
                "GET /?TkConsumes error",
                "Content-Type: application/xml"
            ),
            ""
        )
    ).head();
}
 
Example #14
Source File: TkProducesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkProduces can fail on unsupported Accept header.
 * @throws Exception If some problem inside
 */
@Test(expected = HttpException.class)
public void failsOnUnsupportedAcceptHeader() throws Exception {
    final Take produces = new TkProduces(
        new TkEmpty(),
        "text/json,application/json"
    );
    produces.act(
        new RqFake(
            Arrays.asList(
                "GET /hz0",
                "Host: as0.example.com",
                "Accept: text/xml"
            ),
            ""
        )
    ).head();
}
 
Example #15
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 #16
Source File: XeGoogleLinkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * XeGoogleLink can create a correct link.
 * @throws IOException If some problem inside
 */
@Test
public void generatesCorrectLink() throws IOException {
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                new XeAppend(
                    "root",
                    new XeGoogleLink(new RqFake(), "abcdef")
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPaths(
            "/root/links/link[@rel='takes:google']"
        )
    );
}
 
Example #17
Source File: FkContentTypeTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkContentType can match by Content-Type header with identical types.
 * @throws Exception If some problem inside
 */
@Test
public void matchesIdenticalTypes() throws Exception {
    MatcherAssert.assertThat(
        new FkContentType(
            FkContentTypeTest.CTYPE,
            FkContentTypeTest.emptyResponse()
        ).route(
            new RqWithHeader(
                new RqFake(),
                FkContentTypeTest.CONTENT_TYPE,
                FkContentTypeTest.CTYPE
            )
        ).has(),
        Matchers.is(true)
    );
}
 
Example #18
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 #19
Source File: FkContentTypeTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkContentType can match by Content-Type header with different encodings.
 * @throws Exception If some problem inside
 */
@Test
public void matchesDifferentEncodingsTypes() throws Exception {
    MatcherAssert.assertThat(
        new FkContentType(
            FkContentTypeTest.CTYPE,
            FkContentTypeTest.emptyResponse()
        ).route(
            new RqWithHeader(
                new RqFake(),
                FkContentTypeTest.CONTENT_TYPE,
                "text/html charset=utf8"
            )
        ).has(),
        Matchers.is(false)
    );
}
 
Example #20
Source File: HmHeaderTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * HmRqHeader can test whether a header is available.
 * @throws Exception If some problem inside
 */
@Test
public void testsHeaderAvailable() throws Exception {
    MatcherAssert.assertThat(
        new RqFake(
            Arrays.asList(
                "GET /f?a=3&b-6",
                "Host: example.com",
                "Accept: text/xml",
                "Accept: text/html"
            ),
            ""
        ),
        new HmHeader<>(
            "accept", Matchers.hasItems("text/xml", "text/html")
        )
    );
}
 
Example #21
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 #22
Source File: FkTypesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkTypes can match by Accept header.
 * @throws Exception If some problem inside
 */
@Test
public void matchesByAcceptHeader() throws Exception {
    final String accept = "Accept";
    MatcherAssert.assertThat(
        new FkTypes("text/xml", new RsEmpty()).route(
            new RqWithHeader(new RqFake(), accept, "*/* ")
        ).has(),
        Matchers.is(true)
    );
    MatcherAssert.assertThat(
        new FkTypes("application/json", new RsEmpty()).route(
            new RqWithHeader(new RqFake(), accept, "image/*")
        ).has(),
        Matchers.is(false)
    );
    MatcherAssert.assertThat(
        new FkTypes("*/*", new RsEmpty()).route(
            new RqWithHeader(new RqFake(), accept, "text/html")
        ).has(),
        Matchers.is(true)
    );
}
 
Example #23
Source File: FkRegexTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkRegex can match by regular expression.
 * @throws Exception If some problem inside
 */
@Test
public void matchesByRegularExpression() throws Exception {
    MatcherAssert.assertThat(
        new FkRegex("/h[a-z]{2}", new TkEmpty()).route(
            new RqFake("GET", "/hel?a=1")
        ).has(),
        Matchers.is(true)
    );
    MatcherAssert.assertThat(
        new FkRegex("/", new TkEmpty()).route(
            new RqFake("PUT", "/?test")
        ).has(),
        Matchers.is(true)
    );
}
 
Example #24
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 #25
Source File: FkHitRefreshTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkHitRefresh can refresh on demand.
 * @throws Exception If some problem inside
 */
@Test
public void refreshesOnDemand() throws Exception {
    final Request req = new RqWithHeader(
        new RqFake(), "X-Takes-HitRefresh: yes"
    );
    final AtomicBoolean done = new AtomicBoolean(false);
    final Fork fork = new FkHitRefresh(
        this.temp.getRoot(),
        new Runnable() {
            @Override
            public void run() {
                done.set(true);
            }
        },
        new TkEmpty()
    );
    TimeUnit.SECONDS.sleep(2L);
    FileUtils.touch(this.temp.newFile("hey.txt"));
    MatcherAssert.assertThat(
        fork.route(req).has(),
        Matchers.is(true)
    );
    MatcherAssert.assertThat(done.get(), Matchers.is(true));
}
 
Example #26
Source File: TkReturnTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkReturn can redirect to return location
 * and remove a return cookie.
 * @throws Exception If some problem inside
 */
@Test
public void redirectsAndRemovesCookie() throws Exception {
    final Take take = new TkReturn(new TkEmpty());
    final String destination = "/return/to";
    MatcherAssert.assertThat(
        take.act(
            new RqWithHeader(
                new RqFake(),
                String.format(
                    "Cookie: RsReturn=%s;",
                    URLEncoder.encode(
                        destination,
                        Charset.defaultCharset().name()
                    )
                )
            )
        ).head(),
        Matchers.contains(
            "HTTP/1.1 303 See Other",
            String.format("Location: %s", destination),
            "Set-Cookie: RsReturn=;"
        )
    );
}
 
Example #27
Source File: FkChainTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FkChain can dispatch by regular expression.
 * @throws Exception If some problem inside
 */
@Test
public void dispatchesByRegularExpression() throws Exception {
    final String body = "hello test!";
    MatcherAssert.assertThat(
        new RsPrint(
            new FkChain(
                new FkRegex("/g[a-z]{2}", ""),
                new FkRegex("/h[a-z]{2}", body),
                new FkRegex("/i[a-z]{2}", "")
            ).route(new RqFake("GET", "/hey?yu")).get()
        ),
        new TextIs(
            new Joined(
                "\r\n",
                "HTTP/1.1 200 OK",
                String.format("Content-Length: %s", body.length()),
                "Content-Type: text/plain",
                "",
                body
            )
        )
    );
}
 
Example #28
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 negotiatesContent() throws IOException {
    final Request req = new RqFake(
        Arrays.asList(
            "GET /hello.html",
            "Accept: text/xml; q=0.3, text/plain; q=0.1",
            "Accept: */*; q=0.05"
        ),
        ""
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new RsFork(
                req,
                new FkTypes("text/plain", new RsText("it's a text")),
                new FkTypes("image/*", new RsText("it's an image"))
            )
        ).printBody(),
        Matchers.endsWith("a text")
    );
}
 
Example #29
Source File: XeGithubLinkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * XeGithubLink can create a correct link.
 * @throws IOException If some problem inside
 */
@Test
public void generatesCorrectLink() throws IOException {
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                new XeAppend(
                    "root",
                    new XeGithubLink(new RqFake(), "abcdef")
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPaths(
            "/root/links/link[@rel='takes:github']"
        )
    );
}
 
Example #30
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?")
    );
}