Skip to main content
Module

std/http/file_server_test.ts

Deno standard library
Go to Latest
File
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
// 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<Deno.SpawnOptions>;
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` 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(); } },);