Path: blob/master/src/packages/backend/conat/test/files/read.test.ts
1451 views
/*1Test async streaming read of files from a compute servers using NATS.234DEVELOPMENT:56pnpm test ./read.test.ts78*/910import { before, after } from "@cocalc/backend/conat/test/setup";1112beforeAll(before);1314import { close, createServer, readFile } from "@cocalc/conat/files/read";15import { createReadStream } from "fs";16import { file as tempFile } from "tmp-promise";17import { writeFile as fsWriteFile } from "fs/promises";18import { sha1 } from "@cocalc/backend/sha1";1920describe("do a basic test that the file read service works", () => {21const project_id = "00000000-0000-4000-8000-000000000000";22const compute_server_id = 0;23it("create the read server", async () => {24await createServer({25project_id,26compute_server_id,27createReadStream,28});29});3031let cleanups: any[] = [];32const CONTENT = "cocalc";33let source;34it("creates the file we will read", async () => {35const { path, cleanup } = await tempFile();36source = path;37await fsWriteFile(path, CONTENT);38cleanups.push(cleanup);39});4041it("reads the file into memory", async () => {42const r = await readFile({ project_id, compute_server_id, path: source });43// will get just one chunk44for await (const chunk of r) {45expect(chunk.toString()).toEqual(CONTENT);46}47});4849it("closes the write server", async () => {50close({ project_id, compute_server_id });51for (const f of cleanups) {52f();53}54});55});5657describe("do a larger test that involves multiple chunks and a different name", () => {58const project_id = "00000000-0000-4000-8000-000000000000";59const compute_server_id = 0;60const name = "b";61it("create the read server", async () => {62await createServer({63project_id,64compute_server_id,65createReadStream,66name,67});68});6970let cleanups: any[] = [];71let CONTENT = "";72for (let i = 0; i < 1000000; i++) {73CONTENT += `${i}`;74}75let source;76it("creates the file we will read", async () => {77const { path, cleanup } = await tempFile();78source = path;79await fsWriteFile(path, CONTENT);80cleanups.push(cleanup);81});8283it("reads the file into memory", async () => {84const r = await readFile({85project_id,86compute_server_id,87path: source,88name,89});90// will get many chunks.91let chunks: any[] = [];92for await (const chunk of r) {93chunks.push(chunk);94}95expect(chunks.length).toBeGreaterThan(1);96const s = Buffer.concat(chunks).toString();97expect(s.length).toBe(CONTENT.length);98expect(sha1(s)).toEqual(sha1(CONTENT));99});100101it("closes the write server", async () => {102close({ project_id, compute_server_id, name });103for (const f of cleanups) {104f();105}106});107});108109110afterAll(after);111112113