Skip to main content
Module

std/http/file_server_test.ts

Deno standard library
Go to Latest
File
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.import { assert, assertEquals, assertStringIncludes,} from "../testing/asserts.ts";import { BufReader } from "../io/buffer.ts";import { iterateReader, readAll, writeAll } from "../streams/conversion.ts";import { TextProtoReader } from "../textproto/mod.ts";import { serveDir, serveFile } from "./file_server.ts";import { dirname, fromFileUrl, join, resolve } from "../path/mod.ts";import { isWindows } from "../_util/os.ts";
let fileServer: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
interface FileServerCfg { port?: string; cors?: boolean; "dir-listing"?: boolean; dotfiles?: boolean; host?: string; cert?: string; key?: string; help?: boolean; target?: string;}
const moduleDir = dirname(fromFileUrl(import.meta.url));const testdataDir = resolve(moduleDir, "testdata");
async function startFileServer({ target = ".", port = "4507", "dir-listing": dirListing = true, dotfiles = true,}: FileServerCfg = {}) { fileServer = Deno.run({ cmd: [ Deno.execPath(), "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "file_server.ts", target, "--cors", "-p", `${port}`, `${dirListing ? "" : "--no-dir-listing"}`, `${dotfiles ? "" : "--no-dotfiles"}`, ], cwd: moduleDir, stdout: "piped", stderr: "null", }); // Once fileServer is ready it will write to its stdout. assert(fileServer.stdout != null); const r = new TextProtoReader(new BufReader(fileServer.stdout)); const s = await r.readLine(); assert(s !== null && s.includes("server listening"));}
async function startFileServerAsLibrary({}: FileServerCfg = {}) { fileServer = Deno.run({ cmd: [ Deno.execPath(), "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "testdata/file_server_as_library.ts", ], cwd: moduleDir, stdout: "piped", stderr: "null", }); assert(fileServer.stdout != null); const r = new TextProtoReader(new BufReader(fileServer.stdout)); const s = await r.readLine(); assert(s !== null && s.includes("Server running..."));}
async function killFileServer() { fileServer.close(); // Process.close() kills the file server process. However this termination // happens asynchronously, and since we've just closed the process resource, // we can't use `await fileServer.status()` to wait for the process to have // exited. As a workaround, wait for its stdout to close instead. // TODO(piscisaureus): when `Process.kill()` is stable and works on Windows, // switch to calling `kill()` followed by `await fileServer.status()`. await readAll(fileServer.stdout!); fileServer.stdout!.close();}
/* HTTP GET request allowing arbitrary paths */async function fetchExactPath( hostname: string, port: number, path: string,): Promise<Response> { const encoder = new TextEncoder(); const decoder = new TextDecoder(); const request = encoder.encode("GET " + path + " HTTP/1.1\r\n\r\n"); let conn: void | Deno.Conn; try { conn = await Deno.connect( { hostname: hostname, port: port, transport: "tcp" }, ); await writeAll(conn, request); let currentResult = ""; let contentLength = -1; let startOfBody = -1; for await (const chunk of iterateReader(conn)) { currentResult += decoder.decode(chunk); if (contentLength === -1) { const match = /^content-length: (.*)$/m.exec(currentResult); if (match && match[1]) { contentLength = Number(match[1]); } } if (startOfBody === -1) { const ind = currentResult.indexOf("\r\n\r\n"); if (ind !== -1) { startOfBody = ind + 4; } } if (startOfBody !== -1 && contentLength !== -1) { const byteLen = encoder.encode(currentResult).length; if (byteLen >= contentLength + startOfBody) { break; } } } const status = /^HTTP\/1.1 (...)/.exec(currentResult); let statusCode = 0; if (status && status[1]) { statusCode = Number(status[1]); }
const body = currentResult.slice(startOfBody); const headersStr = currentResult.slice(0, startOfBody); const headersReg = /^(.*): (.*)$/mg; const headersObj: { [i: string]: string } = {}; let match = headersReg.exec(headersStr); while (match !== null) { if (match[1] && match[2]) { headersObj[match[1]] = match[2]; } match = headersReg.exec(headersStr); } return new Response(body, { status: statusCode, headers: new Headers(headersObj), }); } finally { if (conn) { Deno.close(conn.rid); } }}
Deno.test( "file_server serveFile", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/README.md"); assertEquals(res.headers.get("content-type"), "text/markdown"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( await Deno.readFile(join(moduleDir, "README.md")), ); assertEquals(downloadedFile, localFile); } finally { await killFileServer(); } },);
Deno.test( "file_server serveFile in testdata", async () => { await startFileServer({ target: "./testdata" }); try { const res = await fetch("http://localhost:4507/hello.html"); assertEquals(res.headers.get("content-type"), "text/html"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( await Deno.readFile(join(testdataDir, "hello.html")), ); assertEquals(downloadedFile, localFile); } finally { await killFileServer(); } },);
Deno.test("serveDirIndex", async function () { await startFileServer(); try { const res = await fetch("http://localhost:4507/"); const page = await res.text(); assert(page.includes("README.md")); assert(page.includes(`<a href="/testdata/">testdata/</a>`));
// `Deno.FileInfo` is not completely compatible with Windows yet // TODO(bartlomieju): `mode` should work correctly in the future. // Correct this test case accordingly. isWindows === false && assert(/<td class="mode">(\s)*[a-zA-Z- ]{14}(\s)*<\/td>/.test(page)); isWindows && assert(/<td class="mode">(\s)*\(unknown mode\)(\s)*<\/td>/.test(page)); assert(page.includes(`<a href="/README.md">README.md</a>`)); } finally { await killFileServer(); }});Deno.test("serveDirIndex with filename including percent symbol", async function () { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/"); const page = await res.text(); assertStringIncludes(page, "%2525A.txt"); } finally { await killFileServer(); }});
Deno.test("serveFallback", async function () { await startFileServer(); try { const res = await fetch("http://localhost:4507/badfile.txt"); assertEquals(res.status, 404); const _ = await res.text(); } finally { await killFileServer(); }});
Deno.test("checkPathTraversal", async function () { await startFileServer(); try { const res = await fetch( "http://localhost:4507/../../../../../../../..", );
assertEquals(res.status, 200); const listing = await res.text(); assertStringIncludes(listing, "README.md"); } finally { await killFileServer(); }});
Deno.test("checkPathTraversalNoLeadingSlash", async function () { await startFileServer(); try { const res = await fetchExactPath("127.0.0.1", 4507, "../../../.."); assertEquals(res.status, 400); } finally { await killFileServer(); }});
Deno.test("checkPathTraversalAbsoluteURI", async function () { await startFileServer(); try { //allowed per https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html const res = await fetchExactPath( "127.0.0.1", 4507, "http://localhost/../../../..", ); assertEquals(res.status, 200); assertStringIncludes(await res.text(), "README.md"); } finally { await killFileServer(); }});
Deno.test("checkURIEncodedPathTraversal", async function () { await startFileServer(); try { const res = await fetch( "http://localhost:4507/%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..", );
assertEquals(res.status, 404); const _ = await res.text(); } finally { await killFileServer(); }});
Deno.test("serveWithUnorthodoxFilename", async function () { await startFileServer(); try { let res = await fetch("http://localhost:4507/testdata/%"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); assertEquals(res.status, 200); const _ = await res.text(); res = await fetch("http://localhost:4507/testdata/test%20file.txt"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); assertEquals(res.status, 200); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test("CORS support", async function () { await startFileServer(); try { const directoryRes = await fetch("http://localhost:4507/"); assert(directoryRes.headers.has("access-control-allow-origin")); assert(directoryRes.headers.has("access-control-allow-headers")); assertEquals(directoryRes.status, 200); await directoryRes.text(); // Consuming the body so that the test doesn't leak resources
const fileRes = await fetch("http://localhost:4507/testdata/hello.html"); assert(fileRes.headers.has("access-control-allow-origin")); assert(fileRes.headers.has("access-control-allow-headers")); assertEquals(fileRes.status, 200); await fileRes.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test("printHelp", async function () { const helpProcess = Deno.run({ cmd: [ Deno.execPath(), "run", "--no-check", "--quiet", "file_server.ts", "--help", ], cwd: moduleDir, stdout: "piped", }); assert(helpProcess.stdout != null); const r = new TextProtoReader(new BufReader(helpProcess.stdout)); const s = await r.readLine(); assert(s !== null && s.includes("Deno File Server")); helpProcess.close(); helpProcess.stdout.close();});
Deno.test("contentType", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/hello.html"); const contentType = res.headers.get("content-type"); assertEquals(contentType, "text/html"); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test("file_server running as library", async function () { await startFileServerAsLibrary(); try { const res = await fetch("http://localhost:8000"); assertEquals(res.status, 200); const _ = await res.text(); } finally { await killFileServer(); }});
Deno.test("file_server should ignore query params", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/README.md?key=value"); assertEquals(res.status, 200); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( await Deno.readFile(join(moduleDir, "README.md")), ); assertEquals(downloadedFile, localFile); } finally { await killFileServer(); }});
async function startTlsFileServer({ target = ".", port = "4577",}: FileServerCfg = {}) { fileServer = Deno.run({ cmd: [ Deno.execPath(), "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "file_server.ts", target, "--host", "localhost", "--cert", "./testdata/tls/localhost.crt", "--key", "./testdata/tls/localhost.key", "--cors", "-p", `${port}`, ], cwd: moduleDir, stdout: "piped", stderr: "null", }); // Once fileServer is ready it will write to its stdout. assert(fileServer.stdout != null); const r = new TextProtoReader(new BufReader(fileServer.stdout)); const s = await r.readLine(); assert(s !== null && s.includes("server listening"));}
Deno.test("serveDirIndex TLS", async function () { await startTlsFileServer(); try { // Valid request after invalid const conn = await Deno.connectTls({ hostname: "localhost", port: 4577, certFile: join(testdataDir, "tls/RootCA.pem"), });
await writeAll( conn, new TextEncoder().encode("GET / HTTP/1.0\r\n\r\n"), ); const res = new Uint8Array(128 * 1024); const nread = await conn.read(res); assert(nread !== null); conn.close(); const page = new TextDecoder().decode(res.subarray(0, nread)); assert(page.includes("<title>Deno File Server</title>")); } finally { await killFileServer(); }});
Deno.test("partial TLS arguments fail", async function () { fileServer = Deno.run({ cmd: [ Deno.execPath(), "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "file_server.ts", ".", "--host", "localhost", "--cert", "./testdata/tls/localhost.crt", "-p", `4578`, ], cwd: moduleDir, stdout: "piped", stderr: "null", }); try { // Once fileServer is ready it will write to its stdout. assert(fileServer.stdout != null); const r = new TextProtoReader(new BufReader(fileServer.stdout)); const s = await r.readLine(); assert( s !== null && s.includes("--key and --cert are required for TLS"), ); } finally { await killFileServer(); }});
Deno.test("file_server disable dir listings", async function () { await startFileServer({ "dir-listing": false }); try { const res = await fetch("http://localhost:4507/");
assertEquals(res.status, 404); const _ = await res.text(); } finally { await killFileServer(); }});
Deno.test("file_server do not show dotfiles", async function () { await startFileServer({ dotfiles: false }); try { let res = await fetch("http://localhost:4507/testdata/"); assert(!(await res.text()).includes(".dotfile"));
res = await fetch("http://localhost:4507/testdata/.dotfile"); assertEquals(await res.text(), "dotfile"); } finally { await killFileServer(); }});
Deno.test("file_server should show .. if it makes sense", async function (): Promise< void> { await startFileServer(); try { let res = await fetch("http://localhost:4507/"); let page = await res.text(); assert(!page.includes("../")); assert(page.includes("testdata/"));
res = await fetch("http://localhost:4507/testdata/"); page = await res.text(); assert(page.includes("../")); } finally { await killFileServer(); }});
Deno.test( "file_server should download first byte of hello.html file", async () => { await startFileServer(); try { const headers = { "range": "bytes=0-0", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); const text = await res.text(); console.log(text); assertEquals(text, "L"); } finally { await killFileServer(); } },);
Deno.test( "file_server sets `content-range` header for range request responses", async () => { await startFileServer(); try { const headers = { "range": "bytes=0-100", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); const contentLength = await getTestFileSize(); assertEquals( res.headers.get("content-range"), `bytes 0-100/${contentLength}`, );
await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
const getTestFileSize = async () => { const fileInfo = await getTestFileStat(); return fileInfo.size;};
const getTestFileStat = async (): Promise<Deno.FileInfo> => { const fsPath = join(testdataDir, "test file.txt"); const fileInfo = await Deno.stat(fsPath);
return fileInfo;};
const getTestFileEtag = async () => { const fileInfo = await getTestFileStat();
if (fileInfo.mtime instanceof Date) { const lastModified = new Date(fileInfo.mtime); const simpleEtag = await createEtagHash( `${lastModified.toJSON()}${fileInfo.size}`, ); return simpleEtag; } else { return ""; }};
const getTestFileLastModified = async () => { const fileInfo = await getTestFileStat();
if (fileInfo.mtime instanceof Date) { return new Date(fileInfo.mtime).toUTCString(); } else { return ""; }};
const createEtagHash = async (message: string) => { // see: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest const hashType = "SHA-1"; // Faster, and this isn't a security sensitive cryptographic use case const msgUint8 = new TextEncoder().encode(message); const hashBuffer = await crypto.subtle.digest(hashType, msgUint8); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join( "", ); return hashHex;};
Deno.test( "file_server returns 206 for range request responses", async () => { await startFileServer(); try { const headers = { "range": "bytes=0-100", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); await res.text(); // Consuming the body so that the test doesn't leak resources assertEquals(res.status, 206); } finally { await killFileServer(); } },);
Deno.test( "file_server should download from 300 bytes into `hello.html` file until the end", async () => { await startFileServer(); try { const headers = { "range": "bytes=300-", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); const text = await res.text();
const localFile = new TextDecoder().decode( await Deno.readFile(join(testdataDir, "test file.txt")), );
const contentLength = await getTestFileSize(); assertEquals( res.headers.get("content-range"), `bytes 300-${contentLength - 1}/${contentLength}`, ); assertEquals(text, localFile.substring(300)); } finally { await killFileServer(); } },);
Deno.test( "file_server should return 416 due to a bad range request (500-200)", async () => { await startFileServer(); try { const headers = { "range": "bytes=500-200", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); await res.text(); assertEquals(res.status, 416); assertEquals(res.statusText, "Range Not Satisfiable"); } finally { await killFileServer(); } },);
Deno.test( "file_server should return 416 due to a bad range request (-200)", async () => { await startFileServer(); try { const headers = { "range": "bytes=-200", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); await res.text(); assertEquals(res.status, 416); assertEquals(res.statusText, "Range Not Satisfiable"); } finally { await killFileServer(); } },);
Deno.test( "file_server should return 416 due to a bad range request (100)", async () => { await startFileServer(); try { const headers = { "range": "bytes=100", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); await res.text(); assertEquals(res.status, 416); assertEquals(res.statusText, "Range Not Satisfiable"); } finally { await killFileServer(); } },);
Deno.test( "file_server should return 416 due to a bad range request (a-b)", async () => { await startFileServer(); try { const headers = { "range": "bytes=a-b", }; const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); await res.text(); assertEquals(res.status, 416); assertEquals(res.statusText, "Range Not Satisfiable"); } finally { await killFileServer(); } },);
Deno.test( "file_server returns correct mime-types", async () => { await startFileServer(); try { const txtRes = await fetch( "http://localhost:4507/testdata/test%20file.txt", ); assertEquals(txtRes.headers.get("content-type"), "text/plain"); await txtRes.text(); // Consuming the body so that the test doesn't leak resources
const htmlRes = await fetch("http://localhost:4507/testdata/hello.html"); assertEquals(htmlRes.headers.get("content-type"), "text/html"); await htmlRes.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server sets `accept-ranges` header to `bytes` for directory listings", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/"); assertEquals(res.headers.get("accept-ranges"), "bytes"); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server sets `accept-ranges` header to `bytes` for file responses", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/test%20file.txt"); assertEquals(res.headers.get("accept-ranges"), "bytes"); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test("file_server sets `content-length` header correctly", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/test%20file.txt"); const contentLength = await getTestFileSize(); assertEquals(res.headers.get("content-length"), contentLength.toString()); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test("file_server sets `Last-Modified` header correctly", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/test%20file.txt");
const lastModifiedHeader = res.headers.get("last-modified") as string; const lastModifiedTime = Date.parse(lastModifiedHeader);
const fileInfo = await getTestFileStat(); const expectedTime = fileInfo.mtime && fileInfo.mtime instanceof Date ? fileInfo.mtime.getTime() : Number.NaN;
const round = (d: number) => Math.floor(d / 1000 / 60 / 30); // Rounds epochs to 2 minute units, to accommodate minor variances in how long the test(s) take to execute assertEquals(round(lastModifiedTime), round(expectedTime)); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test("file_server sets `Date` header correctly", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/test%20file.txt"); const dateHeader = res.headers.get("date") as string; const date = Date.parse(dateHeader); const fileInfo = await getTestFileStat(); const expectedTime = fileInfo.atime && fileInfo.atime instanceof Date ? fileInfo.atime.getTime() : Number.NaN; const round = (d: number) => Math.floor(d / 1000 / 60 / 30); // Rounds epochs to 2 minute units, to accommodate minor variances in how long the test(s) take to execute assertEquals(round(date), round(expectedTime)); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); }});
Deno.test( "file_server file responses includes correct etag", async () => { await startFileServer(); try { const res = await fetch("http://localhost:4507/testdata/test%20file.txt"); const expectedEtag = await getTestFileEtag(); assertEquals(res.headers.get("etag"), expectedEtag); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server returns 304 for requests with if-none-match set with the etag", async () => { await startFileServer(); try { const expectedEtag = await getTestFileEtag(); const headers = new Headers(); headers.set("if-none-match", expectedEtag); const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); assertEquals(res.status, 304); assertEquals(res.statusText, "Not Modified"); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server returns an empty body for 304 responses from requests with if-none-match set with the etag", async () => { await startFileServer(); try { const expectedEtag = await getTestFileEtag(); const headers = new Headers(); headers.set("if-none-match", expectedEtag); const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); assertEquals(await res.text(), ""); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server returns 304 for requests with if-modified-since if the requested resource has not been modified after the given date", async () => { await startFileServer(); try { const expectedIfModifiedSince = await getTestFileLastModified(); const headers = new Headers(); headers.set("if-modified-since", expectedIfModifiedSince); const res = await fetch( "http://localhost:4507/testdata/test%20file.txt", { headers }, ); assertEquals(res.status, 304); assertEquals(res.statusText, "Not Modified"); await res.text(); // Consuming the body so that the test doesn't leak resources } finally { await killFileServer(); } },);
Deno.test( "file_server `serveFile` serve test file", async () => { const req = new Request("http://localhost:4507/testdata/test file.txt"); const testdataPath = join(testdataDir, "test file.txt"); const res = await serveFile(req, testdataPath); const localFile = new TextDecoder().decode( await Deno.readFile(testdataPath), ); assertEquals(res.status, 200); assertEquals(await res.text(), localFile); },);Deno.test( "file_server `serveFile` should return 416 due to a bad range request (500-200)", async () => { const req = new Request("http://localhost:4507/testdata/test file.txt"); req.headers.set("range", "bytes=500-200"); const testdataPath = join(testdataDir, "test file.txt"); const res = await serveFile(req, testdataPath); assertEquals(res.status, 416); },);Deno.test( "file_server `serveFile` returns 304 for requests with if-modified-since if the requested resource has not been modified after the given date", async () => { const req = new Request("http://localhost:4507/testdata/test file.txt"); const expectedEtag = await getTestFileEtag(); req.headers.set("if-none-match", expectedEtag); const testdataPath = join(testdataDir, "test file.txt"); const res = await serveFile(req, testdataPath); assertEquals(res.status, 304); assertEquals(res.statusText, "Not Modified"); },);
Deno.test( "serveDir (without options) serves files under the current dir", async () => { const req = new Request("http://localhost:4507/http/testdata/hello.html"); const res = await serveDir(req); assertEquals(res.status, 200); assertStringIncludes(await res.text(), "Hello World"); },);
Deno.test( "serveDir (with fsRoot option) serves files under the given dir", async () => { const req = new Request("http://localhost:4507/testdata/hello.html"); const res = await serveDir(req, { fsRoot: "http" }); assertEquals(res.status, 200); assertStringIncludes(await res.text(), "Hello World"); },);
Deno.test( "serveDir (with fsRoot, urlRoot option) serves files under the given dir", async () => { const req = new Request( "http://localhost:4507/my-static-root/testdata/hello.html", ); const res = await serveDir(req, { fsRoot: "http", urlRoot: "my-static-root", }); assertEquals(res.status, 200); assertStringIncludes(await res.text(), "Hello World"); },);