Skip to content
Myr

null-answer.test.ts

This file

Path

packages/checks/test/null-answer.test.ts

460 lines · 14.3 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { LaneName } from "@repo/protocol/ids";4import { WeakCheck } from "@repo/protocol/refusal";5import { Effect, FileSystem, Option, Path, Stream } from "effect";6import { ChildProcess, ChildProcessSpawner } from "effect/process";78import { diagnose, Diagnosis, failureSignature } from "../src/classify.ts";9import type { RunExit } from "../src/classify.ts";10import type { RepoFile } from "../src/finder.ts";11import {12  nullAnswer,13  NullAnswerFailed,14  nullAnswerVerdict,15} from "../src/null-answer.ts";16import {17  datesRepo,18  nullDates,19  strongNewCheck,20  weakNewCheck,21} from "./fixtures/null-answer/dates.ts";22import bunAssertion from "./fixtures/runs/bun-assertion.json" with { type: "json" };23import bunLoadError from "./fixtures/runs/bun-load-error.json" with { type: "json" };24import bunNoTests from "./fixtures/runs/bun-no-tests.json" with { type: "json" };25import vitestAssertion from "./fixtures/runs/vitest-assertion.json" with { type: "json" };2627const dates = { paths: ["packages/dates/**"] } as const;2829const unit = LaneName.make("unit");3031const onUnit = (exit: RunExit) => ({ exit, lane: unit });3233const contentsOf = (files: readonly RepoFile[]) =>34  Object.fromEntries(files.map(({ content, path }) => [path, content]));3536describe("the null answer", () => {37  it.effect(38    "stubs each function, arrow and class method the territory exports, and leaves the rest as it was",39    () =>40      Effect.gen(function* () {41        const tree = yield* nullAnswer(datesRepo, dates);4243        expect(contentsOf(tree)).toStrictEqual({44          ...contentsOf(datesRepo),45          ...contentsOf(nullDates),46        });47      })48  );4950  it.effect(51    "reads the territory's public files, when it names them, in place of its exports",52    () =>53      Effect.gen(function* () {54        const tree = yield* nullAnswer(datesRepo, {55          ...dates,56          publicFiles: ["packages/dates/src/parse.ts"],57        });5859        const nullParse = nullDates.filter(60          ({ path }) => path === "packages/dates/src/parse.ts"61        );6263        expect(contentsOf(tree)).toStrictEqual({64          ...contentsOf(datesRepo),65          ...contentsOf(nullParse),66        });67      })68  );6970  it.effect(71    "reads each source file a subpath pattern of its exports leads to",72    () =>73      Effect.gen(function* () {74        const manifest = {75          content: '{ "exports": { "./*": "./src/*.ts" } }\n',76          path: "package.json",77        };7879        const tree = yield* nullAnswer(80          [81            manifest,82            {83              content: "export const add = (a: number, b: number) => a + b;\n",84              path: "src/add.ts",85            },86            {87              content:88                "export function half(n: number) {\n  return n / 2;\n}\n",89              path: "src/math/half.ts",90            },91          ],92          { paths: ["src/**"] }93        );9495        expect(tree).toStrictEqual([96          manifest,97          {98            content:99              "export const add = (a: number, b: number) => undefined as never;\n",100            path: "src/add.ts",101          },102          {103            content:104              "export function half(n: number) { return undefined as never; }\n",105            path: "src/math/half.ts",106          },107        ]);108      })109  );110111  it.effect("reads the main file of a package that has no exports", () =>112    Effect.gen(function* () {113      const manifest = {114        content: '{ "main": "./src/index.ts" }\n',115        path: "package.json",116      };117118      const tree = yield* nullAnswer(119        [120          manifest,121          {122            content: "export const twice = (n: number) => n * 2;\n",123            path: "src/index.ts",124          },125        ],126        { paths: ["src/**"] }127      );128129      expect(tree).toStrictEqual([130        manifest,131        {132          content: "export const twice = (n: number) => undefined as never;\n",133          path: "src/index.ts",134        },135      ]);136    })137  );138139  it.effect("stubs nothing outside the territory", () =>140    Effect.gen(function* () {141      const tree = yield* nullAnswer(datesRepo, {142        paths: ["packages/dates/src/clock.ts"],143      });144145      expect(146        tree.filter(147          ({ content, path }) => content !== contentsOf(datesRepo)[path]148        )149      ).toStrictEqual(150        nullDates.filter(({ path }) => path === "packages/dates/src/clock.ts")151      );152    })153  );154155  it.effect("fails when the territory has no entry point", () =>156    Effect.gen(function* () {157      expect(158        yield* Effect.flip(nullAnswer(datesRepo, { paths: ["checks/**"] }))159      ).toStrictEqual(160        new NullAnswerFailed({161          path: "checks/**",162          reason:163            "no entry point: the territory names no public files, and no package.json exports a source file for it",164        })165      );166    })167  );168169  it.effect(170    "fails when the territory exports no function, arrow or class",171    () =>172      Effect.gen(function* () {173        const constants = [174          { content: "export const LIMIT = 3;\n", path: "src/limits.ts" },175        ];176177        expect(178          yield* Effect.flip(179            nullAnswer(constants, {180              paths: ["src/**"],181              publicFiles: ["src/limits.ts"],182            })183          )184        ).toStrictEqual(185          new NullAnswerFailed({186            path: "src/**",187            reason:188              "nothing to stub: the entry points export no function, arrow or class from the territory",189          })190        );191      })192  );193194  it.effect("fails on a territory file that does not parse", () =>195    Effect.gen(function* () {196      const broken = [197        { content: "export function parse( {\n", path: "src/parse.ts" },198      ];199200      const failed = yield* Effect.flip(201        nullAnswer(broken, { paths: ["src/**"], publicFiles: ["src/parse.ts"] })202      );203204      expect(failed).toBeInstanceOf(NullAnswerFailed);205      expect(failed.path).toBe("src/parse.ts");206    })207  );208209  it.effect(210    "gives the same tree each time, and leaves its input as it was",211    () =>212      Effect.gen(function* () {213        const before = structuredClone(datesRepo);214215        const frozen = Object.freeze(216          datesRepo.map((file) => Object.freeze(file))217        );218219        const first = yield* nullAnswer(frozen, dates);220        const second = yield* nullAnswer(frozen, dates);221222        expect(second).toStrictEqual(first);223        expect(frozen).toStrictEqual(before);224      })225  );226});227228describe(nullAnswerVerdict, () => {229  it("is WeakCheck nullAnswer for a check that passed against the null answer", () => {230    const passed: RunExit = { code: 0, stderr: " 1 pass\n 0 fail", stdout: "" };231232    expect(nullAnswerVerdict(onUnit(passed))).toStrictEqual(233      Option.some(new WeakCheck({ weakness: "nullAnswer" }))234    );235  });236237  it("is WeakCheck no assertion for a run that found no tests", () => {238    expect(nullAnswerVerdict(onUnit(bunNoTests))).toStrictEqual(239      Option.some(new WeakCheck({ weakness: "no assertion" }))240    );241  });242243  it("finds no weakness in a check that failed against the null answer", () => {244    expect([245      nullAnswerVerdict(onUnit(bunAssertion)),246      nullAnswerVerdict(onUnit(vitestAssertion)),247    ]).toStrictEqual([Option.none(), Option.none()]);248  });249250  it("finds no weakness in a check that never loaded: that is red first's question", () => {251    expect(nullAnswerVerdict(onUnit(bunLoadError))).toStrictEqual(252      Option.none()253    );254  });255});256257const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>258  bytes.pipe(Stream.decodeText(), Stream.mkString);259260const written = (files: readonly RepoFile[]) =>261  Effect.gen(function* () {262    const fs = yield* FileSystem.FileSystem;263    const path = yield* Path.Path;264    const dir = yield* fs.makeTempDirectoryScoped({ prefix: "null-answer-" });265266    for (const file of files) {267      const at = path.join(dir, file.path);268269      yield* fs.makeDirectory(path.dirname(at), { recursive: true });270      yield* fs.writeFileString(at, file.content);271    }272273    return dir;274  });275276const ran = (dir: string, command: string) =>277  Effect.scoped(278    Effect.gen(function* () {279      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;280281      const child = yield* spawner.spawn(282        ChildProcess.make("sh", ["-c", command], {283          cwd: dir,284          env: { FORCE_COLOR: "0", NO_COLOR: "1" },285          extendEnv: true,286        })287      );288289      const [stdout, stderr, code] = yield* Effect.all(290        [text(child.stdout), text(child.stderr), child.exitCode],291        { concurrency: "unbounded" }292      );293294      return { code, stderr, stdout } satisfies RunExit;295    })296  );297298describe("a check run against the null answer", () => {299  it.live("runs on a tree that typechecks with tsc --noEmit", () =>300    Effect.gen(function* () {301      const tsc = (yield* Path.Path).resolve("node_modules", ".bin", "tsc");302      const dir = yield* written(yield* nullAnswer(datesRepo, dates));303304      const { code, stdout } = yield* ran(305        dir,306        `"${tsc}" --noEmit -p tsconfig.json`307      );308309      expect({ code, stdout }).toStrictEqual({ code: 0, stdout: "" });310    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))311  );312313  it.live(314    "is weak when it only asks that the subject exists, and passes anyway",315    () =>316      Effect.gen(function* () {317        const dir = yield* written(yield* nullAnswer(datesRepo, dates));318        const exit = yield* ran(dir, "bun test ./checks/weak.test.ts");319320        expect(nullAnswerVerdict(onUnit(exit))).toStrictEqual(321          Option.some(new WeakCheck({ weakness: "nullAnswer" }))322        );323      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))324  );325326  it.live(327    "is strong when it asserts what the subject returns, and fails by that assertion",328    () =>329      Effect.gen(function* () {330        const dir = yield* written(yield* nullAnswer(datesRepo, dates));331        const exit = yield* ran(dir, "bun test ./checks/strong.test.ts");332333        expect({334          byAssertion: Option.isSome(failureSignature(exit)),335          verdict: nullAnswerVerdict(onUnit(exit)),336        }).toStrictEqual({ byAssertion: true, verdict: Option.none() });337      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))338  );339});340341describe("a check written before its subject", () => {342  const beforeWeekOf = [...datesRepo, weakNewCheck, strongNewCheck];343344  it.live("fails on main by a load error, not an assertion", () =>345    Effect.gen(function* () {346      const dir = yield* written(beforeWeekOf);347      const exit = yield* ran(dir, "bun test ./checks/week-strong.test.ts");348349      expect(Diagnosis.$is("LoadError")(diagnose(exit))).toBeTruthy();350    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))351  );352353  it.live(354    "loads against the null answer, which stands in for each name it imports from the territory",355    () =>356      Effect.gen(function* () {357        const dir = yield* written(yield* nullAnswer(beforeWeekOf, dates));358        const weak = yield* ran(dir, "bun test ./checks/week-weak.test.ts");359        const strong = yield* ran(dir, "bun test ./checks/week-strong.test.ts");360361        expect({362          strongByAssertion: Option.isSome(failureSignature(strong)),363          verdicts: [weak, strong].map((exit) =>364            nullAnswerVerdict(onUnit(exit))365          ),366        }).toStrictEqual({367          strongByAssertion: true,368          verdicts: [369            Option.some(new WeakCheck({ weakness: "nullAnswer" })),370            Option.none(),371          ],372        });373      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))374  );375376  it.effect(377    "stands in for a territory file it imports that main lacks, and leaves a type import out",378    () =>379      Effect.gen(function* () {380        const check = {381          content: [382            'import { expect, test } from "bun:test";',383            'import type { Week } from "../packages/dates/src/week.js";',384            'import weeks, { weekOf } from "../packages/dates/src/week.js";',385            "",386            'test("weekOf", () => {',387            "  expect(weekOf(weeks())).toBe(41);",388            "});",389            "",390          ].join("\n"),391          path: "checks/week-file.test.ts",392        };393394        const tree = yield* nullAnswer([...datesRepo, check], dates);395396        expect(397          tree.filter(({ path }) => path.endsWith("/week.ts"))398        ).toStrictEqual([399          {400            content: [401              "export default function (..._args: readonly unknown[]): never { return undefined as never; }",402              "export function weekOf(..._args: readonly unknown[]): never { return undefined as never; }",403              "",404            ].join("\n"),405            path: "packages/dates/src/week.ts",406          },407        ]);408      })409  );410411  it.live("runs on a tree that still typechecks", () =>412    Effect.gen(function* () {413      const tsc = (yield* Path.Path).resolve("node_modules", ".bin", "tsc");414      const dir = yield* written(yield* nullAnswer(beforeWeekOf, dates));415416      const { code, stdout } = yield* ran(417        dir,418        `"${tsc}" --noEmit -p tsconfig.json`419      );420421      expect({ code, stdout }).toStrictEqual({ code: 0, stdout: "" });422    }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))423  );424});425426describe("where ts-morph is reached from", () => {427  it.effect(428    "only the null answer imports it, and no other module of @repo/checks imports the null answer, so no other entry bundles the compiler",429    () =>430      Effect.gen(function* () {431        const fs = yield* FileSystem.FileSystem;432        const path = yield* Path.Path;433        const sources = yield* fs.readDirectory("src", { recursive: true });434435        // Any quoted specifier counts: a static, dynamic or re-exporting import.436        const tsMorph: string[] = [];437        const theNullAnswer: string[] = [];438439        for (const file of sources.filter((each) => each.endsWith(".ts"))) {440          const source = yield* fs.readFileString(path.join("src", file));441442          if (/["']ts-morph["']/u.test(source)) {443            tsMorph.push(file);444          }445446          if (447            file !== "null-answer.ts" &&448            /["'][^"'\n]*null-answer(?:\.ts)?["']/u.test(source)449          ) {450            theNullAnswer.push(file);451          }452        }453454        expect({ theNullAnswer, tsMorph }).toStrictEqual({455          theNullAnswer: [],456          tsMorph: ["null-answer.ts"],457        });458      }).pipe(Effect.provide(NodeServices.layer))459  );460});