mocha#it TypeScript Examples

The following examples show how to use mocha#it. 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: util.test.ts    From persistent-merkle-tree with Apache License 2.0 7 votes vote down vote up
describe("computeProofGindices", () => {
  it("simple implementation should match bitstring implementation", () => {
    const gindices = [BigInt(8), BigInt(9), BigInt(14)];
    for (const gindex of gindices) {
      const simple = computeProofGindices(gindex);
      const bitstring = computeProofBitstrings(gindex.toString(2));
      expect(new Set([...bitstring.branch].map((str) => BigInt("0b" + str)))).to.deep.equal(simple.branch);
      expect(new Set([...bitstring.path].map((str) => BigInt("0b" + str)))).to.deep.equal(simple.path);
    }
  });

  it("should properly compute known testcases", () => {
    const testCases = [
      {
        input: BigInt(8),
        output: {branch: new Set([BigInt(9), BigInt(5), BigInt(3)]), path: new Set([BigInt(8), BigInt(4), BigInt(2)])},
      },
      {
        input: BigInt(9),
        output: {branch: new Set([BigInt(8), BigInt(5), BigInt(3)]), path: new Set([BigInt(9), BigInt(4), BigInt(2)])},
      },
      {
        input: BigInt(14),
        output: {
          branch: new Set([BigInt(15), BigInt(6), BigInt(2)]),
          path: new Set([BigInt(14), BigInt(7), BigInt(3)]),
        },
      },
    ];
    for (const {input, output} of testCases) {
      const actual = computeProofGindices(input);
      expect(actual.branch).to.deep.equal(output.branch);
      expect(actual.path).to.deep.equal(output.path);
    }
  });
});
Example #2
Source File: utils.test.ts    From context-mod with MIT License 7 votes vote down vote up
describe('Parsing Reddit Entity strings', function () {
    it('should recognize entity name regardless of prefix', function () {
        for(const text of ['/r/anEntity', 'r/anEntity', '/u/anEntity', 'u/anEntity']) {
            assert.equal(parseRedditEntity(text).name, 'anEntity');
        }
    })

    it('should distinguish between subreddit and user prefixes', function () {
        assert.equal(parseRedditEntity('r/mySubreddit').type, 'subreddit');
        assert.equal(parseRedditEntity('u/aUser').type, 'user');
    })

    it('should recognize user based on u_ prefix', function () {
        assert.equal(parseRedditEntity(' u_aUser ').type, 'user');
    })

    it('should handle whitespace', function () {
        assert.equal(parseRedditEntity(' /r/mySubreddit ').name, 'mySubreddit');
    })

    it('should handle dashes in the entity name', function () {
        assert.equal(parseRedditEntity(' /u/a-user ').name, 'a-user');
    })
})
Example #3
Source File: stream-utils.spec.ts    From mtcute with GNU Lesser General Public License v3.0 7 votes vote down vote up
describe('readStreamUntilEnd', () => {
    it('should read stream until end', async () => {
        const stream = new Readable({
            read() {
                this.push(Buffer.from('aaeeff', 'hex'))
                this.push(Buffer.from('ff33ee', 'hex'))
                this.push(null)
            },
        })

        expect((await readStreamUntilEnd(stream)).toString('hex')).eq(
            'aaeeffff33ee'
        )
    })
})
Example #4
Source File: backing.test.ts    From persistent-merkle-tree with Apache License 2.0 6 votes vote down vote up
describe("set", () => {
  it("should return the right node", () => {
    const n = subtreeFillToDepth(new LeafNode(Buffer.alloc(32, 1)), 3);
    const n2 = new LeafNode(Buffer.alloc(32, 2));
    const backing = new Tree(n);
    backing.setNode(15n, n2, true);
    assert.deepEqual(backing.getRoot(15n), Buffer.alloc(32, 2));
  });
});
Example #5
Source File: bitcointransactiontest.spec.ts    From edge-currency-plugins with MIT License 6 votes vote down vote up
describe('bitcoin bip32 seed, aka airbitz seed, to xpriv. Taken from official bip32 test vectors', () => {
  it('seed to xpriv', () => {
    const result = seedOrMnemonicToXPriv({
      seed:
        '//z59vPw7ern5OHe29jV0s/MycbDwL26t7SxrquopaKfnJmWk5CNioeEgX57eHVyb2xpZmNgXVpXVFFOS0hFQg==',
      type: BIP43PurposeTypeEnum.Legacy,
      coin: 'bitcoin'
    })
    expect(result).to.equal(
      'xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt'
    )
  })
})
Example #6
Source File: utils.test.ts    From context-mod with MIT License 6 votes vote down vote up
describe('Non-temporal Comparison Operations', function () {
    it('should throw if no operator sign', function () {
        const shouldThrow = () => parseGenericValueComparison('just 3');
        assert.throws(shouldThrow)
    });
    it('should parse greater-than with a numeric value', function () {
        const res = parseGenericValueComparison('> 3');
        assert.equal(res.operator, '>')
        assert.equal(res.value, 3);
    });
    it('should parse greater-than-or-equal-to with a numeric value', function () {
        const res = parseGenericValueComparison('>= 3');
        assert.equal(res.operator, '>=')
        assert.equal(res.value, 3)
    })
    it('should parse less-than with a numeric value', function () {
        const res = parseGenericValueComparison('< 3');
        assert.equal(res.operator, '<')
        assert.equal(res.value, 3)
    })
    it('should parse less-than-or-equal-to with a numeric value', function () {
        const res = parseGenericValueComparison('<= 3');
        assert.equal(res.operator, '<=')
        assert.equal(res.value, 3)
    })
    it('should parse extra content', function () {
        const res = parseGenericValueComparison('<= 3 foobars');
        assert.equal(res.extra, ' foobars')

        const noExtra = parseGenericValueComparison('<= 3');
        assert.isUndefined(noExtra.extra)
    })
    it('should parse percentage', function () {
        const withPercent = parseGenericValueOrPercentComparison('<= 3%');
        assert.isTrue(withPercent.isPercent)

        const withoutPercent = parseGenericValueOrPercentComparison('<= 3');
        assert.isFalse(withoutPercent.isPercent)
    })
});
Example #7
Source File: 1.arrange.ts    From attendance-backend with MIT License 6 votes vote down vote up
describe(' => Testing / route', () => {
  before((done) => {
    try {
      serverInstance.listen(3000)
      setTimeout(() => {
        connect(async () => {
          logger.info('Connecting to database to clear old records')
          Seed()
          db.collection('users').deleteMany({})
          logger.info('Cleared collection : users')
          db.collection('events').deleteMany({})
          logger.info('Cleared collection : events')
          db.collection('sessions').deleteMany({})
          logger.info('Cleared collection : sessions')
          done()
        })
      }, 3000)
    } catch (error) {
      done(error)
    }
  })

  //   testing connection
  it('should just pass', (done) => {
    done()
  })
})
Example #8
Source File: utils.spec.ts    From programmer-fa with MIT License 6 votes vote down vote up
describe('Unit tests', () => {
  it('should properly count the number of hashtags', ((done) => {
    const testCase = 'سلام این یک متن جاوا #اسکریپتی می‌باشد. و این #جمله هم دارای تعدادی، #هشتگ است';

    expect(getNumberOfHashtags(testCase)).to.equal(3);

    done();
  }));

  it('should remove suspicious words from a string', ((done) => {
    const testCase = 'سلام این یک متن است که دارای کلمات جنگو و روبی و پایتون و چند تای دیگر است که این اسامی باید حذف شوند.';

    expect(removeSuspiciousWords(testCase)).to.equal('سلام این یک متن است که دارای کلمات جنگو و و و چند تای دیگر است که این اسامی باید حذف شوند.');

    done();
  }));

  it('should remove all URLs from a string', ((done) => {
    const testCase = 'سلام این یک متن است که شامل چندین URL هست که باید حذف شوند: https://google.com http://www.google.com یکی دیگه: http://google.com/ اینم آخری: google.com';

    expect(removeURLs(testCase))
      .to.equal('سلام این یک متن است که شامل چندین url هست که باید حذف شوند: یکی دیگه: / اینم آخری:');

    done();
  }));

  it('should convert a string to hashtag', (done) => {
    const testCase = 'سلام این یک متن جاوا اسکریپتی می‌باشد. و این کلمه هم دارای خط-تیره است';

    expect(makeHashtag(testCase)).to.equal('#سلام_این_یک_متن_جاوا_اسکریپتی_می_باشد_و_این_کلمه_هم_دارای_خط_تیره_است');

    done();
  });

  it('should properly count the characters of a tweet', (done) => {
    const testCase = 'سلام این یک متن جاوا اسکریپتی می‌باشد. و این کلمه هم دارای خط-تیره است';

    expect(getTweetLength(testCase)).to.equal(70);

    done();
  });

  it('should return a `DateTime` object from a twitter data string', () => {
    const testCase = 'Wed Dec 23 13:28:54 +0000 2020';

    expect(parseTwitterDateToLuxon(testCase).isValid).to.equal(true);
  })
});
Example #9
Source File: remarkable.test.ts    From reMarkable-typescript with MIT License 6 votes vote down vote up
describe('Client initialization', () => {
  it('should not set the deviceToken if not provided', () => {
    const client = new Remarkable();
    expect(client.deviceToken).to.be.undefined;
  });
  it('should set the deviceToken if provided', () => {
    const client = new Remarkable({ deviceToken: 'test' });
    expect(client.deviceToken).to.be.equal('test');
  });
});
Example #10
Source File: Extension-PostUpgrade.test.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
suite(
  "temporary testing of Dendron version compatibility downgrade sequence",
  () => {
    describe(`GIVEN the activation sequence of Dendron`, () => {
      describe(`WHEN VS Code Version is up to date`, () => {
        let invokedWorkspaceTrustFn: boolean = false;

        beforeEach(() => {
          invokedWorkspaceTrustFn = semver.gte(vscode.version, "1.57.0");
        });

        it(`THEN onDidGrantWorkspaceTrust will get invoked.`, () => {
          expect(invokedWorkspaceTrustFn).toEqual(true);
        });

        it(`AND onDidGrantWorkspaceTrust can be found in the API.`, () => {
          vscode.workspace.onDidGrantWorkspaceTrust(() => {
            //no-op for testing
          });
        });
      });

      describe(`WHEN VS Code Version is on a version less than 1.57.0`, () => {
        let invokedWorkspaceTrustFn: boolean = false;
        const userVersion = "1.56.1";
        beforeEach(() => {
          invokedWorkspaceTrustFn = semver.gte(userVersion, "1.57.0");
        });

        it(`THEN onDidGrantWorkspaceTrust will not get invoked.`, () => {
          expect(invokedWorkspaceTrustFn).toEqual(false);
        });
      });
    });
  }
);
Example #11
Source File: request.spec.ts    From genshin-kit-node with Apache License 2.0 6 votes vote down vote up
describe('request.ts', () => {
  const app = new GenshinKit()
  app.loginWithCookie(env.HOYOLAB_COOKIE as string)

  it('Get user game role by cookie', async () => {
    let res = await app.request(
      'get',
      'https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie'
    )
    const user = res.data.list.find((item: any) =>
      ['hk4e_cn', 'hk4e_global'].includes(item.game_biz)
    )
    res = await app.request('get', 'index', {
      role_id: user.game_uid,
      server: user.region,
    })
    expect(res.retcode).to.equal(0)
  })
})
Example #12
Source File: DuplicationEventName.test.ts    From YoutubeLiveApp with MIT License 6 votes vote down vote up
describe(__filename, () => {
  it("イベント名に重複がないかをチェケラ", () => {
    eventNameList.reduce<string[]>((prev, current) => {
      chai.assert.isFalse(
        prev.some((eventName) => current === eventName),
        `EventNameが重複: ${current} in [${prev.join(", ")}]`
      );

      return [...prev, current];
    }, []);
  });
});
Example #13
Source File: DataModel.test.ts    From minecraft-schemas with MIT License 6 votes vote down vote up
describe('DataModel', () => {
	it('Delete last list item', () => {
		const schema = ObjectNode({
			extra: Opt(ListNode(
				StringNode()
			))
		})
		const model = new DataModel(schema)
		const root = new ModelPath(model, new Path([]))
		
		root.push('extra').set(['hello'])
		
		root.push('extra').push(0).set(undefined)
		
		assert(Object.keys(root.get()).length === 0)
	})
})
Example #14
Source File: buffer-utils.spec.ts    From mtcute with GNU Lesser General Public License v3.0 6 votes vote down vote up
describe('isProbablyPlainText', () => {
    it('should return true for buffers only containing printable ascii', () => {
        expect(
            isProbablyPlainText(Buffer.from('hello this is some ascii text'))
        ).to.be.true
        expect(
            isProbablyPlainText(
                Buffer.from(
                    'hello this is some ascii text\nwith unix new lines'
                )
            )
        ).to.be.true
        expect(
            isProbablyPlainText(
                Buffer.from(
                    'hello this is some ascii text\r\nwith windows new lines'
                )
            )
        ).to.be.true
        expect(
            isProbablyPlainText(
                Buffer.from(
                    'hello this is some ascii text\n\twith unix new lines and tabs'
                )
            )
        ).to.be.true
        expect(
            isProbablyPlainText(
                Buffer.from(
                    'hello this is some ascii text\r\n\twith windows new lines and tabs'
                )
            )
        ).to.be.true
    })

    it('should return false for buffers containing some binary data', () => {
        expect(isProbablyPlainText(Buffer.from('hello this is cedilla: ç'))).to
            .be.false
        expect(
            isProbablyPlainText(
                Buffer.from('hello this is some ascii text with emojis ?')
            )
        ).to.be.false

        // random strings of 16 bytes
        expect(
            isProbablyPlainText(
                Buffer.from('717f80f08eb9d88c3931712c0e2be32f', 'hex')
            )
        ).to.be.false
        expect(
            isProbablyPlainText(
                Buffer.from('20e8e218e54254c813b261432b0330d7', 'hex')
            )
        ).to.be.false
    })
})
Example #15
Source File: dueDate.test.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
describe('♻ Recurring with starting date', () => {
	const dueString = '2018-01-01|e2d';

	it(`${dueString} is due on the same day`, () => {
		assert.equal(new DueDate(dueString, { targetDate: new Date(2018, 0, 1) }).isDue, DueState.Due);
	});
	it(`${dueString} is not due on the next day`, () => {
		assert.equal(new DueDate(dueString, { targetDate: new Date(2018, 0, 2) }).isDue, DueState.NotDue);
	});
	it(`${dueString} is due in 2 days`, () => {
		assert.equal(new DueDate(dueString, { targetDate: new Date(2018, 0, 3) }).isDue, DueState.Due);
	});
});
Example #16
Source File: cache.test.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
describe('BlockCache', () => {
  const EXTRA_BLOCK_COUNT = 15;
  const TOTAL_BLOCKS = 80;
  const chain = mockChain(TOTAL_BLOCKS);
  let cache: BlockCache;

  beforeEach(() => {
    cache = new BlockCache(EXTRA_BLOCK_COUNT);
  });

  describe('initialization', () => {
    it('initialize two empty map', () => {
      expect(cache.blockToHashes).to.deep.equal({});
      expect(cache.hashToBlocks).to.deep.equal({});
    });
  });

  describe('add block', () => {
    it('correctly find cached transactions, and prune old blocks', () => {
      chain.forEach((transactions, latestBlockNumber) => {
        cache.addTxsAtBlock(latestBlockNumber, transactions);

        const firstBlockInCache = Math.max(0, latestBlockNumber - EXTRA_BLOCK_COUNT + 1);
        /* ---------- test inspect ---------- */
        const { cachedBlocks } = cache._inspect();
        expect(parseInt(cachedBlocks[0])).to.equal(firstBlockInCache);
        expect(parseInt(cachedBlocks[cachedBlocks.length - 1])).to.equal(latestBlockNumber);

        /* ---------- test getBlockNumber ---------- */
        for (let blockNumber = 0; blockNumber < TOTAL_BLOCKS; blockNumber++) {
          const isBlockInCache = blockNumber >= firstBlockInCache && blockNumber <= latestBlockNumber;

          for (const curTx of chain[blockNumber]) {
            expect(cache.getBlockNumber(curTx)).to.equal(isBlockInCache ? blockNumber : undefined);
          }
        }
      });
    });
  });
});
Example #17
Source File: backing.test.ts    From persistent-merkle-tree with Apache License 2.0 5 votes vote down vote up
describe("get", () => {
  it("should return the right node", () => {
    const n = subtreeFillToDepth(new LeafNode(Buffer.alloc(32, 1)), 3);
    const backing = new Tree(n);
    assert.deepEqual(backing.getRoot(8n), Buffer.alloc(32, 1));
  });
});
Example #18
Source File: bitcoincashtransactiontest.spec.ts    From edge-currency-plugins with MIT License 5 votes vote down vote up
describe('bitcoincash transaction creation and signing test', () => {
  // key with control on the unspent output and used to sign the transaction
  const wifKey = 'L2uPYXe17xSTqbCjZvL2DsyXPCbXspvcu5mHLDYUgzdUbZGSKrSr'
  const privateKey = wifToPrivateKey({
    wifKey,
    coin: 'bitcoin'
  })
  const scriptPubkey: string = pubkeyToScriptPubkey({
    pubkey: privateKeyToPubkey(privateKey),
    scriptType: ScriptTypeEnum.p2pkh
  }).scriptPubkey
  const address: string = scriptPubkeyToAddress({
    scriptPubkey: scriptPubkey,
    coin: 'bitcoin',
    addressType: AddressTypeEnum.p2pkh
  }).address
  it('Create transaction with one legacy input and one output', async () => {
    /*
      This here is the rawtransaction as assembled below:
      0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc5660209e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec631e5e1e66009ce3710ceea5b1ad13ffffffff01905f0100000000001976a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac00000000
      The test case deconstructs the value, script pubkey and locktime values to show some deserialized values.
      This deserialization is not required in the usual form from the caller.
      It is enough to pass the full previous rawtransaction.
    */
    const { psbtBase64 } = await makeTx({
      forceUseUtxo: [],
      coin: 'bitcoincash',
      setRBF: false,
      freshChangeAddress: address,
      feeRate: 0,
      subtractFee: false,
      utxos: [
        {
          id: '0',
          scriptType: ScriptTypeEnum.p2pkh,
          txid:
            '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e',
          scriptPubkey,
          value: '80000',
          blockHeight: 0,
          spent: false,
          script:
            '0200000001f9f34e95b9d5c8abcd20fc5bd4a825d1517be62f0f775e5f36da944d9' +
            '452e550000000006b483045022100c86e9a111afc90f64b4904bd609e9eaed80d48' +
            'ca17c162b1aca0a788ac3526f002207bb79b60d4fc6526329bf18a77135dc566020' +
            '9e761da46e1c2f1152ec013215801210211755115eabf846720f5cb18f248666fec' +
            '631e5e1e66009ce3710ceea5b1ad13ffffffff01' +
            // value in satoshis (Int64LE) = 0x015f90 = 90000
            '905f010000000000' +
            // scriptPubkey length
            '19' +
            // scriptPubkey
            scriptPubkey +
            // locktime
            '00000000',
          vout: 0
        }
      ],
      targets: []
    })
    const signedTx = await signTx({
      psbtBase64,
      privateKeys: [privateKey],
      coin: 'bitcoincash'
    })
    expect(signedTx.hex).to.equal(
      '02000000013ebc8203037dda39d482bf41ff3be955996c50d9d4f7cfc3d2097a694a7b067d000000006a473044022041e30e01f06523646374a356a61238da09f67cfbb5017ff7df47be7c5d1fc1bf0220788ed258f1b6d9c2b28d49c10909cd2cf48f49139c1bb9fe6bfd102f9bf4e44141210365db9da3f8a260078a7e8f8b708a1161468fb2323ffda5ec16b261ec1056f455ffffffff0180380100000000001976a9148bbc95d2709c71607c60ee3f097c1217482f518d88ac00000000'
    )
  })
})
Example #19
Source File: languageProcessing.test.ts    From context-mod with MIT License 5 votes vote down vote up
describe('Language Detection', function () {

    describe('Derives language from user input', async function () {
        it('gets from valid, case-insensitive alpha2', async function () {
            const lang = await getLanguageTypeFromValue('eN');
            assert.equal(lang.alpha2, 'en');
        });
        it('gets from valid, case-insensitive alpha3', async function () {
            const lang = await getLanguageTypeFromValue('eNg');
            assert.equal(lang.alpha2, 'en');
        });
        it('gets from valid, case-insensitive language name', async function () {
            const lang = await getLanguageTypeFromValue('EnGlIsH');
            assert.equal(lang.alpha2, 'en');
        });

        it('throws on invalid value', function () {
            assert.isRejected(getLanguageTypeFromValue('pofdsfa'))
        });
    })

    describe('Recognizes the language in moderately long content well', function () {
        it('should recognize english', async function () {
            const lang = await getContentLanguage(longPositiveEnglish);
            assert.equal(lang.language.alpha2, 'en');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize french', async function () {
            const lang = await getContentLanguage(longFrench);
            assert.equal(lang.language.alpha2, 'fr');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize spanish', async function () {
            const lang = await getContentLanguage(longSpanish);
            assert.equal(lang.language.alpha2, 'es');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize german', async function () {
            const lang = await getContentLanguage(longGerman);
            assert.equal(lang.language.alpha2, 'de');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize indonesian', async function () {
            const lang = await getContentLanguage(longIndonesian);
            assert.equal(lang.language.alpha2, 'id');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
    });

    describe('Correctly handles short content classification', function () {
        it('uses default language', async function () {

            for (const content of [shortIndistinctEnglish, shortIndistinctEnglish2, shortIndonesian]) {
                const lang = await getContentLanguage(content);
                assert.equal(lang.language.alpha2, 'en', content);
                assert.isTrue(lang.usedDefault, content);
            }
        });

        it('uses best guess when default language is not provided', async function () {

            for (const content of [shortIndistinctEnglish, shortIndistinctEnglish2, shortIndonesian]) {
                const lang = await getContentLanguage(content, {defaultLanguage: false});
                assert.isFalse(lang.usedDefault);
            }
        });
    });
});
Example #20
Source File: system_file.ts    From Daemon with GNU Affero General Public License v3.0 5 votes vote down vote up
describe("File management directory permissions", () => {
  const filemanager = new FileManager(process.cwd() + "/test_file");
  console.log(`[DEBUG] ABS_PATH: ${filemanager.topPath}`);

  describe("#checkPath()", () => {
    it("should return true", function () {
      assert.strictEqual(filemanager.checkPath("aaa"), true);
      assert.strictEqual(filemanager.checkPath("aaa/xzxzx"), true);
      assert.strictEqual(filemanager.checkPath("./xxxxx"), true);
      assert.strictEqual(filemanager.checkPath("./xxxxx/zzzz zz z/xxxxx xx /sssss"), true);
      assert.strictEqual(filemanager.checkPath("./xxxxx.txt"), true);
    });

    it("should return false", function () {
      assert.strictEqual(filemanager.checkPath("../a.txt"), false);
      assert.strictEqual(filemanager.checkPath("../"), false);
      assert.strictEqual(filemanager.checkPath("../..//"), false);
      assert.strictEqual(filemanager.checkPath("../xxxx/aaa"), false);
      assert.strictEqual(filemanager.checkPath("../../xxxx/aaa"), false);
    });

    it("Test file cwd", async () => {
      // filemanager.cd("test_file");
      console.log(`CWD IS: ${filemanager.cwd}`);
      assert.notStrictEqual(await filemanager.readFile("abc.txt"), "");
      assert.strictEqual(await filemanager.readFile("abc.txt"), "测试文件 123 ABC 哈哈");
      filemanager.cd("Test dir 1");
      console.log(`CWD IS: ${filemanager.cwd}`);
      assert.strictEqual(await filemanager.readFile("hello.txt"), "TEST_TEXT_TEST[][][][]\r\nTEST_TEXT_TEST");
      filemanager.cd("../Test dir 1");
      console.log(`CWD IS: ${filemanager.cwd}`);
      assert.strictEqual(await filemanager.readFile("hello.txt"), "TEST_TEXT_TEST[][][][]\r\nTEST_TEXT_TEST");
      filemanager.cd("../");
      console.log(`CWD IS: ${filemanager.cwd}`);
      assert.strictEqual(await filemanager.readFile("abc.txt"), "测试文件 123 ABC 哈哈");
      filemanager.cd("Test dir 1/Last/");
      console.log(`CWD IS: ${filemanager.cwd}`);
      assert.strictEqual(await filemanager.readFile("OK.txt"), "OKOKOK");
      assert.strictEqual(await filemanager.readFile("../hello.txt"), "TEST_TEXT_TEST[][][][]\r\nTEST_TEXT_TEST");
      assert.strictEqual(await filemanager.readFile("../../abc.txt"), "测试文件 123 ABC 哈哈");
      // assert.strictEqual(await filemanager.readFile("../../../../abc.txt"), "测试文件 123 ABC 哈哈");
      filemanager.cd("../");
      console.log("filemanager.list()", `CWD IS: ${filemanager.cwd}`);
      // console.log("filemanager.list():", filemanager.list())
    });
  });
});
Example #21
Source File: remarkable.test.ts    From reMarkable-typescript with MIT License 5 votes vote down vote up
describe('Upload Zip', async function () {
  it('passes the correct parameters to remarkable API', async function () {
    // SETUP
    localSandbox.stub(got, 'post').resolves(
      Promise.resolve({
        body: 'token',
      }),
    );
    const client = new Remarkable({
      deviceToken: 'stubToken',
    });
    await client.refreshToken();
    // configure stubbing for calls to the document apis
    const mockFileId = 'b8710f71-c86e-5037-8ef2-bac047709355';
    const mockFolderId = '71e70cd9-8d72-5c8b-addc-0d18c74364bc';
    const putStub = localSandbox
      .stub((client as any).gotClient, 'put')
      .resolves(Promise.resolve({ body: [{ Success: true, BlobURLPut: 'someURL' }] }))
      .onSecondCall()
      .resolves(Promise.resolve({ body: [{ Success: true, ID: mockFileId }] }));

    localSandbox.stub(client, 'getStorageUrl').resolves(await Promise.resolve('http://localhost'));

    localSandbox.stub(got, 'put').resolves(
      Promise.resolve({
        statusCode: 200,
        body: mockFileId,
      }),
    );

    const testEpub = Buffer.from('oogabooga');
    // ACT
    await client.uploadZip('testID', mockFileId, testEpub, mockFolderId);
    // ASSERT
    const argsToRmAPI = putStub.getCall(1).args[1];
    const unwrappedArgs = argsToRmAPI.json[0];
    expect(unwrappedArgs.parent).to.be.equal(mockFolderId);
    expect(unwrappedArgs.ID).to.be.equal(mockFileId);
    expect(unwrappedArgs.VissibleName).to.be.equal('testID');
    return;
  });
});
Example #22
Source File: LookupProviderV3.test.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
suite("LookupProviderV3 utility methods:", () => {
  describe(`shouldBubbleUpCreateNew`, () => {
    describe(`WHEN no special characters and no exact matches`, () => {
      let querystring: string;
      let numberOfExactMatches: number;

      beforeEach(() => {
        querystring = "simple-query-no-special-chars";
        numberOfExactMatches = 0;
      });

      it(`AND bubble up is omitted THEN bubble up`, () => {
        expect(
          shouldBubbleUpCreateNew({ querystring, numberOfExactMatches })
        ).toBeTruthy();

        expect(
          shouldBubbleUpCreateNew({
            querystring,
            numberOfExactMatches,
            bubbleUpCreateNew: undefined,
          })
        ).toBeTruthy();
      });

      it("AND bubble up is set to false THEN do NOT bubble up", () => {
        const actual = shouldBubbleUpCreateNew({
          querystring,
          numberOfExactMatches,
          bubbleUpCreateNew: false,
        });
        expect(actual).toBeFalsy();
      });

      it("AND bubble up is set to true THEN bubble up", () => {
        const actual = shouldBubbleUpCreateNew({
          querystring,
          numberOfExactMatches,
          bubbleUpCreateNew: true,
        });
        expect(actual).toBeTruthy();
      });
    });

    it(`WHEN special char is used THEN do NOT bubble up`, () => {
      const actual = shouldBubbleUpCreateNew({
        querystring: "query with space",
        numberOfExactMatches: 0,
      });
      expect(actual).toBeFalsy();
    });

    it(`WHEN number of exact matches is more than 0 THEN do NOT bubble up`, () => {
      const actual = shouldBubbleUpCreateNew({
        querystring: "query-val",
        numberOfExactMatches: 1,
      });
      expect(actual).toBeFalsy();
    });
  });

  describe(`sortBySimilarity`, () => {
    it("WHEN notes out of order THEN sort by similarity", async () => {
      const noteFactory = TestNoteFactory.defaultUnitTestFactory();

      const notes = [
        await noteFactory.createForFName("pkg.hi.components"),
        await noteFactory.createForFName("pkg.hi.arch"),
        await noteFactory.createForFName("pkg.hi.quickstart"),
      ];

      const sorted = sortBySimilarity(notes, "pkg.hi.arc");
      expect(sorted.map((sorted) => sorted.fname)).toEqual([
        "pkg.hi.arch",
        "pkg.hi.quickstart",
        "pkg.hi.components",
      ]);
    });
  });
});
Example #23
Source File: modules.spec.ts    From genshin-kit-node with Apache License 2.0 5 votes vote down vote up
getUid(app).then((uid) => {
  describe('GenshinKit modules', () => {
    it('getUserInfo', async () => {
      const res = await app.getUserInfo(uid)
      expect(res).to.be.an('object')
      expect(res.avatars).to.be.an('array')
    })

    it('getUserRoles', async () => {
      const res = await app.getUserRoles(uid)
      expect(res).to.be.an('array')
      expect(res[0].id).to.be.an('number')
      expect(res[0].name).to.be.an('string')
    })

    it('getAbyss', async () => {
      const res = await app.getAbyss(uid, 1)

      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1

      expect(res).to.be.an('object')
      expect(
        new Date(Number(res.start_time) * 1000)
          .toISOString()
          .startsWith(`${year}-${month}`)
      ).to.eq(true)
    })

    it('getActivities', async () => {
      const res = await app.getActivities(uid)
      expect(res).to.be.an('object')
      expect(res.activities).to.be.an('array')
    })

    it('getDailyNote', async () => {
      const res = await app.getDailyNote(uid)
      expect(res).to.be.an('object')
      // 原粹树脂应该介于 0 - 160
      // 暂时不考虑月亮嗑多了的情况
      expect(res.current_resin).to.lte(160)
      expect(res.current_resin).to.gte(0)
    })
  })
})
Example #24
Source File: idle-connection.spec.ts    From mtcute with GNU Lesser General Public License v3.0 5 votes vote down vote up
describe('e2e : idle connection', function () {

    this.timeout(120000)

    // 75s is to make sure ping is sent

    it('75s idle to test dc', async () => {
        const client = createTestTelegramClient()

        await client.connect()
        await sleep(75000)

        expect(client.primaryConnection['_transport'].state()).eq(TransportState.Ready)

        const config = await client.call({ _: 'help.getConfig' })
        expect(config._).eql('config')

        await client.close()
        expect(client.primaryConnection['_transport'].state()).eq(TransportState.Idle)
    })

    if (!process.env.USER_SESSION) {
        console.warn('Warning: skipping e2e idle connection test with auth (no USER_SESSION)')
        return
    }

    it('75s idle to test dc with auth', async () => {
        const client = createTestTelegramClient()

        client.importSession(process.env.USER_SESSION!)

        await client.connect()
        await sleep(75000)

        expect(client.primaryConnection['_transport'].state()).eq(TransportState.Ready)

        const config = await client.call({ _: 'help.getConfig' })
        expect(config._).eql('config')

        await client.close()
        expect(client.primaryConnection['_transport'].state()).eq(TransportState.Idle)
    })
})
Example #25
Source File: dueDate.test.ts    From vscode-todo-md with MIT License 5 votes vote down vote up
describe(`${headerDelimiter('due date')}Not recurring`, () => {
	it('Simple date format `2018-01-01` is due at that date.', () => {
		assert.equal($1jan2018mondayDueDate.isDue, DueState.Due);
	});
	it('`2018-01-01` is not recurring', () => {
		assert.isFalse($1jan2018mondayDueDate.isRecurring);
	});
});