sinon#stub TypeScript Examples
The following examples show how to use
sinon#stub.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: build.spec.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
describe("getLernaRoot", () => {
beforeEach(()=> {
});
afterEach(()=> {
sinon.restore();
});
test("ok: cwd = root ", async () => {
const root = tmpDir().name;
fs.ensureFileSync(path.join(root, "lerna.json"))
stub(process, "cwd").returns(root);
expect(BuildUtils.getLernaRoot()).toEqual(root);
});
test("ok: cwd below root ", async () => {
const root = tmpDir().name;
const twoDirsBelow = path.join(root, "one", "two");
fs.ensureDirSync(path.join(twoDirsBelow));
fs.ensureFileSync(path.join(root, "lerna.json"))
stub(process, "cwd").returns(twoDirsBelow);
expect(BuildUtils.getLernaRoot()).toEqual(root);
});
test("error: missing", async () => {
const root = tmpDir().name;
const twoDirsBelow = path.join(root, "one", "two");
fs.ensureDirSync(path.join(twoDirsBelow));
stub(process, "cwd").returns(twoDirsBelow);
expect(BuildUtils.getLernaRoot).toThrow(DendronError);
});
});
Example #2
Source File: publishCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
describe("WHEN run `dendron publish dev`", () => {
const cmd = PublishCommands.DEV;
afterEach(() => {
sinon.restore();
});
test("THEN run build ", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const cli = new PublishCLICommand();
const initStub = stub(cli, "init").resolves({ error: null });
const buildStub = stub(cli, "build").resolves({ error: null });
const devStub = stub(cli, "dev").resolves({ error: null });
await runPublishCmd({ cli, cmd, wsRoot });
expect(initStub.calledOnce).toBeTruthy();
expect(buildStub.calledOnce).toBeTruthy();
expect(devStub.calledOnce).toBeTruthy();
},
{
expect,
}
);
});
});
Example #3
Source File: publishCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
describe("WHEN run `dendron publish init`", () => {
const cmd = PublishCommands.INIT;
afterEach(() => {
sinon.restore();
});
test("THEN succeed", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const cli = new PublishCLICommand();
const initStub = stub(cli, "init").resolves({ error: null });
await runPublishCmd({ cli, cmd, wsRoot });
expect(initStub.calledOnce).toBeTruthy();
},
{
expect,
}
);
});
});
Example #4
Source File: publishCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
evalPublishCmd = ({
cmd,
...opts
}: {
cmd: PublishCommands;
cli?: PublishCLICommand;
} & PublishCLICommandCLIOpts) => {
const cli = opts.cli ? opts.cli : new PublishCLICommand();
sinon.stub(cli, "validateConfig").resolves();
return cli.eval({ cmd, ...opts });
}
Example #5
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
action = stub(this.program, 'action').returnsThis();
Example #6
Source File: tx.ts From algo-builder with Apache License 2.0 | 5 votes |
describe("ASA modify fields", () => {
useFixtureProject("config-project");
let deployer: Deployer;
let execParams: wtypes.ModifyAssetParam;
let algod: AlgoOperatorDryRunImpl;
let assetFields: wtypes.AssetModFields;
beforeEach(async () => {
const env = mkEnv("network1");
algod = new AlgoOperatorDryRunImpl();
const deployerCfg = new DeployerConfig(env, algod);
deployer = new DeployerDeployMode(deployerCfg);
assetFields = {
manager: "",
clawback: bobAcc.addr,
};
execParams = {
type: wtypes.TransactionType.ModifyAsset,
sign: wtypes.SignType.SecretKey,
payFlags: {},
fromAccount: bobAcc,
assetID: 1,
fields: assetFields,
};
stubAlgodGenesisAndTxParams(algod.algodClient);
});
afterEach(async () => {
(algod.algodClient.getTransactionParams as SinonStub).restore();
(algod.algodClient.genesis as SinonStub).restore();
});
/**
* Verifies correct asset fields are sent to network
* @param rawTxns rawTxns Signed transactions in Uint8Array
*/
function checkTx(rawTxns: Uint8Array | Uint8Array[]): Promise<ConfirmedTxInfo> {
if (Array.isArray(rawTxns)) {
// verify here if group tx
} else {
const tx: Transaction = decodeSignedTransaction(rawTxns).txn;
// Verify if fields are set correctly
assert.isUndefined(tx.assetManager);
assert.isUndefined(tx.assetReserve);
assert.equal(encodeAddress(tx.assetFreeze.publicKey), mockAssetInfo.params.freeze);
assert.equal(encodeAddress(tx.assetClawback.publicKey), assetFields.clawback);
}
(algod.sendAndWait as SinonStub).restore();
return algod.sendAndWait(rawTxns);
}
it("Should set fields, freeze is not sent, therefore it should be picked from assetInfo", async () => {
// Manager should be set to ""(sent as undefined to network)
// Clawback should be updated
stub(algod, "sendAndWait").callsFake(checkTx);
await deployer.executeTx([execParams]);
});
});
Example #7
Source File: tx.ts From algo-builder with Apache License 2.0 | 5 votes |
function stubAlgodGenesisAndTxParams(algodClient: algosdk.Algodv2): void {
stub(algodClient, "getTransactionParams").returns({
do: async () => mockSuggestedParam,
} as ReturnType<algosdk.Algodv2["getTransactionParams"]>);
stub(algodClient, "genesis").returns({ do: async () => mockGenesisInfo } as ReturnType<
algosdk.Algodv2["genesis"]
>);
}
Example #8
Source File: utils.spec.ts From opentelemetry-ext-js with Apache License 2.0 | 5 votes |
describe('elasticsearch utils', () => {
const spanMock = {
recordException: (err) => {},
setStatus: (obj) => {},
end: () => {},
setAttributes: (obj) => {},
};
context('defaultDbStatementSerializer', () => {
it('should serialize', () => {
const result = Utils.defaultDbStatementSerializer('operationName', { index: 'test' }, {});
expect(result).to.equal('{"params":{"index":"test"},"options":{}}');
});
});
context('onError', () => {
it('should record error', () => {
const recordExceptionStub = stub(spanMock, 'recordException');
const setStatusStub = stub(spanMock, 'setStatus');
const endStub = stub(spanMock, 'end');
const error = new Error('test error');
// @ts-ignore
Utils.onError(spanMock, error);
assert.calledOnce(recordExceptionStub);
assert.calledWith(recordExceptionStub, error);
assert.calledOnce(setStatusStub);
assert.calledWith(setStatusStub, { code: SpanStatusCode.ERROR, message: error.message });
assert.calledOnce(endStub);
recordExceptionStub.restore();
setStatusStub.restore();
endStub.restore();
});
});
context('onResponse', () => {
it('should record response without responseHook', () => {
const setAttributesStub = stub(spanMock, 'setAttributes');
const setStatusStub = stub(spanMock, 'setStatus');
const endStub = stub(spanMock, 'end');
// @ts-ignore
Utils.onResponse(spanMock, { meta: { connection: { url: 'http://localhost' } } });
assert.calledOnce(setAttributesStub);
assert.calledOnce(setStatusStub);
assert.calledOnce(endStub);
assert.calledWith(setStatusStub, { code: SpanStatusCode.OK });
setAttributesStub.restore();
setStatusStub.restore();
endStub.restore();
});
it('should record response with responseHook', () => {
const setAttributesStub = stub(spanMock, 'setAttributes');
const setStatusStub = stub(spanMock, 'setStatus');
const endStub = stub(spanMock, 'end');
const responseHook = spy();
// @ts-ignore
Utils.onResponse(spanMock, { meta: { connection: { url: 'http://localhost' } } }, responseHook);
assert.calledOnce(setAttributesStub);
assert.calledOnce(setStatusStub);
assert.calledOnce(endStub);
assert.calledWith(setStatusStub, { code: SpanStatusCode.OK });
expect(responseHook.called).to.be.true;
setAttributesStub.restore();
setStatusStub.restore();
endStub.restore();
});
});
context('getNetAttributes', () => {
const url = 'http://localhost:9200';
const attributes = Utils.getNetAttributes(url);
it('should get hostname from url', () => {
expect(attributes[SemanticAttributes.NET_PEER_NAME]).to.equal('localhost');
});
it('should get hostname from url', () => {
expect(attributes[SemanticAttributes.NET_PEER_PORT]).to.equal('9200');
});
it('should set net.transport', () => {
expect(attributes[SemanticAttributes.NET_TRANSPORT]).to.equal('IP.TCP');
});
});
context('getPort', () => {
it('should get port', () => {
const result = Utils.getPort('3030', 'http:');
expect(result).to.equal('3030');
});
it('should get port from http protocol', () => {
const result = Utils.getPort('', 'http:');
expect(result).to.equal('80');
});
it('should get port from https protocol', () => {
const result = Utils.getPort('', 'https:');
expect(result).to.equal('443');
});
});
context('normalizeArguments', () => {
it('should normalize with callback only', () => {
const callbackFunction = () => {};
// @ts-ignore
const [params, options, callback] = Utils.normalizeArguments(callbackFunction);
expect(params).to.be.empty;
expect(options).to.be.empty;
expect(callback).to.be.equal(callbackFunction);
});
it('should normalize with params only', () => {
// @ts-ignore
const [params, options, callback] = Utils.normalizeArguments({ index: 'test' });
expect(params).to.deep.equal({ index: 'test' });
expect(options).to.be.undefined;
expect(callback).to.be.undefined;
});
});
context('getIndexName', () => {
it('should accept index string', () => {
const index = Utils.getIndexName({ index: 'test' });
expect(index).to.equal('test');
});
it('should accept index array', () => {
const indexes = Utils.getIndexName({ index: ['index1', 'index2'] });
expect(indexes).to.equal('index1,index2');
});
it('should accept no index', () => {
const undefinedParams = Utils.getIndexName(undefined);
const emptyObject = Utils.getIndexName({});
expect(undefinedParams).to.be.undefined;
expect(emptyObject).to.be.undefined;
});
it('should ignore unexpected index', () => {
const functionIndex = Utils.getIndexName({ index: () => {} });
const objectIndex = Utils.getIndexName({ index: {} });
expect(functionIndex).to.be.undefined;
expect(objectIndex).to.be.undefined;
});
});
context('startSpan', () => {
const tracerMock = {
startSpan: (name, options?, context?): any => {},
startActiveSpan: () => {},
};
it('should start span with client kind', () => {
const startSpanStub = stub(tracerMock, 'startSpan');
Utils.startSpan({
tracer: tracerMock,
attributes: { testAttribute: 'testValue' },
});
assert.calledOnce(startSpanStub);
const [operation, options] = startSpanStub.getCall(0).args;
expect(operation).to.equal('elasticsearch.request');
expect(options.kind).to.equal(SpanKind.CLIENT);
expect(options.attributes[SemanticAttributes.DB_SYSTEM]).to.equal('elasticsearch');
expect(options.attributes.testAttribute).to.equal('testValue');
});
});
});
Example #9
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
outputHelp = stub(this.program, 'outputHelp');
Example #10
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
usage = stub(this.program, 'usage').returnsThis();
Example #11
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
name = stub(this.program, 'name').returnsThis();
Example #12
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
exitOverride = stub(this.program, 'exitOverride').returnsThis();
Example #13
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
opts = stub(this.program, 'opts').returnsThis();
Example #14
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
addHelpCommand = stub(this.program, 'addHelpCommand').returnsThis();
Example #15
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
parse = stub(this.program, 'parse');
Example #16
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
command = stub(this.program, 'command').returnsThis();
Example #17
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
requiredOption = stub(this.program, 'requiredOption').returnsThis();
Example #18
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
option = stub(this.program, 'option').returnsThis();
Example #19
Source File: cli_command.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 5 votes |
arguments = stub(this.program, 'arguments').returnsThis();
Example #20
Source File: example.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 4 votes |
// Describe the function or behavior to test
describe('The basicInputOutputExample function', () => {
// Define input
const input = 42;
// Define expectedOutput
const expectedOutput = 1596;
// Basic Mocha/Chai unit test example
it('returns the expected output', () => {
const actual = basicInputOutputExample(input);
expect(actual).to.equal(expectedOutput);
});
// Asynchronous mocha/chai example
it('asynchronously returns the expected output', async () => {
const actual = await asyncInputOutputExample(input);
// Returning anything to `it()` will conclude an async test
return expect(actual).to.equal(expectedOutput);
});
// To more easily be used with Sinon, use test function inside of an object
const objectWithExampleFunctions = { basicInputOutputExample };
// Sinon spy example
it('returns correct output when checked by Sinon spy', () => {
// Setup spy
const sinonSpy = spy(objectWithExampleFunctions, 'basicInputOutputExample');
// Run test as normal
const actual = objectWithExampleFunctions.basicInputOutputExample(input);
expect(actual).to.equal(expectedOutput);
// Verify spy calls with Chai
expect(sinonSpy.calledWith(input)).to.be.ok;
expect(sinonSpy.calledOnce).to.be.ok;
});
// Sinon stub example
it('can be stubbed by a Sinon stub', () => {
// Stub in a fake function
stub(objectWithExampleFunctions, 'basicInputOutputExample').callsFake(() => 1337);
const actual = objectWithExampleFunctions.basicInputOutputExample(input);
// Verify stubbed output
expect(actual).to.equal(1337);
});
// Sinon mock example
it('can be used in a Sinon mock', () => {
// Create mock
const sinonMock = mock(objectWithExampleFunctions);
// Setup mock expectations
sinonMock.expects('basicInputOutputExample').once().returns(10101);
const actual = objectWithExampleFunctions.basicInputOutputExample(input);
// Confirm output with Chai
expect(actual).to.equal(10101);
// Verify mock expectations
sinonMock.verify();
});
// Power-assert debugging example
it('can provide detailed error output when used with the power-assert library', () => {
// Comment out the regular Chai test
// const output = basicInputOutputExample(input);
// expect(output).to.equal(expectedOutput);
// Put everything relevant inside a power-assert assertion
// More info inside the assertion results in a more detailed output
assert(basicInputOutputExample(input) === expectedOutput);
/**
* This test has been left in a passing state because all tests must pass
* To view the detailed error output example, change above assertion to fail in some way
*
* For instance:
* assert(basicInputOutputExample(56) === expectedOutput);
* assert(basicInputOutputExample(input) !== expectedOutput);
*
* And then use: yarn power-assert -g 'power-assert'
*/
});
});
Example #21
Source File: local_file_path.test.ts From ardrive-cli with GNU Affero General Public License v3.0 | 4 votes |
describe('local path resolver methods', () => {
describe('getOutputFilePathAndName function', () => {
const fsStatSyncAndPathResolveWrapper = {
statSync: stub(),
resolve: stub()
};
before(() => {
// makes the resolve function to return the same given path
fsStatSyncAndPathResolveWrapper.resolve.returnsArg(0);
// makes the stubbed statsSync method to return a mocked fs.Stats for each corresponding case
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_PARENT_FOLDER).returns(mockStatsFolder);
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_FOLDER).returns(mockStatsFolder);
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_FILE).returns(mockStatsFile);
fsStatSyncAndPathResolveWrapper.statSync
.withArgs(PATH_EXISTING_NON_FILE)
.returns(mockStatsNotFileNorFolder);
// the stub throws for the nonexistent paths
fsStatSyncAndPathResolveWrapper.statSync.throws();
});
it('returns only the provided path if it is a directory', () => {
expect(getOutputFilePathAndName(PATH_EXISTING_FOLDER, fsStatSyncAndPathResolveWrapper)).to.deep.equal([
PATH_EXISTING_FOLDER
]);
});
it('returns the parent path and the basename if the file exists', () => {
expect(getOutputFilePathAndName(PATH_EXISTING_FILE, fsStatSyncAndPathResolveWrapper)).to.deep.equal([
PATH_EXISTING_PARENT_FOLDER,
NAME_EXISTING_FILE
]);
});
it("returns the parent path and the basename if it doesn't exist, but the parent does", () => {
expect(getOutputFilePathAndName(PATH_NONEXISTENT_FILE, fsStatSyncAndPathResolveWrapper)).to.deep.equal([
PATH_EXISTING_FOLDER,
NAME_NONEXISTENT_FILE
]);
});
it('throws if the path is neither a file nor a directory', () => {
expect(() => getOutputFilePathAndName(PATH_EXISTING_NON_FILE, fsStatSyncAndPathResolveWrapper)).to.throw();
});
it('throws if neither the path nor its parent exist', () => {
expect(() => getOutputFilePathAndName(PATH_NONEXISTENT, fsStatSyncAndPathResolveWrapper)).to.throw();
});
});
describe('getOutputFolderPathAndName function', () => {
const fsStatSyncAndPathResolveWrapper = {
statSync: stub(),
resolve: stub()
};
before(() => {
// makes the resolve function to return the same given path
fsStatSyncAndPathResolveWrapper.resolve.returnsArg(0);
// makes the stubbed statsSync method to return a mocked fs.Stats for each corresponding case
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_PARENT_FOLDER).returns(mockStatsFolder);
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_FOLDER).returns(mockStatsFolder);
fsStatSyncAndPathResolveWrapper.statSync.withArgs(PATH_EXISTING_FILE).returns(mockStatsFile);
// the stub throws for the nonexistent paths
fsStatSyncAndPathResolveWrapper.statSync.throws();
});
it('returns only the provided path if it is a directory', () => {
expect(getOutputFolderPathAndName(PATH_EXISTING_FOLDER, fsStatSyncAndPathResolveWrapper)).to.deep.equal([
PATH_EXISTING_FOLDER
]);
});
it('returns the parent path and the basename if the path is nonexistent but the parent is a directory', () => {
expect(getOutputFolderPathAndName(PATH_NONEXISTENT_FOLDER, fsStatSyncAndPathResolveWrapper)).to.deep.equal([
PATH_EXISTING_PARENT_FOLDER,
NAME_NONEXISTENT_FOLDER
]);
});
it("throws if the path isn't a directory", () => {
expect(() => getOutputFolderPathAndName(PATH_EXISTING_FILE, fsStatSyncAndPathResolveWrapper)).to.throw();
});
it('throws if the path nor its parent exist', () => {
expect(() => getOutputFolderPathAndName(PATH_NONEXISTENT, fsStatSyncAndPathResolveWrapper)).to.throw();
});
});
});
Example #22
Source File: devCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
describe("build", () => {
const cmd = DevCommands.BUILD;
// TODO: this test is too brittle. need to revisit later
test.skip("ok, build local", async () => {
await runEngineTestV5(
async () => {
// stub lerna.json
const root = tmpDir().name;
fs.writeJsonSync(path.join(root, "lerna.json"), { version: "1.0.0" });
stub(process, "cwd").returns(root);
const prepPublishLocalStub = stub(
BuildUtils,
"prepPublishLocal"
).returns(undefined);
const typecheckStub = stub(BuildUtils, "runTypeCheck").returns();
const bumpVersionStub = stub(LernaUtils, "bumpVersion").returns();
const publishVersionStub = stub(LernaUtils, "publishVersion").returns(
Promise.resolve()
);
const buildNextServerStub = stub(
BuildUtils,
"buildNextServer"
).returns();
const buildPluginViewsStub = stub(
BuildUtils,
"buildPluginViews"
).returns();
const syncStaticAssetsStub = stub(
BuildUtils,
"syncStaticAssets"
).returns(Promise.resolve({ staticPath: "" }));
const syncStaticAssetsToNextjsTemplateStub = stub(
BuildUtils,
"syncStaticAssetsToNextjsTemplate"
).returns(Promise.resolve());
const prepPluginPkgStub = stub(BuildUtils, "prepPluginPkg").returns(
Promise.resolve()
);
const installPluginDependenciesStub = stub(
BuildUtils,
"installPluginDependencies"
).returns({} as any);
const compilePluginStub = stub(BuildUtils, "compilePlugin").returns(
{} as any
);
const packagePluginDependenciesStub = stub(
BuildUtils,
"packagePluginDependencies"
).returns({} as any);
const setRegRemoteStub = stub(BuildUtils, "setRegRemote").returns();
const restorePluginPkgJsonStub = stub(
BuildUtils,
"restorePluginPkgJson"
).returns();
const sleepStub = stub(TimeUtils, "sleep").returns(Promise.resolve());
await runDevCmd({
cmd,
publishEndpoint: PublishEndpoint.LOCAL,
upgradeType: SemverVersion.PATCH,
});
[
prepPublishLocalStub,
typecheckStub,
bumpVersionStub,
publishVersionStub,
buildNextServerStub,
buildPluginViewsStub,
syncStaticAssetsStub,
syncStaticAssetsToNextjsTemplateStub,
prepPluginPkgStub,
installPluginDependenciesStub,
compilePluginStub,
packagePluginDependenciesStub,
setRegRemoteStub,
restorePluginPkgJsonStub,
sleepStub,
].map((_stub) => {
// uncomment to figure out which stub is failing
// console.log(_stub);
expect(_stub.calledOnce).toBeTruthy();
});
},
{
expect,
}
);
});
});
Example #23
Source File: publishCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
describe("WHEN run `dendron publish build`", () => {
const cmd = PublishCommands.BUILD;
afterEach(() => {
sinon.restore();
});
test("THEN succeed", async () => {
jest.setTimeout(15000);
await runEngineTestV5(
async ({ wsRoot }) => {
await runPublishCmd({ cmd, wsRoot });
const dataDir = path.join(wsRoot, ".next", "data");
expect(fs.existsSync(dataDir)).toBeTruthy();
},
{
expect,
}
);
});
describe("AND WHEN sitemap is used", () => {
test("THEN sitemap is called", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const cli = new PublishCLICommand();
const buildNext = stub(cli, "_buildNextData").resolves({
error: undefined,
data: {} as any,
});
const buildSiteMapstub = stub(
NextjsExportPodUtils,
"buildSiteMap"
).resolves(0);
await runPublishCmd({
cli,
cmd,
wsRoot,
sitemap: true,
});
expect(
_.every(
[buildNext, buildSiteMapstub].map((ent) => {
return ent.calledOnce;
})
)
).toBeTruthy();
},
{
expect,
}
);
});
});
describe("AND with invalid override key", () => {
test("THEN show error", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const out = await evalPublishCmd({
cmd,
wsRoot,
overrides: "foo=bar",
});
expect(out?.error?.message).toEqual(
"bad key for override. foo is not a valid key"
);
},
{
expect,
preSetupHook: ENGINE_HOOKS.setupBasic,
}
);
});
});
describe("AND with asset prefix without forward slash", () => {
test("THEN show error", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
TestConfigUtils.withConfig(
(config) => {
ConfigUtils.setPublishProp(config, "assetsPrefix", "foo");
return config;
},
{ wsRoot }
);
await evalPublishCmd({
cmd,
wsRoot,
});
const out = await evalPublishCmd({
cmd,
wsRoot,
});
await checkString(out.error!.message, "assetsPrefix requires a '/");
},
{
expect,
preSetupHook: ENGINE_HOOKS.setupBasic,
}
);
});
});
describe("AND with siteUrl override", () => {
test("THEN update siteUrl", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const siteUrlOverride = "http://foo.com";
await evalPublishCmd({
cmd,
wsRoot,
overrides: `siteUrl=${siteUrlOverride}`,
});
const dest = URI.file(path.join(wsRoot, ".next"));
const dataDir = path.join(wsRoot, ".next", "data");
expect(fs.existsSync(dataDir)).toBeTruthy();
const cpath = NextjsExportPodUtils.getDendronConfigPath(dest);
const config = fs.readJSONSync(cpath) as IntermediateDendronConfig;
expect(config.publishing!.siteUrl).toEqual(siteUrlOverride);
},
{
expect,
preSetupHook: ENGINE_HOOKS.setupBasic,
}
);
});
});
});
Example #24
Source File: publishCLICommand.spec.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
describe("WHEN run `dendron publish export`", () => {
const cmd = PublishCommands.EXPORT;
afterEach(() => {
sinon.restore();
});
describe("AND WHEN github target", () => {
describe("AND docs folder exists", () => {
test("THEN delete when confirm", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const cli = new PublishCLICommand();
const docsPath = path.join(wsRoot, "docs");
fs.ensureDirSync(docsPath);
fs.ensureFileSync(path.join(docsPath, "canary-fail"));
fs.ensureFileSync(
path.join(wsRoot, ".next", "out", "canary-success")
);
const initStub = stub(cli, "init").resolves({ error: null });
const buildStub = stub(cli, "build").resolves({ error: null });
const exportStub = stub(cli, "export").resolves({} as any);
prompts.inject([true]);
await runPublishCmd({
cli,
cmd,
wsRoot,
target: PublishTarget.GITHUB,
});
// build and export called
expect(initStub.calledOnce).toBeTruthy();
expect(buildStub.calledOnce).toBeTruthy();
expect(exportStub.calledOnce).toBeTruthy();
// old docs removed
expect(
fs.pathExistsSync(path.join(docsPath, "canary-fail"))
).toBeFalsy();
// contents of out moved over
expect(
fs.pathExistsSync(path.join(docsPath, "canary-success"))
).toBeTruthy();
// no jekyll file generated
expect(
fs.pathExistsSync(path.join(docsPath, ".nojekyll"))
).toBeTruthy();
},
{
expect,
}
);
});
test("THEN cancel when no confirm", async () => {
await runEngineTestV5(
async ({ wsRoot }) => {
const cli = new PublishCLICommand();
const docsPath = path.join(wsRoot, "docs");
fs.ensureDirSync(docsPath);
fs.ensureFileSync(path.join(docsPath, "canary-fail"));
fs.ensureFileSync(
path.join(wsRoot, ".next", "out", "canary-success")
);
const initStub = stub(cli, "init").resolves({ error: null });
const buildStub = stub(cli, "build").resolves({ error: null });
const exportStub = stub(cli, "export").resolves({} as any);
prompts.inject([false]);
await runPublishCmd({
cli,
cmd,
wsRoot,
target: PublishTarget.GITHUB,
});
// build and export called
expect(initStub.calledOnce).toBeTruthy();
expect(buildStub.callCount).toBeTruthy();
expect(exportStub.calledOnce).toBeTruthy();
// old docs removed
expect(
fs.pathExistsSync(path.join(docsPath, "canary-fail"))
).toBeTruthy();
// contents of out moved over
expect(
fs.pathExistsSync(path.join(docsPath, "canary-success"))
).toBeFalsy();
// no jekyll file generated
expect(
fs.pathExistsSync(path.join(docsPath, ".nojekyll"))
).toBeFalsy();
},
{
expect,
}
);
});
});
});
});
Example #25
Source File: debug.test.ts From js-sdk with MIT License | 4 votes |
describe('debug', function () {
let logger: Debugger
let logStub: sinon.SinonStub<any[], void>
function expectedTestMessage(namespace: string, message: string): string {
return `${namespace} ${message}`
}
beforeEach(() => {
logger = debug('test')
logStub = stub(logger, 'log')
})
afterEach(() => {
logStub.restore()
logger.destroy()
debug.disable()
})
it('logs when enabled', () => {
debug.enable('test')
assert.isTrue(logger.enabled)
const testMessage = 'halo is good!'
logger(testMessage)
assert.isTrue(logStub.calledOnceWith(expectedTestMessage('[test]', testMessage)))
})
it('does not log when not enabled', () => {
const testMessage = 'halo is good!'
logger(testMessage)
assert.isTrue(logStub.notCalled)
})
it('stops logging after being disabled', () => {
debug.enable('test')
assert.isTrue(logger.enabled)
const testMessage = 'halo is good!'
logger(testMessage)
assert.isTrue(logStub.calledOnceWith(expectedTestMessage('[test]', testMessage)))
assert.strictEqual(debug.disable(), 'test', 'disable should return the list of what was enabled')
assert.isFalse(logger.enabled)
logger(testMessage)
assert.isTrue(logStub.calledOnce, 'Logger should not have been called a second time.')
})
it('extend() creates a new namespace', () => {
const subLogger = logger.extend('foo')
assert.strictEqual(subLogger.namespace, 'test:foo')
debug.enable('test:foo')
const testMessage = 'hello world!'
logger(testMessage)
subLogger(testMessage)
assert.isTrue(logStub.calledOnceWith(expectedTestMessage('[test:foo]', testMessage)))
})
it('enable() handles a csv list', () => {
debug.enable('test,test2')
assert.isTrue(debug.enabled('test'))
assert.isTrue(debug.enabled('test2'))
})
it('enable() supports wildcards', () => {
const subLogger = logger.extend('foo')
debug.enable('test:*')
assert.isTrue(subLogger.enabled)
const testMessage = 'hello world!'
subLogger(testMessage)
assert.isTrue(logStub.calledOnceWith(expectedTestMessage('[test:foo]', testMessage)))
})
it('enable() supports the global wildcard', () => {
debug.enable('*')
assert.isTrue(debug.enabled('test'))
assert.isTrue(debug.enabled('bar'))
})
it('enable() supports skips', () => {
debug.enable('*,-test:*')
assert.isTrue(debug.enabled('bar'))
assert.isFalse(debug.enabled('test:foo'))
})
it('names ending in * are always enabled', () => {
assert.isTrue(debug.enabled('foo*'))
})
})
Example #26
Source File: dryrun.ts From algo-builder with Apache License 2.0 | 4 votes |
describe("Debugging TEAL code using tealdbg", () => {
useFixtureProject("config-project");
let deployer: Deployer;
let algod: AlgoOperatorDryRunImpl;
let txParam: ExecParams;
let tealDebugger: TealDbgMock;
beforeEach(async () => {
const env = mkEnv("network1");
algod = new AlgoOperatorDryRunImpl();
const deployerCfg = new DeployerConfig(env, algod);
deployer = new DeployerRunMode(deployerCfg);
stub(algod.algodClient, "getTransactionParams").returns({
do: async () => mockSuggestedParam,
} as ReturnType<algosdk.Algodv2["getTransactionParams"]>);
stub(algod.algodClient, "genesis").returns({
do: async () => mockGenesisInfo,
} as ReturnType<algosdk.Algodv2["genesis"]>);
(stub(algod.algodClient, "dryrun") as any).returns({
do: async () => mockDryRunResponse,
}) as ReturnType<algosdk.Algodv2["dryrun"]>;
(stub(algod.algodClient, "accountInformation") as any).returns({
do: async () => mockAccountInformation,
}) as ReturnType<algosdk.Algodv2["accountInformation"]>;
(stub(algod.algodClient, "getApplicationByID") as any).returns({
do: async () => mockApplicationResponse,
}) as ReturnType<algosdk.Algodv2["getApplicationByID"]>;
txParam = {
type: types.TransactionType.TransferAsset,
sign: types.SignType.LogicSignature,
fromAccountAddr: generateAccount().addr,
toAccountAddr: generateAccount().addr,
amount: 500,
assetID: 1,
lsig: mockLsig,
payFlags: { totalFee: 1000 },
};
tealDebugger = new TealDbgMock(deployer, txParam);
});
afterEach(async () => {
(algod.algodClient.getTransactionParams as SinonStub).restore();
(algod.algodClient.dryrun as SinonStub).restore();
(algod.algodClient.accountInformation as SinonStub).restore();
(algod.algodClient.getApplicationByID as SinonStub).restore();
(algod.algodClient.genesis as SinonStub).restore();
});
it("dump dryrunResponse in assets/<file>", async () => {
const resp = await tealDebugger.dryRunResponse();
// assert recieved response
assert.deepEqual(resp, mockDryRunResponse);
// dump response to file in assets
await tealDebugger.dryRunResponse("dryrun-resp.json");
// verify path and data
const outPath = path.join(process.cwd(), ASSETS_DIR, "dryrun-resp.json");
assert.isTrue(pathExistsSync(outPath));
const data = fs.readFileSync(outPath);
assert.deepEqual(JSON.parse(Buffer.from(data).toString()), mockDryRunResponse);
fs.rmSync(outPath);
});
it("should warn or overwrite existing dryRunResponse based on --force flag", async () => {
const stub = console.error as SinonStub;
stub.reset();
await tealDebugger.dryRunResponse("response.json");
await tealDebugger.dryRunResponse("response.json"); // running again with same outfile
const warnMsg =
"File assets/response.json already exists. Aborting. Use --force flag if you want to overwrite it";
assert.isTrue(stub.calledWith(warnMsg));
// if --force == true is passed then file is overwritten
await tealDebugger.dryRunResponse("response.json", true);
assert.isTrue(
(console.log as SinonStub).calledWith(`Data written succesfully to assets/response.json`)
);
fs.rmSync(path.join(process.cwd(), ASSETS_DIR, "response.json"));
});
it("should write --dryrun-dump in `cache/dryrun` and run debugger with provided args", async () => {
assert.equal(tealDebugger.writtenFiles.length, 0);
await tealDebugger.run();
// verify .msdp (dryrun dump) is present in cache/dryrun
assert.equal(tealDebugger.writtenFiles.length, 1);
// eg. artifacts/cache/dryrun/dump-1626204870.msgp
const pathToMsgpDump = tealDebugger.writtenFiles[0];
assert.equal(path.dirname(pathToMsgpDump), "artifacts/cache/dryrun");
// verify dump arg (-d)
assert.include(tealDebugger.debugArgs, "-d");
assert.include(tealDebugger.debugArgs, pathToMsgpDump);
// verify path to teal file is present(if passed)
await tealDebugger.run({ tealFile: "gold-asa.teal" });
assert.include(tealDebugger.debugArgs, "assets/gold-asa.teal");
// verify mode and groupIndex arg (--mode, --group-index)
await tealDebugger.run({ mode: ExecutionMode.APPLICATION, groupIndex: 0 });
assert.include(tealDebugger.debugArgs, "--mode");
assert.include(tealDebugger.debugArgs, "application");
assert.include(tealDebugger.debugArgs, "--group-index");
assert.include(tealDebugger.debugArgs, "0");
});
it("should throw error if groupIndex is greator than txGroup length", async () => {
tealDebugger.execParams = [txParam, { ...txParam, payFlags: { note: "Algrand" } }];
try {
await tealDebugger.run({ mode: ExecutionMode.APPLICATION, groupIndex: 5 });
} catch (error) {
if (error instanceof Error) {
assert.equal(error.message, "groupIndex(= 5) exceeds transaction group length(= 2)");
}
console.error("An unexpected error occurred:", error);
}
});
it("should run debugger using pyteal files as well", async () => {
const writtenFilesBeforeLen = tealDebugger.writtenFiles.length;
await tealDebugger.run({ tealFile: "gold-asa.py" });
// 2 files should be written: (1. --dryrun-dump and 2. compiled teal code from pyTEAL)
assert.equal(tealDebugger.writtenFiles.length, writtenFilesBeforeLen + 2);
});
it("should run debugger from cached TEAL code", async () => {
const stub = console.info as SinonStub;
stub.reset();
const writtenFilesBeforeLen = tealDebugger.writtenFiles.length;
// write to cache
const pathToWrite = path.join(CACHE_DIR, "gold-asa.py.yaml");
fs.writeFileSync(
pathToWrite,
YAML.stringify({
tealCode: getProgram("gold-asa.py"),
})
);
await tealDebugger.run({ tealFile: "gold-asa.py" });
// verify cached console.info is true
assert.isTrue(
(console.info as SinonStub).calledWith(
"\x1b[33m%s\x1b[0m",
`Using cached TEAL code for gold-asa.py`
)
);
// 2 files should be written: (1. --dryrun-dump and 2. cached teal code from pyTEAL)
assert.equal(tealDebugger.writtenFiles.length, writtenFilesBeforeLen + 2);
fs.rmSync(pathToWrite);
});
});