Skip to content

Commit

Permalink
Refactor for easier testing
Browse files Browse the repository at this point in the history
following example from tj/commander.js#1565 (comment)
  • Loading branch information
IamJeffG committed Jul 16, 2024
1 parent 0bc57de commit 81e3d90
Show file tree
Hide file tree
Showing 5 changed files with 154 additions and 82 deletions.
79 changes: 0 additions & 79 deletions bin/audiomoth-utils.js

This file was deleted.

25 changes: 25 additions & 0 deletions bin/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env node

const command = require("../lib/command");
const program = command.makeProgram();

function main() {
try {
program.parse(process.argv);
} catch (err) {
if (err instanceof Error) {
// if (program.opts().debug) {
// console.error(`${err.stack}`);
// }
// if (err.message !== util.suppressTerminateExceptionMessage) {
console.log(`caught exception with message ${err.message}`);
// }
} else {
throw err;
}
// Recommended practice for node is set exitcode not force exit
process.exitCode = 7; // Exit with code 7 if an exception occurred
}
}

main().then(() => {});
86 changes: 86 additions & 0 deletions lib/command.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
const { Command, Option } = require("commander");
const audiomothUtils = require("audiomoth-utils");

function makeProgram() {
const program = new Command();

program
.description(
"Expand an AudioMoth T.WAV recording (a recording with amplitude thresholding or frequency triggering applied)"
) // TODO use addCommand to handle the subcommands
.arguments("<subcommand> <inputFile>")
.option(
"-d, --destination [outputPath]",
"output directory to write expansions. If omitted, dump expanded files in the same folder as inputFile."
)
.option(
"--prefix [prefix]",
"optional string (not including '_') to prefix to expanded filenames that will be created."
)
.addOption(
new Option(
"--max-file-duration [seconds]",
"max duration of expanded file to write, in seconds"
)
.argParser(parseInt)
.default(5)
)
.option("--generate-silent-files", "generate silent files", false)
.option(
"--align-to-second-transitions",
"align to second transitions",
false
)
.action((subcommand, inputFile, options) => {
const {
destination,
prefix,
maxFileDuration,
generateSilentFiles,
alignToSecondTransitions,
} = options;

// Determine expansionType based on command
let expansionType;
switch (subcommand) {
case "expand-duration":
expansionType = "DURATION";
break;
case "expand-event":
expansionType = "EVENT";
break;
default:
console.error("Invalid subcommand");
process.exit(9);
}

// Call the expand function with the provided arguments and options
const result = audiomothUtils.expand(
inputFile,
destination, // optional
prefix, // optional
expansionType,
maxFileDuration,
generateSilentFiles,
alignToSecondTransitions
);

if (result?.success) {
console.log("Expansion completed successfully.");
process.exit(0); // Exit with code 0 if success is true
} else {
console.error("Expansion failed:", result?.error);
process.exit(1); // Exit with code 1 if success is false
}
});
return program;
}

function fab(args) {
makeProgram().parse(args, { from: "user" });
}

module.exports = {
makeProgram: makeProgram,
fab: fab,
};
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
"version": "1.0.0",
"description": "A thin CLI wrapper over AudioMoth-Utils",
"bin": {
"hello-world": "./bin/audiomoth-utils.js"
"audiomoth-utils": "./bin/cli.js"
},
"scripts": {
"start": "node ./bin/audiomoth-utils.js",
"build": "pkg . --targets node14-linux-x64,node14-win-x64 --out-path dist"
"start": "node ./bin/cli.js",
"build": "pkg . --targets node14-linux-x64,node14-win-x64 --out-path dist",
"test": "jest"
},
"dependencies": {
"audiomoth-utils": "1.5.0",
"commander": "^12.1.0"
},
"devDependencies": {
"jest": "^29.7.0",
"pkg": "^5.8.1"
}
}
38 changes: 38 additions & 0 deletions test/command.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const command = require("../lib/command");

const audiomothUtils = require("audiomoth-utils");

jest.mock("audiomoth-utils", () => ({
expand: jest.fn(),
}));

describe("audiomoth-utils CLI", () => {
beforeEach(() => {
audiomothUtils.expand.mockClear();
audiomothUtils.expand.mockReturnValue({ success: true });
// Mock console.log and console.error
console.log = jest.fn();
console.error = jest.fn();
// Mock process.exit
process.exit = jest.fn();
});

test("calling with no arguments uses default values", () => {
command.fab(["expand-duration", "input.wav"]);

expect(audiomothUtils.expand).toHaveBeenCalledWith(
"input.wav",
undefined,
undefined,
"DURATION",
5,
false,
false
);

expect(console.log).toHaveBeenCalledWith(
"Expansion completed successfully."
);
expect(process.exit).toHaveBeenCalledWith(0);
});
});

0 comments on commit 81e3d90

Please sign in to comment.