1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-05 13:59:01 -05:00

avoid using same port number for test (#4147)

This commit is contained in:
Yusuke Sakurai 2020-03-21 22:53:47 +09:00 committed by GitHub
parent 0adc86f105
commit 60cee4f045
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 165 additions and 63 deletions

View file

@ -3,14 +3,16 @@ import {
unitTest, unitTest,
assert, assert,
assertEquals, assertEquals,
createResolvable createResolvable,
randomPort
} from "./test_util.ts"; } from "./test_util.ts";
unitTest({ perms: { net: true } }, function netTcpListenClose(): void { unitTest({ perms: { net: true } }, function netTcpListenClose(): void {
const listener = Deno.listen({ hostname: "127.0.0.1", port: 4500 }); const port = randomPort();
const listener = Deno.listen({ hostname: "127.0.0.1", port });
assertEquals(listener.addr.transport, "tcp"); assertEquals(listener.addr.transport, "tcp");
assertEquals(listener.addr.hostname, "127.0.0.1"); assertEquals(listener.addr.hostname, "127.0.0.1");
assertEquals(listener.addr.port, 4500); assertEquals(listener.addr.port, port);
listener.close(); listener.close();
}); });
@ -21,14 +23,15 @@ unitTest(
ignore: Deno.build.os === "win" ignore: Deno.build.os === "win"
}, },
function netUdpListenClose(): void { function netUdpListenClose(): void {
const port = randomPort();
const socket = Deno.listen({ const socket = Deno.listen({
hostname: "127.0.0.1", hostname: "127.0.0.1",
port: 4500, port,
transport: "udp" transport: "udp"
}); });
assertEquals(socket.addr.transport, "udp"); assertEquals(socket.addr.transport, "udp");
assertEquals(socket.addr.hostname, "127.0.0.1"); assertEquals(socket.addr.hostname, "127.0.0.1");
assertEquals(socket.addr.port, 4500); assertEquals(socket.addr.port, port);
socket.close(); socket.close();
} }
); );
@ -38,7 +41,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netTcpCloseWhileAccept(): Promise<void> { async function netTcpCloseWhileAccept(): Promise<void> {
const listener = Deno.listen({ port: 4501 }); const port = randomPort();
const listener = Deno.listen({ port });
const p = listener.accept(); const p = listener.accept();
listener.close(); listener.close();
let err; let err;
@ -56,7 +60,8 @@ unitTest(
unitTest( unitTest(
{ perms: { net: true } }, { perms: { net: true } },
async function netTcpConcurrentAccept(): Promise<void> { async function netTcpConcurrentAccept(): Promise<void> {
const listener = Deno.listen({ port: 4502 }); const port = randomPort();
const listener = Deno.listen({ port });
let acceptErrCount = 0; let acceptErrCount = 0;
const checkErr = (e: Error): void => { const checkErr = (e: Error): void => {
if (e.message === "Listener has been closed") { if (e.message === "Listener has been closed") {
@ -79,19 +84,20 @@ unitTest(
unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise< unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise<
void void
> { > {
const listener = Deno.listen({ port: 4500 }); const port = randomPort();
const listener = Deno.listen({ port });
listener.accept().then( listener.accept().then(
async (conn): Promise<void> => { async (conn): Promise<void> => {
assert(conn.remoteAddr != null); assert(conn.remoteAddr != null);
assertEquals(conn.localAddr.hostname, "127.0.0.1"); assertEquals(conn.localAddr.hostname, "127.0.0.1");
assertEquals(conn.localAddr.port, 4500); assertEquals(conn.localAddr.port, port);
await conn.write(new Uint8Array([1, 2, 3])); await conn.write(new Uint8Array([1, 2, 3]));
conn.close(); conn.close();
} }
); );
const conn = await Deno.connect({ hostname: "127.0.0.1", port: 4500 }); const conn = await Deno.connect({ hostname: "127.0.0.1", port });
assertEquals(conn.remoteAddr.hostname, "127.0.0.1"); assertEquals(conn.remoteAddr.hostname, "127.0.0.1");
assertEquals(conn.remoteAddr.port, 4500); assertEquals(conn.remoteAddr.port, port);
assert(conn.localAddr != null); assert(conn.localAddr != null);
const buf = new Uint8Array(1024); const buf = new Uint8Array(1024);
const readResult = await conn.read(buf); const readResult = await conn.read(buf);
@ -113,13 +119,15 @@ unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise<
unitTest( unitTest(
{ ignore: Deno.build.os === "win", perms: { net: true } }, { ignore: Deno.build.os === "win", perms: { net: true } },
async function netUdpSendReceive(): Promise<void> { async function netUdpSendReceive(): Promise<void> {
const alice = Deno.listen({ port: 4500, transport: "udp" }); const alicePort = randomPort();
assertEquals(alice.addr.port, 4500); const alice = Deno.listen({ port: alicePort, transport: "udp" });
assertEquals(alice.addr.port, alicePort);
assertEquals(alice.addr.hostname, "0.0.0.0"); assertEquals(alice.addr.hostname, "0.0.0.0");
assertEquals(alice.addr.transport, "udp"); assertEquals(alice.addr.transport, "udp");
const bob = Deno.listen({ port: 4501, transport: "udp" }); const bobPort = randomPort();
assertEquals(bob.addr.port, 4501); const bob = Deno.listen({ port: bobPort, transport: "udp" });
assertEquals(bob.addr.port, bobPort);
assertEquals(bob.addr.hostname, "0.0.0.0"); assertEquals(bob.addr.hostname, "0.0.0.0");
assertEquals(bob.addr.transport, "udp"); assertEquals(bob.addr.transport, "udp");
@ -127,7 +135,7 @@ unitTest(
await alice.send(sent, bob.addr); await alice.send(sent, bob.addr);
const [recvd, remote] = await bob.receive(); const [recvd, remote] = await bob.receive();
assertEquals(remote.port, 4500); assertEquals(remote.port, alicePort);
assertEquals(recvd.length, 3); assertEquals(recvd.length, 3);
assertEquals(1, recvd[0]); assertEquals(1, recvd[0]);
assertEquals(2, recvd[1]); assertEquals(2, recvd[1]);
@ -140,7 +148,8 @@ unitTest(
unitTest( unitTest(
{ perms: { net: true } }, { perms: { net: true } },
async function netTcpListenCloseWhileIterating(): Promise<void> { async function netTcpListenCloseWhileIterating(): Promise<void> {
const listener = Deno.listen({ port: 8000 }); const port = randomPort();
const listener = Deno.listen({ port });
const nextWhileClosing = listener[Symbol.asyncIterator]().next(); const nextWhileClosing = listener[Symbol.asyncIterator]().next();
listener.close(); listener.close();
assertEquals(await nextWhileClosing, { value: undefined, done: true }); assertEquals(await nextWhileClosing, { value: undefined, done: true });
@ -153,7 +162,8 @@ unitTest(
unitTest( unitTest(
{ ignore: Deno.build.os === "win", perms: { net: true } }, { ignore: Deno.build.os === "win", perms: { net: true } },
async function netUdpListenCloseWhileIterating(): Promise<void> { async function netUdpListenCloseWhileIterating(): Promise<void> {
const socket = Deno.listen({ port: 8000, transport: "udp" }); const port = randomPort();
const socket = Deno.listen({ port, transport: "udp" });
const nextWhileClosing = socket[Symbol.asyncIterator]().next(); const nextWhileClosing = socket[Symbol.asyncIterator]().next();
socket.close(); socket.close();
assertEquals(await nextWhileClosing, { value: undefined, done: true }); assertEquals(await nextWhileClosing, { value: undefined, done: true });
@ -170,7 +180,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netListenAsyncIterator(): Promise<void> { async function netListenAsyncIterator(): Promise<void> {
const addr = { hostname: "127.0.0.1", port: 4500 }; const port = randomPort();
const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const runAsyncIterator = async (): Promise<void> => { const runAsyncIterator = async (): Promise<void> => {
for await (const conn of listener) { for await (const conn of listener) {
@ -205,7 +216,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netCloseReadSuccess() { async function netCloseReadSuccess() {
const addr = { hostname: "127.0.0.1", port: 4500 }; const port = randomPort();
const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const closeDeferred = createResolvable(); const closeDeferred = createResolvable();
const closeReadDeferred = createResolvable(); const closeReadDeferred = createResolvable();
@ -242,7 +254,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netDoubleCloseRead() { async function netDoubleCloseRead() {
const addr = { hostname: "127.0.0.1", port: 4500 }; const port = randomPort();
const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const closeDeferred = createResolvable(); const closeDeferred = createResolvable();
listener.accept().then(async conn => { listener.accept().then(async conn => {
@ -274,7 +287,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netCloseWriteSuccess() { async function netCloseWriteSuccess() {
const addr = { hostname: "127.0.0.1", port: 4500 }; const port = randomPort();
const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const closeDeferred = createResolvable(); const closeDeferred = createResolvable();
listener.accept().then(async conn => { listener.accept().then(async conn => {
@ -313,7 +327,8 @@ unitTest(
perms: { net: true } perms: { net: true }
}, },
async function netDoubleCloseWrite() { async function netDoubleCloseWrite() {
const addr = { hostname: "127.0.0.1", port: 4500 }; const port = randomPort();
const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const closeDeferred = createResolvable(); const closeDeferred = createResolvable();
listener.accept().then(async conn => { listener.accept().then(async conn => {
@ -365,8 +380,8 @@ unitTest(
resolvable.resolve(); resolvable.resolve();
} }
const port = randomPort();
const addr = { hostname: "127.0.0.1", port: 4500 }; const addr = { hostname: "127.0.0.1", port };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
iteratorReq(listener); iteratorReq(listener);
const conn = await Deno.connect(addr); const conn = await Deno.connect(addr);

View file

@ -359,3 +359,21 @@ unitTest(
}); });
} }
); );
function* portIterator(): IterableIterator<number> {
// use 49152 ~ 55000 for js/cli (rest are for std)
let i = 49152;
while (true) {
yield i;
i++;
if (i > 55000) {
i = 55000;
}
}
}
const it = portIterator();
/** Obtain (maybe) safe port number for net tests */
export function randomPort(): number {
const { value } = it.next();
assert(value != null);
return value;
}

View file

@ -2,6 +2,7 @@
import { import {
assert, assert,
assertEquals, assertEquals,
randomPort,
createResolvable, createResolvable,
unitTest unitTest
} from "./test_util.ts"; } from "./test_util.ts";
@ -43,7 +44,7 @@ unitTest(
let err; let err;
const options = { const options = {
hostname: "localhost", hostname: "localhost",
port: 4500, port: randomPort(),
certFile: "cli/tests/tls/localhost.crt", certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key" keyFile: "cli/tests/tls/localhost.key"
}; };
@ -72,10 +73,11 @@ unitTest(
unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void { unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void {
let err; let err;
const port = randomPort();
try { try {
Deno.listenTLS({ Deno.listenTLS({
hostname: "localhost", hostname: "localhost",
port: 4500, port,
certFile: "cli/tests/tls/localhost.crt", certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key" keyFile: "cli/tests/tls/localhost.key"
}); });
@ -94,7 +96,7 @@ unitTest(
let err; let err;
const options = { const options = {
hostname: "localhost", hostname: "localhost",
port: 4500, port: randomPort(),
certFile: "cli/tests/tls/localhost.crt", certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key" keyFile: "cli/tests/tls/localhost.key"
}; };
@ -123,7 +125,7 @@ unitTest(
let err; let err;
const options = { const options = {
hostname: "localhost", hostname: "localhost",
port: 4500, port: randomPort(),
certFile: "cli/tests/tls/localhost.crt", certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key" keyFile: "cli/tests/tls/localhost.key"
}; };
@ -151,7 +153,7 @@ unitTest(
async function dialAndListenTLS(): Promise<void> { async function dialAndListenTLS(): Promise<void> {
const resolvable = createResolvable(); const resolvable = createResolvable();
const hostname = "localhost"; const hostname = "localhost";
const port = 4500; const port = randomPort();
const listener = Deno.listenTLS({ const listener = Deno.listenTLS({
hostname, hostname,

View file

@ -29,7 +29,9 @@ async function wsHandler(ws: WebSocket): Promise<void> {
} }
} }
listenAndServe({ port: 8080 }, async req => { const addr = Deno.args[0] ?? "127.0.0.1:8080";
listenAndServe(addr, async req => {
if (req.method === "GET" && req.url === "/") { if (req.method === "GET" && req.url === "/") {
//Serve with hack //Serve with hack
const u = new URL("./index.html", import.meta.url); const u = new URL("./index.html", import.meta.url);
@ -75,4 +77,4 @@ listenAndServe({ port: 8080 }, async req => {
} }
} }
}); });
console.log("chat server starting on :8080...."); console.log(`chat server starting on ${addr}....`);

View file

@ -3,13 +3,22 @@ import { assert, assertEquals } from "../../testing/asserts.ts";
import { TextProtoReader } from "../../textproto/mod.ts"; import { TextProtoReader } from "../../textproto/mod.ts";
import { BufReader } from "../../io/bufio.ts"; import { BufReader } from "../../io/bufio.ts";
import { connectWebSocket, WebSocket } from "../../ws/mod.ts"; import { connectWebSocket, WebSocket } from "../../ws/mod.ts";
import { randomPort } from "../../http/test_util.ts";
import { delay } from "../../util/async.ts"; import { delay } from "../../util/async.ts";
const port = randomPort();
const { test, build } = Deno; const { test, build } = Deno;
async function startServer(): Promise<Deno.Process> { async function startServer(): Promise<Deno.Process> {
const server = Deno.run({ const server = Deno.run({
args: [Deno.execPath(), "--allow-net", "--allow-read", "server.ts"], args: [
Deno.execPath(),
"--allow-net",
"--allow-read",
"server.ts",
`127.0.0.1:${port}`
],
cwd: "examples/chat", cwd: "examples/chat",
stdout: "piped" stdout: "piped"
}); });
@ -35,7 +44,7 @@ test({
async fn() { async fn() {
const server = await startServer(); const server = await startServer();
try { try {
const resp = await fetch("http://127.0.0.1:8080/"); const resp = await fetch(`http://127.0.0.1:${port}/`);
assertEquals(resp.status, 200); assertEquals(resp.status, 200);
assertEquals(resp.headers.get("content-type"), "text/html"); assertEquals(resp.headers.get("content-type"), "text/html");
const html = await resp.body.text(); const html = await resp.body.text();
@ -55,7 +64,7 @@ test({
const server = await startServer(); const server = await startServer();
let ws: WebSocket | undefined; let ws: WebSocket | undefined;
try { try {
ws = await connectWebSocket("http://127.0.0.1:8080/ws"); ws = await connectWebSocket(`http://127.0.0.1:${port}/ws`);
const it = ws.receive(); const it = ws.receive();
assertEquals((await it.next()).value, "Connected: [1]"); assertEquals((await it.next()).value, "Connected: [1]");
ws.send("Hello"); ws.send("Hello");

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const hostname = "0.0.0.0"; const hostname = "0.0.0.0";
const port = 8080; const port = +(Deno.args[0] ?? "8080");
const listener = Deno.listen({ hostname, port }); const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`); console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) { for await (const conn of listener) {

View file

@ -1,14 +1,16 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { serve } from "../../http/server.ts"; import { serve } from "../../http/server.ts";
import { assertStrictEq } from "../../testing/asserts.ts"; import { assertStrictEq } from "../../testing/asserts.ts";
import { randomPort } from "../../http/test_util.ts";
const port = randomPort();
Deno.test({ Deno.test({
name: "[examples/curl] send a request to a specified url", name: "[examples/curl] send a request to a specified url",
// FIXME(bartlomieju): this test is leaking both resources and ops, // FIXME(bartlomieju): this test is leaking both resources and ops,
// and causes interference with other tests // and causes interference with other tests
ignore: true, ignore: true,
fn: async () => { fn: async () => {
const server = serve({ port: 8081 }); const server = serve({ port });
(async (): Promise<void> => { (async (): Promise<void> => {
for await (const req of server) { for await (const req of server) {
req.respond({ body: "Hello world" }); req.respond({ body: "Hello world" });
@ -21,7 +23,7 @@ Deno.test({
Deno.execPath(), Deno.execPath(),
"--allow-net", "--allow-net",
"curl.ts", "curl.ts",
"http://localhost:8081" "http://localhost:" + port
], ],
cwd: "examples", cwd: "examples",
stdout: "piped" stdout: "piped"

View file

@ -1,12 +1,14 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assertStrictEq, assertNotEquals } from "../../testing/asserts.ts"; import { assertStrictEq, assertNotEquals } from "../../testing/asserts.ts";
import { BufReader, ReadLineResult } from "../../io/bufio.ts"; import { BufReader, ReadLineResult } from "../../io/bufio.ts";
import { randomPort } from "../../http/test_util.ts";
const port = randomPort();
Deno.test("[examples/echo_server]", async () => { Deno.test("[examples/echo_server]", async () => {
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const decoder = new TextDecoder(); const decoder = new TextDecoder();
const process = Deno.run({ const process = Deno.run({
args: [Deno.execPath(), "--allow-net", "echo_server.ts"], args: [Deno.execPath(), "--allow-net", "echo_server.ts", `${port}`],
cwd: "examples", cwd: "examples",
stdout: "piped" stdout: "piped"
}); });
@ -19,10 +21,10 @@ Deno.test("[examples/echo_server]", async () => {
assertNotEquals(message, Deno.EOF); assertNotEquals(message, Deno.EOF);
assertStrictEq( assertStrictEq(
decoder.decode((message as ReadLineResult).line).trim(), decoder.decode((message as ReadLineResult).line).trim(),
"Listening on 0.0.0.0:8080" "Listening on 0.0.0.0:" + port
); );
conn = await Deno.connect({ hostname: "127.0.0.1", port: 8080 }); conn = await Deno.connect({ hostname: "127.0.0.1", port });
const connReader = new BufReader(conn); const connReader = new BufReader(conn);
await conn.write(encoder.encode("Hello echo_server\n")); await conn.write(encoder.encode("Hello echo_server\n"));

View file

@ -2,9 +2,11 @@
import { assert, assertEquals, assertStrContains } from "../testing/asserts.ts"; import { assert, assertEquals, assertStrContains } from "../testing/asserts.ts";
import { BufReader } from "../io/bufio.ts"; import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
import { randomPort } from "./test_util.ts";
const { test } = Deno; const { test } = Deno;
let fileServer: Deno.Process; let fileServer: Deno.Process;
const port = randomPort();
async function startFileServer(): Promise<void> { async function startFileServer(): Promise<void> {
fileServer = Deno.run({ fileServer = Deno.run({
args: [ args: [
@ -14,7 +16,9 @@ async function startFileServer(): Promise<void> {
"--allow-net", "--allow-net",
"http/file_server.ts", "http/file_server.ts",
".", ".",
"--cors" "--cors",
"--port",
`${port}`
], ],
stdout: "piped", stdout: "piped",
stderr: "null" stderr: "null"
@ -34,7 +38,7 @@ function killFileServer(): void {
test(async function serveFile(): Promise<void> { test(async function serveFile(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/README.md"); const res = await fetch(`http://localhost:${port}/README.md`);
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assert(res.headers.has("content-type")); assert(res.headers.has("content-type"));
@ -52,7 +56,7 @@ test(async function serveFile(): Promise<void> {
test(async function serveDirectory(): Promise<void> { test(async function serveDirectory(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/"); const res = await fetch(`http://localhost:${port}/`);
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
const page = await res.text(); const page = await res.text();
@ -74,7 +78,7 @@ test(async function serveDirectory(): Promise<void> {
test(async function serveFallback(): Promise<void> { test(async function serveFallback(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/badfile.txt"); const res = await fetch(`http://localhost:${port}/badfile.txt`);
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.status, 404); assertEquals(res.status, 404);
@ -87,12 +91,12 @@ test(async function serveFallback(): Promise<void> {
test(async function serveWithUnorthodoxFilename(): Promise<void> { test(async function serveWithUnorthodoxFilename(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
let res = await fetch("http://localhost:4500/http/testdata/%"); let res = await fetch(`http://localhost:${port}/http/testdata/%`);
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.status, 200); assertEquals(res.status, 200);
res.body.close(); res.body.close();
res = await fetch("http://localhost:4500/http/testdata/test%20file.txt"); res = await fetch(`http://localhost:${port}/http/testdata/test%20file.txt`);
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.status, 200); assertEquals(res.status, 200);
@ -103,8 +107,16 @@ test(async function serveWithUnorthodoxFilename(): Promise<void> {
}); });
test(async function servePermissionDenied(): Promise<void> { test(async function servePermissionDenied(): Promise<void> {
const _port = randomPort();
const deniedServer = Deno.run({ const deniedServer = Deno.run({
args: [Deno.execPath(), "run", "--allow-net", "http/file_server.ts"], args: [
Deno.execPath(),
"run",
"--allow-net",
"http/file_server.ts",
"-p",
`${_port}`
],
stdout: "piped", stdout: "piped",
stderr: "piped" stderr: "piped"
}); });
@ -116,7 +128,7 @@ test(async function servePermissionDenied(): Promise<void> {
assert(s !== Deno.EOF && s.includes("server listening")); assert(s !== Deno.EOF && s.includes("server listening"));
try { try {
const res = await fetch("http://localhost:4500/"); const res = await fetch(`http://localhost:${_port}/`);
res.body.close(); res.body.close();
assertStrContains( assertStrContains(
(await errReader.readLine()) as string, (await errReader.readLine()) as string,

View file

@ -1,7 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { serve } from "./server.ts"; import { serve } from "./server.ts";
import { randomPort } from "./test_util.ts";
const addr = Deno.args[0] || "127.0.0.1:4500"; const addr = Deno.args[0] || "127.0.0.1:" + randomPort();
const server = serve(addr); const server = serve(addr);
const body = new TextEncoder().encode("Hello World"); const body = new TextEncoder().encode("Hello World");

View file

@ -2,7 +2,7 @@
import { serve, ServerRequest } from "./server.ts"; import { serve, ServerRequest } from "./server.ts";
import { delay } from "../util/async.ts"; import { delay } from "../util/async.ts";
const addr = Deno.args[1] || "127.0.0.1:4501"; const addr = Deno.args[0] || "127.0.0.1:4501";
const server = serve(addr); const server = serve(addr);
function body(i: number): string { function body(i: number): string {

View file

@ -1,12 +1,20 @@
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import { BufReader, BufWriter } from "../io/bufio.ts"; import { BufReader, BufWriter } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
import { randomPort } from "./test_util.ts";
const port = randomPort();
const { connect, run, test } = Deno; const { connect, run, test } = Deno;
let server: Deno.Process; let server: Deno.Process;
async function startServer(): Promise<void> { async function startServer(): Promise<void> {
server = run({ server = run({
args: [Deno.execPath(), "run", "-A", "http/racing_server.ts"], args: [
Deno.execPath(),
"run",
"-A",
"http/racing_server.ts",
"127.0.0.1:" + port
],
stdout: "piped" stdout: "piped"
}); });
// Once racing server is ready it will write to its stdout. // Once racing server is ready it will write to its stdout.
@ -61,7 +69,7 @@ Step7
test(async function serverPipelineRace(): Promise<void> { test(async function serverPipelineRace(): Promise<void> {
await startServer(); await startServer();
const conn = await connect({ port: 4501 }); const conn = await connect({ port });
const r = new TextProtoReader(new BufReader(conn)); const r = new TextProtoReader(new BufReader(conn));
const w = new BufWriter(conn); const w = new BufWriter(conn);
await w.write(new TextEncoder().encode(input)); await w.write(new TextEncoder().encode(input));

View file

@ -18,6 +18,7 @@ import { BufReader, BufWriter } from "../io/bufio.ts";
import { delay } from "../util/async.ts"; import { delay } from "../util/async.ts";
import { encode, decode } from "../strings/mod.ts"; import { encode, decode } from "../strings/mod.ts";
import { mockConn } from "./mock.ts"; import { mockConn } from "./mock.ts";
import { randomPort } from "./test_util.ts";
const { Buffer, test } = Deno; const { Buffer, test } = Deno;
@ -355,8 +356,14 @@ test({
ignore: true, ignore: true,
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
// Runs a simple server as another process // Runs a simple server as another process
const port = randomPort();
const p = Deno.run({ const p = Deno.run({
args: [Deno.execPath(), "--allow-net", "http/testdata/simple_server.ts"], args: [
Deno.execPath(),
"--allow-net",
"http/testdata/simple_server.ts",
`${port}`
],
stdout: "piped" stdout: "piped"
}); });
@ -395,13 +402,15 @@ test({
// FIXME(bartlomieju): hangs on windows, cause can't do `Deno.kill` // FIXME(bartlomieju): hangs on windows, cause can't do `Deno.kill`
ignore: true, ignore: true,
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
const port = randomPort();
// Runs a simple server as another process // Runs a simple server as another process
const p = Deno.run({ const p = Deno.run({
args: [ args: [
Deno.execPath(), Deno.execPath(),
"--allow-net", "--allow-net",
"--allow-read", "--allow-read",
"http/testdata/simple_https_server.ts" "http/testdata/simple_https_server.ts",
`${port}`
], ],
stdout: "piped" stdout: "piped"
}); });
@ -413,7 +422,6 @@ test({
serverIsRunning = false; serverIsRunning = false;
}) })
.catch((_): void => {}); // Ignores the error when closing the process. .catch((_): void => {}); // Ignores the error when closing the process.
try { try {
const r = new TextProtoReader(new BufReader(p.stdout!)); const r = new TextProtoReader(new BufReader(p.stdout!));
const s = await r.readLine(); const s = await r.readLine();
@ -424,7 +432,7 @@ test({
// Requests to the server and immediately closes the connection // Requests to the server and immediately closes the connection
const conn = await Deno.connectTLS({ const conn = await Deno.connectTLS({
hostname: "localhost", hostname: "localhost",
port: 4503, port,
certFile: "http/testdata/tls/RootCA.pem" certFile: "http/testdata/tls/RootCA.pem"
}); });
await Deno.writeAll( await Deno.writeAll(
@ -448,7 +456,7 @@ test({
}); });
test("close server while iterating", async (): Promise<void> => { test("close server while iterating", async (): Promise<void> => {
const server = serve(":8123"); const server = serve({ port: randomPort() });
const nextWhileClosing = server[Symbol.asyncIterator]().next(); const nextWhileClosing = server[Symbol.asyncIterator]().next();
server.close(); server.close();
assertEquals(await nextWhileClosing, { value: undefined, done: true }); assertEquals(await nextWhileClosing, { value: undefined, done: true });
@ -491,8 +499,9 @@ test({
test({ test({
name: "respond error closes connection", name: "respond error closes connection",
async fn(): Promise<void> { async fn(): Promise<void> {
const port = randomPort();
const serverRoutine = async (): Promise<void> => { const serverRoutine = async (): Promise<void> => {
const server = serve(":8124"); const server = serve(":" + port);
// @ts-ignore // @ts-ignore
for await (const req of server) { for await (const req of server) {
await assertThrowsAsync(async () => { await assertThrowsAsync(async () => {
@ -509,7 +518,7 @@ test({
const p = serverRoutine(); const p = serverRoutine();
const conn = await Deno.connect({ const conn = await Deno.connect({
hostname: "127.0.0.1", hostname: "127.0.0.1",
port: 8124 port
}); });
await Deno.writeAll( await Deno.writeAll(
conn, conn,

20
std/http/test_util.ts Normal file
View file

@ -0,0 +1,20 @@
import { assert } from "../testing/asserts.ts";
function* portIterator(): IterableIterator<number> {
// use 55001 ~ 65535 (rest (49152~55000) are for cli/js)
let i = 55001;
while (true) {
yield i;
i++;
if (i > 65535) {
i = 55001;
}
}
}
const it = portIterator();
/** Obtain (maybe) safe port number for net tests */
export function randomPort(): number {
const { value } = it.next();
assert(value != null);
return value;
}

View file

@ -2,9 +2,10 @@
// This is an example of a https server // This is an example of a https server
import { serveTLS } from "../server.ts"; import { serveTLS } from "../server.ts";
const port = parseInt(Deno.args[0] || "4503");
const tlsOptions = { const tlsOptions = {
hostname: "localhost", hostname: "localhost",
port: 4503, port,
certFile: "./http/testdata/tls/localhost.crt", certFile: "./http/testdata/tls/localhost.crt",
keyFile: "./http/testdata/tls/localhost.key" keyFile: "./http/testdata/tls/localhost.key"
}; };

View file

@ -2,8 +2,9 @@
// This is an example of a server that responds with an empty body // This is an example of a server that responds with an empty body
import { serve } from "../server.ts"; import { serve } from "../server.ts";
const addr = "0.0.0.0:4502"; const port = parseInt(Deno.args[0] || "4502");
console.log(`Simple server listening on ${addr}`); const addr: Deno.ListenOptions = { port };
console.log(`Simple server listening on ${port}`);
for await (const req of serve(addr)) { for await (const req of serve(addr)) {
req.respond({}); req.respond({});
} }