Skip to content

Commit

Permalink
fix(tests): missed files
Browse files Browse the repository at this point in the history
  • Loading branch information
Jake Lauer authored and Jake Lauer committed Jul 21, 2024
1 parent 760714b commit dedf27b
Show file tree
Hide file tree
Showing 20 changed files with 620 additions and 216 deletions.
13 changes: 4 additions & 9 deletions .mocharc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,16 @@
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

module.exports = {
require: [
"ts-node/register",
"tsconfig-paths/register"
],
// Search the whole tree
recursive: true,
// Match the following extensions
extension: ["ts", "tsx"],
extension: ["ts"],
// Skip over shit
ignore: ["**/node_modules/**/*", "**/dist/**/*"],
// TBH I don't know why this is required, but removing it breaks things and it's not in the docs for Mocha.
// Seems as though this determines the search pattern, but then why do I also have to specify extensions?
spec: ["**/*.test.js", "**/*.test.ts"],
"node-option": [
"experimental-specifier-resolution=node",
"loader=ts-node/esm"
spec: ["**/*.test.js", "**/*.test.ts"],
"node-option": [
"loader=ts-node/esm"
]
};
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"test:debug": "cross-env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --exit --config ./.mocharc.cjs --theseus-log-level debug",
"test:pkg": "pnpm -r run test",
"test:pkg:sandbox": "pnpm -r run test",
"test:base": "cross-env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --exit --config ./.mocharc.cjs",
"test:base": "ts-mocha --paths --exit --config ./.mocharc.cjs",
"test": "pnpm test:pkg && pnpm test:base",
"// ==== BUILD ==== //": "",
"build:base": "tsup && resolve-tspaths",
Expand Down Expand Up @@ -88,7 +88,7 @@
"mocha-suppress-logs": "^0.4.1",
"prettier": "^3.2.5",
"prettier-eslint": "^16.3.0",
"proxyquire": "^2.1.3",
"quibble": "0.9.2",
"resolve-tspaths": "^0.8.18",
"semantic-release": "^23.1.1",
"semantic-release-monorepo": "^8.0.2",
Expand All @@ -98,10 +98,12 @@
"theseus-gpt-zip": "workspace:~",
"theseus-logger": "workspace:~",
"theseus-sandbox": "workspace:~",
"ts-mocha": "^10.0.0",
"ts-node": "10.9.2",
"tsconfig-paths": "^4.2.0",
"tsup": "^8.1.0",
"tsx": "^4.11.0",
"typescript": "^5.4.5"
"typescript": "^5.4.5",
"vitest": "^2.0.3"
},
"lint-staged": {
"*.ts": [
Expand Down
14 changes: 14 additions & 0 deletions packages/eslint-plugin-theseus/.mocharc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Ignore issues with self-signed certs
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

module.exports = {
// Search the whole tree
recursive: true,
// Match the following extensions
extension: ["js"],
// Skip over shit
ignore: ["**/node_modules/**/*", "**/dist/**/*"],
// TBH I don't know why this is required, but removing it breaks things and it's not in the docs for Mocha.
// Seems as though this determines the search pattern, but then why do I also have to specify extensions?
spec: ["**/*.test.js"]
};
2 changes: 1 addition & 1 deletion packages/eslint-plugin-theseus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "lib/index.js",
"scripts": {
"build": "echo 'no build'",
"test": "mocha '**/_test/*.test.js'"
"test": "mocha --exit --config ./.mocharc.cjs"
},
"devDependencies": {
"eslint": "^8.57.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/logger/lib/_test/get-theseus-logger.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect } from "chai";
import { expect } from "vitest";
import sinon from "sinon";
import * as winston from "winston";
import { getTheseusLogger, type MockLoggingLib } from "../get-theseus-logger.js";
Expand Down
8 changes: 4 additions & 4 deletions packages/logger/lib/stringifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ export const stringifier = (obj: object) =>
return `CANNOT_STRINGIFY: ${e}`;
}
};
function isShallowSandbox(obj: object)
function isShallowSandbox<T extends object>(obj: T)
{
return !!obj?.[CONSTANTS.SANDBOX_SYMBOL];
return !!(obj as any)?.[CONSTANTS.SANDBOX_SYMBOL];
}

function isShallowFrost(obj: object)
function isShallowFrost<T extends object>(obj: T)
{
return !!obj?.[CONSTANTS.FROST.BASIS_SYMBOL];
return !!(obj as any)?.[CONSTANTS.FROST.BASIS_SYMBOL];
}

10 changes: 8 additions & 2 deletions packages/sandbox/lib/_test/type-tests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,12 @@ describe("Integration type tests", function ()
{
const val = propValuesByType[key as keyof typeof propValuesByType];

expect(val[Symbol.toStringTag]).to.be.undefined;
expect(val?.[Symbol.toStringTag]).to.be.undefined;
expect(isElligibleForProxy(val)).to.be.true;

// @ts-expect-error - known possible undefined value
const sb = sandbox(val);
// @ts-expect-error - known possible undefined value
const f = frost(val);

expect(isSandbox(sb)).to.be.true;
Expand All @@ -218,10 +220,12 @@ describe("Integration type tests", function ()
{
const val = propValuesByType[key as keyof typeof propValuesByType];

expect(val[Symbol.toStringTag]).to.be.undefined;
expect(val?.[Symbol.toStringTag]).to.be.undefined;
expect(isElligibleForProxy(val)).to.be.true;

// @ts-expect-error - known possible undefined value
const sb = sandbox(val);
// @ts-expect-error - known possible undefined value
const f = frost(val);

expect(isSandbox(sb)).to.be.true;
Expand All @@ -239,7 +243,9 @@ describe("Integration type tests", function ()
`Expected ${key} not to be elligible for proxy`,
);

// @ts-expect-error - known possible undefined value
const sb = sandbox(val);
// @ts-expect-error - known possible undefined value
const f = frost(val);

expect(isSandbox(sb)).to.equal(false, `Expected ${key} to not be a sandbox`);
Expand Down
19 changes: 7 additions & 12 deletions packages/sandbox/lib/actions/cement/cement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function cement<T extends object>(obj: T): T
const rootCemented = cementAtRoot(obj);
if (rootCemented !== undefined)
{
finalResult = rootCemented;
finalResult = rootCemented as T;
}

// If the object contains nested sandbox proxies, apply the changes recursively.
Expand All @@ -46,32 +46,27 @@ export function cement<T extends object>(obj: T): T
return finalResult;
}

function cementAtRoot<T extends object>(obj: T): T
function cementAtRoot<T extends object>(obj: T)
{
let original: T,
changes: Record<string | symbol, any>,
mode: SandboxMode,
isSandbox = false;
mode: SandboxMode;
try
{
// If this errors, the object is not a sandbox proxy
const sbMetadata = obj[CONSTANTS.SANDBOX_SYMBOL];
original = sbMetadata.original;
changes = sbMetadata.changes;
mode = sbMetadata.params.mode;
isSandbox = true;
}
catch
{
// Not really an error case, just means the object is not a sandbox proxy
}

if (isSandbox)
{
const toModify = getModifiableObject(original, mode);

return applyChanges(toModify, changes);
}
catch
{
// Not really an error case, just means the object is not a sandbox proxy
}
}

function getModifiableObject<T extends object>(obj: T, mode: SandboxMode): T
Expand Down
31 changes: 15 additions & 16 deletions packages/sandbox/lib/actions/sandbox/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,22 +46,21 @@ function createProxy<T extends object>(obj: T, proxyMap: WeakMap<T, T>, params:
const metadata = createMetadata(obj, params);

const proxy =
proxyMap.has(obj) ?
proxyMap.get(obj)
: new Proxy<T>(obj, {
get(target, prop, receiver)
{
return handleGet(target, prop, receiver, metadata, proxyMap);
},
set(_target, prop, value)
{
return handleSet(prop, value, metadata, proxyMap);
},
deleteProperty(_target, prop)
{
return handleDelete(prop, metadata);
},
});
proxyMap.get(obj) ??
new Proxy<T>(obj, {
get(target, prop, receiver)
{
return handleGet(target, prop, receiver, metadata, proxyMap);
},
set(_target, prop, value)
{
return handleSet(prop, value, metadata, proxyMap);
},
deleteProperty(_target, prop)
{
return handleDelete(prop, metadata);
},
});

if (!proxyMap.has(obj))
{
Expand Down
29 changes: 29 additions & 0 deletions packages/sandbox/lib/quibble.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
declare module 'quibble' {
export type QuibbleConfig = {
defaultFakeCreator: (request: string) => any;
};

type Quibble = {
<T = any>(request: string, stub?: any): T;
config(userConfig: Partial<QuibbleConfig>): QuibbleConfig;
ignoreCallsFromThisFile(file?: string): void;
reset(hard?: boolean): void;
absolutify(relativePath: string, parentFileName?: string): string;
esm<TMockedType extends Record<string, any> = Record<string, any>>(
specifier: string,
namedExportStubs?:Partial<TMockedType>,
defaultExportStub?: any
): Promise<void>;
listMockedModules(): string[];
isLoaderLoaded(): boolean;
esmImportWithPath(specifier: string): Promise<{
modulePath: string;
moduleUrl: string;
module: any;
}>;
};

const quibble: Quibble;
const _default: Quibble;
export { quibble, _default as default };
}
90 changes: 35 additions & 55 deletions packages/sandbox/lib/strictness/_test/strictness.test.ts
Original file line number Diff line number Diff line change
@@ -1,90 +1,70 @@
import { expect } from "chai";
import {
beforeEach, describe, it,
describe, it, afterEach,
} from "mocha";
import sinon from "sinon";
import * as loggerModule from "theseus-logger";
import proxyquire from "proxyquire";
import type * as StrictnessType from "../strictness.js";
import quibble from "quibble";

const strictness = proxyquire<typeof StrictnessType>("../strictness", {
"theseus-logger": {
getTheseusLogger: () => {},
},
});
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
type LoggerMock = typeof import("theseus-logger");

describe("fail function", () =>
{
let logSpy: { warn: sinon.SinonSpy; error: sinon.SinonSpy; debug: sinon.SinonSpy };
let fail: any;
const logSpy = {
warn: sinon.spy(),
error: sinon.spy(),
debug: sinon.spy(),
};

beforeEach(() =>
await quibble.esm<LoggerMock>("theseus-logger", {
getTheseusLogger: (name: string) =>
{
logSpy = {
warn: sinon.spy(),
error: sinon.spy(),
debug: sinon.spy(),
};

// Use proxyquire to mock 'theseus-logger' module
fail = strictness.fail;
console.log("Mock getTheseusLogger called with name:", name);
return logSpy as any;
},
});

sinon.stub(loggerModule, "getTheseusLogger").returns(logSpy as any);
});
const { fail } = await import("../strictness.js");

afterEach(function ()
describe("fail function", () =>
{
afterEach(() =>
{
sinon.restore();
logSpy.warn.resetHistory();
logSpy.error.resetHistory();
logSpy.debug.resetHistory();
});

it("calls log.debug when strict is undefined or false", () =>
{
fail(undefined, "Test message");
expect(logSpy.debug.calledOnceWith("Test message")).to.be.true;

fail(
{
strict: false,
},
"Test message",
);
expect(logSpy.debug.calledTwice).to.be.true;
fail({
strict: false,
}, "Test message");
expect(logSpy.debug).to.be.calledTwice;
});

it("calls log.warn when strict is 'warn'", () =>
{
fail(
{
strict: "warn",
},
"Warning message",
);
fail({
strict: "warn",
}, "Warning message");
expect(logSpy.warn.calledOnceWith("Warning message")).to.be.true;
});

it("throws an error and calls log.error when strict is true and multiple parameters are provided", () =>
{
expect(() =>
fail(
{
strict: true,
},
"Error message",
"Extra info",
),
).to.throw("Extra info");
expect(() => fail({
strict: true,
}, "Error message", "Extra info")).to.throw("Error message");
expect(logSpy.error.calledOnceWith("Error message", "Extra info")).to.be.true;
});

it("throws an error with the correct message when strict is true and only one parameter is provided", () =>
{
expect(() =>
fail(
{
strict: true,
},
"Error message",
),
).to.throw("Error message");
expect(() => fail({
strict: true,
}, "Error message")).to.throw("Error message");
});
});
Loading

0 comments on commit dedf27b

Please sign in to comment.