Skip to main content
Module

std/http/file_server_test.ts

Deno standard library
Go to Latest
File
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.import { assert, assertEquals, assertStringIncludes,} from "../testing/asserts.ts";import { iterateReader, writeAll } from "../streams/conversion.ts";import { serveDir, serveFile } from "./file_server.ts";import { dirname, fromFileUrl, join, resolve } from "../path/mod.ts";import { isWindows } from "../_util/os.ts";import { TextLineStream } from "../streams/delimiter.ts";
let fileServer: Deno.Child;
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.spawnChild(Deno.execPath(), { args: [ "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "file_server.ts", target, "--cors", "-p", `${port}`, `${dirListing ? "" : "--no-dir-listing"}`, `${dotfiles ? "" : "--no-dotfiles"}`, ], cwd: moduleDir, stderr: "null", }); // Once fileServer is ready it will write to its stdout. const r = fileServer.stdout.pipeThrough(new TextDecoderStream()).pipeThrough( new TextLineStream(), ); const reader = r.getReader(); const res = await reader.read(); assert(!res.done && res.value.includes("Listening")); reader.releaseLock();}
async function startFileServerAsLibrary({}: FileServerCfg = {}) { fileServer = Deno.spawnChild(Deno.execPath(), { args: [ "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "testdata/file_server_as_library.ts", ], cwd: moduleDir, stderr: "null", }); const r = fileServer.stdout.pipeThrough(new TextDecoderStream()).pipeThrough( new TextLineStream(), ); const reader = r.getReader(); const res = await reader.read(); assert(!res.done && res.value.includes("Server running...")); reader.releaseLock();}
async function killFileServer() { fileServer.kill("SIGKILL"); await fileServer.status;}
/* 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; charset=UTF-8", ); 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; charset=UTF-8"); 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 = await Deno.spawn(Deno.execPath(), { args: [ "run", "--no-check", "--quiet", "file_server.ts", "--help", ], cwd: moduleDir, }); const stdout = new TextDecoder().decode(helpProcess.stdout); assert(stdout.includes("Deno File Server"));});
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; charset=UTF-8"); 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.spawnChild(Deno.execPath(), { args: [ "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, stderr: "null", }); // Once fileServer is ready it will write to its stdout. const r = fileServer.stdout.pipeThrough(new TextDecoderStream()).pipeThrough( new TextLineStream(), ); const reader = r.getReader(); const res = await reader.read(); assert(!res.done && res.value.includes("Listening")); reader.releaseLock();}
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.spawnChild(Deno.execPath(), { args: [ "run", "--no-check", "--quiet", "--allow-read", "--allow-net", "file_server.ts", ".", "--host", "localhost", "--cert", "./testdata/tls/localhost.crt", "-p", `4578`, ], cwd: moduleDir, stderr: "null", }); try { // Once fileServer is ready it will write to its stdout. const r = fileServer.stdout.pipeThrough(new TextDecoderStream()) .pipeThrough(new TextLineStream()); const reader = r.getReader(); const res = await reader.read(); assert( !res.done && res.value.includes("--key and --cert are required for TLS"), ); reader.releaseLock(); } 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 ""; }};
function createEtagHash(buf: string): string { let hash = 2166136261; // 32-bit FNV offset basis for (let i = 0; i < buf.length; i++) { hash ^= buf.charCodeAt(i); // Equivalent to `hash *= 16777619` without using BigInt // 32-bit FNV prime hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); } // 32-bit hex string return (hash >>> 0).toString(16);}
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; charset=UTF-8", ); 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; charset=UTF-8", ); 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 `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"), `W/${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` returns 404 due to file not found", async () => { const req = new Request("http://localhost:4507/testdata/non_existent.txt"); const testdataPath = join(testdataDir, "non_existent.txt"); const res = await serveFile(req, testdataPath); assertEquals(res.status, 404); assertEquals(res.statusText, "Not Found"); },);
Deno.test( "file_server `serveFile` returns 404 when the given path is a directory", async () => { const req = new Request("http://localhost:4507/testdata/"); const res = await serveFile(req, testdataDir); assertEquals(res.status, 404); assertEquals(res.statusText, "Not Found"); },);
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"); },);
Deno.test( "file_server returns 304 for requests with if-none-match set with the etag but with W/ prefixed etag in request headers.", async () => { await startFileServer(); try { const testurl = "http://localhost:4507/testdata/desktop.ini"; const fileurl = new URL("./testdata/desktop.ini", import.meta.url); let etag: string | undefined | null;
{ const res = await fetch( testurl, { headers: [ ["Accept-Encoding", "gzip, deflate, br"], ], }, ); assertEquals(res.status, 200); assertEquals(res.statusText, "OK");
const data = await Deno.readTextFile( fileurl, ); assertEquals(data, await res.text()); // Consuming the body so that the test doesn't leak resources etag = res.headers.get("etag"); }
assert(typeof etag === "string"); assert(etag.length > 0); assert(etag.startsWith("W/")); { const res = await fetch( testurl, { headers: { "if-none-match": etag, }, }, ); assertEquals(res.status, 304); assertEquals(res.statusText, "Not Modified"); assertEquals("", await res.text()); // Consuming the body so that the test doesn't leak resources assert( etag === res.headers.get("etag") || etag === "W/" + res.headers.get("etag"), ); } } finally { await killFileServer(); } },);