Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix: tests adapted to new Deno.test API #98

Merged
merged 2 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions agent_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import Reader = Deno.Reader;
import Buffer = Deno.Buffer;
import copy = Deno.copy;
import { it } from "./test_util.ts";
import { group } from "./test_util.ts";
import { ServeListener } from "./server.ts";

async function readString(r: Reader) {
Expand All @@ -36,13 +36,13 @@ function setupRouter(port: number): ServeListener {
return app.listen({ port });
}

it("agent", (t) => {
group("agent", ({ test, setupAll }) => {
let port = 8700;
t.beforeAfterAll(() => {
setupAll(() => {
const listener = setupRouter(port);
return () => listener.close();
});
t.run("basic", async () => {
test("basic", async () => {
const agent = createAgent(`http://127.0.0.1:${port}`);
try {
{
Expand All @@ -66,7 +66,7 @@ it("agent", (t) => {
agent.conn.close();
}
});
t.run("agentTls", async () => {
test("agentTls", async () => {
const agent = createAgent(`https://httpbin.org`);
try {
{
Expand Down Expand Up @@ -96,7 +96,7 @@ it("agent", (t) => {
agent.conn.close();
}
});
t.run("agent unread body", async () => {
test("agent unread body", async () => {
const agent = createAgent(`http://127.0.0.1:${port}`);
try {
await agent.send({ path: "/get", method: "GET" });
Expand All @@ -111,7 +111,7 @@ it("agent", (t) => {
agent.conn.close();
}
});
t.run("agent invalid scheme", async () => {
test("agent invalid scheme", async () => {
assertThrows(() => {
createAgent("ftp://127.0.0.1");
});
Expand Down
22 changes: 13 additions & 9 deletions app_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,52 @@ import {
assertEquals,
assertMatch,
} from "./vendor/https/deno.land/std/testing/asserts.ts";
import { it, makeGet, assertRoutingError } from "./test_util.ts";
import { group, makeGet } from "./test_util.ts";
import { Loglevel, setLevel } from "./logger.ts";
import { connectWebSocket } from "./vendor/https/deno.land/std/ws/mod.ts";
setLevel(Loglevel.NONE);

it("app", (t) => {
group({
name: "app",
}, ({ setupAll, test }) => {
const app = createApp();
app.handle("/no-response", () => {});
app.handle("/throw", () => {
throw new Error("throw");
});
const get = makeGet(app);
t.beforeAfterAll(() => {
setupAll(() => {
const l = app.listen({ port: 8899 });
return () => l.close();
});
t.run("should respond if req.respond wasn't called", async () => {
test("should respond if req.respond wasn't called", async () => {
const res = await get("/no-response");
assertEquals(res.status, 404);
});
t.run("should respond for unknown path", async () => {
test("should respond for unknown path", async () => {
const res = await get("/not-found");
assertEquals(res.status, 404);
});
t.run("should handle global error", async () => {
test("should handle global error", async () => {
const res = await get("/throw");
const text = await res.body.text();
assertEquals(res.status, 500);
assertMatch(text, /Error: throw/);
});
});
it("app/ws", (t) => {
group({
name: "app/ws",
}, ({ test, setupAll }) => {
const app = createApp();
app.ws("/ws", async (sock) => {
await sock.send("Hello");
await sock.close(1000);
});
t.beforeAfterAll(() => {
setupAll(() => {
const l = app.listen({ port: 8890 });
return () => l.close();
});
t.run("should accept ws", async () => {
test("should accept ws", async () => {
const sock = await connectWebSocket("ws://127.0.0.1:8890/ws");
const it = sock.receive();
const { value: msg1 } = await it.next();
Expand Down
8 changes: 4 additions & 4 deletions body_parser_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {
import { parserMultipartRequest } from "./body_parser.ts";
import * as fs from "./vendor/https/deno.land/std/fs/mod.ts";
import Buffer = Deno.Buffer;
import { it } from "./test_util.ts";
import { group } from "./test_util.ts";

it("multipart", (t) => {
t.run("basic", async () => {
group("multipart", ({ test }) => {
test("basic", async () => {
const buf = new Buffer();
const w = new MultipartWriter(buf);
await w.writeField("deno", "land");
Expand All @@ -38,7 +38,7 @@ it("multipart", (t) => {
await m.removeAllTempFiles();
assertEquals(await fs.exists(mfile.tempfile!), false);
});
t.run("should throw if content-type is invalid", async () => {
test("should throw if content-type is invalid", async () => {
const body = new Buffer();
await assertThrowsAsync(async () => {
await parserMultipartRequest({
Expand Down
14 changes: 14 additions & 0 deletions boilerplates/basic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {
createApp,
createRouter,
serveStatic,
} from "../mod.ts";
import { RoutingError } from "../error.ts";
const app = createApp();
app.use(serveStatic("public"));
app.get("/", async (req) => {
req.respond({ status: 200, body: "Hello Servest🌾" });
});
app.handle(new RegExp("^/users/(\d+?)$"));

app.listen({ port: parseInt(Deno.env("PORT") ?? "8899") });
50 changes: 50 additions & 0 deletions boilerplates/rest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { createApp, createRouter } from "../mod.ts";

const app = createApp();
type User = {
id: number;
name: string;
};
function isUser(x: any): x is User {
return x != null && typeof x.id === "number" && typeof x.name === "string";
}

function UserRoute() {
const router = createRouter();
const userDB = new Map<number, User>();
router.get("/", (req) => {
req.respond({ status: 200, body: JSON.stringify(userDB.values()) });
});
const regex = new RegExp("^/uesrs/(\d+?)$");
router.get(regex, (req, { match }) => {
const id = parseInt(match[1]);
const user = userDB.get(id);
if (user) {
req.respond({ status: 200, body: JSON.stringify(user) });
} else {
req.respond({ status: 404 });
}
});
router.put(regex, async (req, { match }) => {
const id = parseInt(match[1]);
const user = await req.body?.json();
if (isUser(user) && id === user.id) {
userDB.set(id, { id, name: user.name });
req.respond({ status: 201, body: JSON.stringify(user) });
} else {
req.respond({ status: 400 });
}
});
router.delete(regex, (req, { match }) => {
const id = parseInt(match[1]);
if (userDB.has(id)) {
userDB.delete(id);
req.respond({ status: 200 });
} else {
req.respond({ status: 404 });
}
});
return router;
}
app.route("/users", UserRoute());
app.listen({ port: parseInt(Deno.env("PORT") ?? "8899") });
25 changes: 13 additions & 12 deletions cookie_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import {
assertEquals,
assertThrows,
} from "./vendor/https/deno.land/std/testing/asserts.ts";
import { it } from "./test_util.ts";
import { group } from "./test_util.ts";
import { cookieToString, parseCookie, parseSetCookie } from "./cookie.ts";
import { toIMF } from "./vendor/https/deno.land/std/datetime/mod.ts";
import { createApp } from "./app.ts";

it("parseCookie", (t) => {
t.run("basic", () => {
group("parseCookie", ({ test }) => {
test("basic", () => {
const cookie = parseCookie(
`deno=land; foo=var; ${encodeURIComponent("👉=🦕")}`,
);
Expand All @@ -19,13 +19,13 @@ it("parseCookie", (t) => {
assertEquals(cookie.get("👉"), "🦕");
});
});
it("parseSetCookie", (t) => {
group("parseSetCookie", ({ test }) => {
const expires = new Date();
const maxAge = 1000;
const domain = "servestjs.org";
const path = "/path";
const sameSite = "Lax";
t.run("basic", () => {
test("basic", () => {
const e = `deno=land; Expires=${toIMF(
expires,
)}; Max-Age=${maxAge}; Domain=${domain}; Path=${path}; Secure; HttpOnly; SameSite=${sameSite}`;
Expand All @@ -41,8 +41,8 @@ it("parseSetCookie", (t) => {
assertEquals(opts.sameSite, sameSite);
});
});
it("cookieToString", (t) => {
t.run("basic", () => {
group("cookieToString", ({ test }) => {
test("basic", () => {
const expires = new Date();
const maxAge = 1000;
const domain = "servestjs.org";
Expand All @@ -64,14 +64,14 @@ it("cookieToString", (t) => {
)}; Max-Age=${maxAge}; Domain=${domain}; Path=${path}; Secure; HttpOnly; SameSite=${sameSite}`,
);
});
t.run("should throw if maxAge is not integer", () => {
test("should throw if maxAge is not integer", () => {
assertThrows(() =>
cookieToString("deno", "land", {
maxAge: 1.11,
})
);
});
t.run("should throw if maxAge is lesser than or equals 0", () => {
test("should throw if maxAge is lesser than or equals 0", () => {
assertThrows(() => {
cookieToString("deno", "land", {
maxAge: -1,
Expand All @@ -80,10 +80,10 @@ it("cookieToString", (t) => {
});
});

it("cookie integration", (t) => {
group("cookie integration", ({ setupAll, test }) => {
const now = new Date();
now.setMilliseconds(0);
t.beforeAfterAll(() => {
setupAll(() => {
const router = createApp();
router.get("/", (req) => {
req.setCookie("deno", "land", {
Expand All @@ -100,11 +100,12 @@ it("cookie integration", (t) => {
const lis = router.listen({ port: 9983 });
return () => lis.close();
});
t.run("basic", async () => {
test("basic", async () => {
const resp = await fetch("http://127.0.0.1:9983/");
const sc = resp.headers.get("Set-Cookie");
assert(sc != null, "should set cookie");
const cookie = parseSetCookie(sc);
resp.body.close();
assertEquals(cookie, {
name: "deno",
value: "land",
Expand Down
8 changes: 4 additions & 4 deletions matcher_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import {
resolveIndexPath,
} from "./matcher.ts";
import { assertEquals } from "./vendor/https/deno.land/std/testing/asserts.ts";
import { it } from "./test_util.ts";
import { group } from "./test_util.ts";

it("matcher", (t) => {
group("matcher", ({ test }) => {
type Pat = [string, (string | RegExp)[], number[]][];
([
["/foo", ["/foo", "/bar", "/f"], [0]],
Expand All @@ -19,7 +19,7 @@ it("matcher", (t) => {
["/foo", [/\/foo/, /\/bar\/foo/], [0]],
["/foo", [/\/a\/foo/, /\/foo/], [1]],
] as Pat).forEach(([path, pat, idx]) => {
t.run("findLongestAndNearestMatch:" + path, () => {
test("findLongestAndNearestMatch:" + path, () => {
const matches = findLongestAndNearestMatches(path, pat);
assertEquals(matches.length, idx.length);
for (let i = 0; i < idx.length; i++) {
Expand All @@ -28,7 +28,7 @@ it("matcher", (t) => {
});
});

t.run("resolveIndexPath", async () => {
test("resolveIndexPath", async () => {
for (
const [dir, fp, exp] of [
[".", "/README.md", "README.md"],
Expand Down
8 changes: 4 additions & 4 deletions middleware_test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { basicAuth } from "./middleware.ts";
import { it } from "./test_util.ts";
import { group } from "./test_util.ts";
import {
assertEquals,
} from "./vendor/https/deno.land/std/testing/asserts.ts";
import { createRecorder } from "./testing.ts";
it("middleware", (t) => {
t.run("basicAuth", async () => {
group("middleware", ({ test }) => {
test("basicAuth", async () => {
const auth = basicAuth({
username: "deno",
password: "land",
Expand All @@ -31,7 +31,7 @@ it("middleware", (t) => {
await auth(req);
assertEquals(req.isResponded(), false);
});
t.run("basicAuth failed", async () => {
test("basicAuth failed", async () => {
const patterns = [
"Basic hoge",
`Basic ${btoa("deno:js")}`,
Expand Down
Loading