Skip to content

Commit

Permalink
release: v0.3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
JairusSW committed Aug 8, 2024
1 parent 2ddc485 commit 7e4cbbb
Show file tree
Hide file tree
Showing 23 changed files with 889 additions and 614 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ v0.2.1 - Remove accidental logging

v0.3.0 - Pass metadata through terminal - Support for multiple files - Better reporting - Timing for suites - Terminal utilities
v0.3.1 - Add screenshot of completed tests to readme
v0.3.2 - Add `mockImport` to override imported functions
13 changes: 3 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
| _ || __| ___|_ _|| __|| __||_ _|
| ||__ ||___| | | | __||__ | | |
|__|__||_____| |_| |_____||_____| |_|
v0.3.1
v0.3.2
</pre>
</h5>

Expand Down Expand Up @@ -59,6 +59,8 @@ mockFn<void>("console.log", (data: string): void => {
console.log("[MOCKED]: " + data + "\n");
});

// Or override an imported function with mockImport

describe("Should sleep", () => {
test("1ms", () => {
const start = Date.now();
Expand Down Expand Up @@ -133,21 +135,12 @@ Build and run it using as-test
npm run test
```

<img src="https://raw.githubusercontent.com/JairusSW/as-test/main/assets/img/screenshot.png">

<h6>

## Running

To add `as-test` to your CI/CD workflow, check out [The provided example](https://github.com/JairusSW/as-test/blob/main/.github/workflows/nodejs.yml)

If you use this project in your codebase, consider dropping a [⭐ HERE](https://github.com/JairusSW/as-test). I would really appreciate it!

## Notes

This library is in the EARLY STAGES OF DEVELOPMENT!
If you want a feature, drop an issue (and again, maybe a star). I'll likely add it in less than 7 days.

## Issues

Please submit an issue to https://github.com/JairusSW/as-test/issues if you find anything wrong with this library
22 changes: 22 additions & 0 deletions assembly/__tests__/mock.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { expect, it, log, mockFn, mockImport, run } from "..";
import { foo, getFoo } from "./mock";

// function foo(): string {
// return "bar";
// }

mockFn(foo, (): string => {
return "baz " + foo();
});

mockImport("mock.foo", (): string => {
return "biz";
});

it("should mock functions", () => {
log(foo());
expect(foo()).toBe("baz biz");
expect(getFoo()).toBe("biz");
});

run();
7 changes: 7 additions & 0 deletions assembly/__tests__/mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

@external("mock", "foo")
export declare function foo(): string;

export function getFoo(): string {
return foo();
}
32 changes: 13 additions & 19 deletions assembly/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Expectation } from "./src/expectation";
import { stringify } from "as-console/stringify";
import { __COVER, __HASHES, __POINTS } from "as-test/assembly/coverage";
import { JSON } from "json-as";
import { term, TermLine } from "./util/term";
import { term } from "./util/term";
import { Log } from "./src/log";

let entrySuites: Suite[] = [];
Expand All @@ -13,6 +13,10 @@ let entrySuites: Suite[] = [];
const FILE = isDefined(ENTRY_FILE) ? ENTRY_FILE : "unknown";
// Globals
// @ts-ignore
@global let __mock_global: Map<string, u32> = new Map<string, u32>();
// @ts-ignore
@global let __mock_import: Map<string, u32> = new Map<string, u32>();
// @ts-ignore
@global let suites: Suite[] = [];
// @ts-ignore
@global let depth: i32 = -1;
Expand Down Expand Up @@ -215,26 +219,16 @@ export function afterEach(callback: () => void): void {
}

/**
* Overrides all references to an existing function in local scope to instead point to new function
* @param {string} fn - name of function to override
* @param {() => returnType} callback - the function to substitute it with
*/
export function mockFn<returnType>(
fn: string,
callback: (...args: any[]) => returnType,
): void {}

/**
* Unmock all references to an existing function to instead point to the original function
* @param {string} fn - name of function to override
* Replace all references to an existing function to new function
* @param {Function} oldFn - name of function to mock
* @param {Function} newFn - the function to substitute it with
*/
export function unmockFn(fn: string): void {}
export function mockFn(oldFn: Function, newFn: Function): void {}

/**
* Re-mock all references to an existing function to instead point to the declared function
* @param {string} fn - name of function to override
*/
export function remockFn(fn: string): void {}
export function mockImport(oldFn: string, newFn: () => string): void {
__mock_import.set(oldFn, newFn.index);
// mocks.set(oldFn, new MockFn(oldFn, newFn).enable());
}

/**
* Class defining options that can be passed to the `run` function.
Expand Down
142 changes: 77 additions & 65 deletions bin/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,80 +7,92 @@ import { loadConfig } from "./util.js";
const CONFIG_PATH = path.join(process.cwd(), "./as-test.config.json");
const PKG_PATH = path.join(process.cwd(), "./package.json");
export async function build() {
let config = loadConfig(CONFIG_PATH, true);
const ASCONFIG_PATH = path.join(process.cwd(), config.config);
if (config.config && config.config !== "none" && !existsSync(ASCONFIG_PATH)) {
console.log(`${chalk.bgMagentaBright(" WARN ")}${chalk.dim(":")} Could not locate asconfig.json file! If you do not want to provide a config, set "config": "none"`);
}
ensureDeps(config);
let pkgRunner = getPkgRunner();
const inputFiles = await glob(config.input);
let buildArgs = getBuildArgs(config);
for (const file of inputFiles) {
let cmd = `${pkgRunner} asc ${file}${buildArgs}`;
const outFile = `${config.outDir}/${file.slice(file.lastIndexOf("/") + 1).replace(".ts", ".wasm")}`;
if (config.outDir) {
cmd += " -o " + outFile;
}
buildFile(cmd);
let config = loadConfig(CONFIG_PATH, true);
const ASCONFIG_PATH = path.join(process.cwd(), config.config);
if (config.config && config.config !== "none" && !existsSync(ASCONFIG_PATH)) {
console.log(
`${chalk.bgMagentaBright(" WARN ")}${chalk.dim(":")} Could not locate asconfig.json file! If you do not want to provide a config, set "config": "none"`,
);
}
ensureDeps(config);
let pkgRunner = getPkgRunner();
const inputFiles = await glob(config.input);
let buildArgs = getBuildArgs(config);
for (const file of inputFiles) {
let cmd = `${pkgRunner} asc ${file}${buildArgs}`;
const outFile = `${config.outDir}/${file.slice(file.lastIndexOf("/") + 1).replace(".ts", ".wasm")}`;
if (config.outDir) {
cmd += " -o " + outFile;
}
buildFile(cmd);
}
}
function ensureDeps(config) {
const pkg = JSON.parse(readFileSync(PKG_PATH).toString());
if (config.buildOptions.target == "wasi") {
if (!existsSync("./node_modules/@assemblyscript/wasi-shim/asconfig.json")) {
console.log(`${chalk.bgRed(" ERROR ")}${chalk.dim(":")} could not find @assemblyscript/wasi-shim! Add it to your dependencies to run with WASI!`);
process.exit(1);
}
if (pkg.dependencies &&
!Object.keys(pkg.dependencies).includes("@assemblyscript/wasi-shim") &&
pkg.devDependencies &&
!Object.keys(pkg.devDependencies).includes("@assemblyscript/wasi-shim") &&
pkg.peerDependencies &&
!Object.keys(pkg.peerDependencies).includes("@assemblyscript/wasi-shim") &&
existsSync("./node_modules/@assemblyscript/wasi-shim/asconfig.json")) {
console.log(`${chalk.bold.bgMagentaBright(" WARN ")}${chalk.dim(":")} @assemblyscript/wasi-shim is not included in project dependencies!"`);
}
const pkg = JSON.parse(readFileSync(PKG_PATH).toString());
if (config.buildOptions.target == "wasi") {
if (!existsSync("./node_modules/@assemblyscript/wasi-shim/asconfig.json")) {
console.log(
`${chalk.bgRed(" ERROR ")}${chalk.dim(":")} could not find @assemblyscript/wasi-shim! Add it to your dependencies to run with WASI!`,
);
process.exit(1);
}
if (
pkg.dependencies &&
!Object.keys(pkg.dependencies).includes("@assemblyscript/wasi-shim") &&
pkg.devDependencies &&
!Object.keys(pkg.devDependencies).includes("@assemblyscript/wasi-shim") &&
pkg.peerDependencies &&
!Object.keys(pkg.peerDependencies).includes(
"@assemblyscript/wasi-shim",
) &&
existsSync("./node_modules/@assemblyscript/wasi-shim/asconfig.json")
) {
console.log(
`${chalk.bold.bgMagentaBright(" WARN ")}${chalk.dim(":")} @assemblyscript/wasi-shim is not included in project dependencies!"`,
);
}
}
}
function getPkgRunner() {
switch (process.env.npm_config_user_agent) {
case "pnpm": {
return "pnpx";
}
case "yarn": {
return "yarn";
}
case "bun": {
return "bunx";
}
switch (process.env.npm_config_user_agent) {
case "pnpm": {
return "pnpx";
}
case "yarn": {
return "yarn";
}
return "npx";
case "bun": {
return "bunx";
}
}
return "npx";
}
function buildFile(command) {
execSync(command, { stdio: "inherit" });
execSync(command, { stdio: "inherit" });
}
function getBuildArgs(config) {
let buildArgs = "";
buildArgs += " --transform as-test/transform --transform json-as/transform";
if (config.config && config.config !== "none") {
buildArgs += " --config " + config.config;
}
// Should also strip any bindings-enabling from asconfig
if (config.buildOptions.target == "bindings") {
buildArgs += " --bindings raw --exportRuntime --exportStart _start";
}
else if (config.buildOptions.target == "wasi") {
buildArgs +=
" --config ./node_modules/@assemblyscript/wasi-shim/asconfig.json";
}
else {
console.log(`${chalk.bgRed(" ERROR ")}${chalk.dim(":")} could determine target in config! Set target to 'bindings' or 'wasi'`);
process.exit(0);
}
if (config.buildOptions.args.length &&
config.buildOptions.args.find((v) => v.length > 0)) {
buildArgs += " " + config.buildOptions.args.join(" ");
}
return buildArgs;
let buildArgs = "";
buildArgs += " --transform as-test/transform --transform json-as/transform";
if (config.config && config.config !== "none") {
buildArgs += " --config " + config.config;
}
// Should also strip any bindings-enabling from asconfig
if (config.buildOptions.target == "bindings") {
buildArgs += " --bindings raw --exportRuntime --exportStart _start";
} else if (config.buildOptions.target == "wasi") {
buildArgs +=
" --config ./node_modules/@assemblyscript/wasi-shim/asconfig.json";
} else {
console.log(
`${chalk.bgRed(" ERROR ")}${chalk.dim(":")} could determine target in config! Set target to 'bindings' or 'wasi'`,
);
process.exit(0);
}
if (
config.buildOptions.args.length &&
config.buildOptions.args.find((v) => v.length > 0)
) {
buildArgs += " " + config.buildOptions.args.join(" ");
}
return buildArgs;
}
Loading

0 comments on commit 7e4cbbb

Please sign in to comment.