mocha#describe TypeScript Examples

The following examples show how to use mocha#describe. 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: utils.test.ts    From dendron with GNU Affero General Public License v3.0 7 votes vote down vote up
suite("Plugin Utils", function () {
  describe("PickerUtils", function () {
    const ctx = setupBeforeAfter(this);

    test("vault picker", function (done) {
      runLegacyMultiWorkspaceTest({
        ctx,
        postSetupHook: ENGINE_HOOKS.setupBasic,
        onInit: async ({ vaults }) => {
          const stub = sinon
            .stub(VSCodeUtils, "showQuickPick")
            .returns({} as any);
          await PickerUtilsV2.promptVault();
          const items: VaultPickerItem[] = vaults.map((vault) => ({
            vault,
            label: VaultUtils.getName(vault),
          }));
          expect(stub.calledOnceWith(items)).toBeTruthy();
          done();
        },
      });
    });
  });
});
Example #4
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 #5
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 #6
Source File: BlockReorderingServiceTest.ts    From DamnVulnerableCryptoApp with MIT License 6 votes vote down vote up
describe("BlockReorderingService", () => {

  before(TestContext.create);
  after(TestContext.reset);


  it("Should encrypt token", () => {
    expect(BlockReorderingService.encryptToken("dvca")).to.be.equal("4d04658c39fb48269dc741aa6b2c78c0");
  });



  it("Should decerypt token", () => {
    expect(BlockReorderingService.decryptToken("4d04658c39fb48269dc741aa6b2c78c0")).to.be.equal("dvca");
  });



  it("Should create token adn check that is admin", () => {
    const t = BlockReorderingService.createToken("dvca", true);
    expect(t).to.match(/[a-f0-9]{128}/);
    expect(BlockReorderingService.isAdmin(t)).to.be.true;

  });

});
Example #7
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 #8
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 #9
Source File: commands.spec.ts    From mops-vida-pm-watchdog with MIT License 6 votes vote down vote up
describe('Commands', () => {
  const cases: Record<string, Buffer> = {
    AA01AB: cmds.shutdown(),
    AA080005B7: cmds.setMeasurementInterval(5),
    AA0800782A: cmds.setMeasurementInterval(120),
    AA095F492A981D: cmds.setRTC(new Date('2020-08-28T16:02:32.000Z')),
    AA0AB4: cmds.readHistory(),
    AA0BB5: cmds.nextHistory(),
    AA1600C0: cmds.setMeasurementEnable(false),
    AA1601C1: cmds.setMeasurementEnable(true),
  };
  for (const [expected, packet] of Object.entries(cases)) {
    it(expected, () => {
      assert.equalBytes(packet, expected);
    });
  }
});
Example #10
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 #11
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 #12
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 #13
Source File: ConfigureCommand.test.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
suite("ConfigureCommand", () => {
  describe("basic", function () {
    const ctx = setupBeforeAfter(this);

    test("ok", (done) => {
      runLegacySingleWorkspaceTest({
        ctx,
        onInit: async ({ wsRoot }) => {
          await new ConfigureCommand().run();
          expect(
            VSCodeUtils.getActiveTextEditor()?.document.uri.fsPath.toLowerCase()
          ).toEqual(path.join(wsRoot, "dendron.yml").toLowerCase());
          done();
        },
      });
    });

    test.skip("diff dendronRoot", (done) => {
      runLegacySingleWorkspaceTest({
        ctx,
        configOverride: {
          [CONFIG.DENDRON_DIR.key]: "dendron",
        },
        onInit: async ({ wsRoot }) => {
          await new ConfigureCommand().run();
          expect(
            VSCodeUtils.getActiveTextEditor()?.document.uri.fsPath
          ).toEqual(path.join(wsRoot, "dendron", "dendron.yml"));
          done();
        },
      });
    });
  });
});
Example #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: AlgorithmNegotiationServiceTest.ts    From DamnVulnerableCryptoApp with MIT License 5 votes vote down vote up
describe("AlgorithmNegotiationService", () => {

  before(TestContext.create);
  after(TestContext.reset);

  describe("Generate JWT", () => {
    it("Should generate jwt", () => {
      const oneYearFromNow = new Date();
      const timestamp = 123123123;

      const jwt = AlgorithmNegotiationService.generateJWT("dvca", true, timestamp);

      expect(jwt);
      expect(jwt.header.alg).to.equal("HS256");
      expect(jwt.header.typ).to.equal("JWT");

      expect(jwt.payload.sub).to.equal("dvca");
      expect(jwt.payload.isAdmin).to.equal(true);
      expect(jwt.payload.iat).to.equal(123123);
    });

    it("Should generate jwt and convert to string", () => {
      const oneYearFromNow = new Date();
      const timestamp = 123123123;

      const jwt = AlgorithmNegotiationService.generateJWT("dvca", true, timestamp);
      expect(AlgorithmNegotiationService.JWTToString(jwt)).to.be.equal("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkdmNhIiwiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxMjMxMjN9.7c55y69UKqGX59tWMP-rFJ93vag3tqvpWoCyaC7sxyk");

    });
  });

  describe("parseToken", () => {
    it("Should parse and validate jwt", () => {
      const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkdmNhIiwiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxMjMxMjN9.7c55y69UKqGX59tWMP-rFJ93vag3tqvpWoCyaC7sxyk";
      const parsed = AlgorithmNegotiationService.parseToken(jwt);

      expect(parsed);
      expect(parsed.header.alg).to.equal("HS256");
      expect(parsed.header.typ).to.equal("JWT");

      expect(parsed.payload.sub).to.equal("dvca");
      expect(parsed.payload.isAdmin).to.equal(true);
      expect(parsed.payload.iat).to.equal(123123);
    });

    it("Should throw error because of bad signature", () => {
      const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkdmNhIiwiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxMjMxMjN9.7c55y69UKqGX59tWMP-rFJ93vag3tqvpWoCyaC7sxy";
      expect(() => AlgorithmNegotiationService.parseToken(jwt)).to.throw();
    });

    it("Should parse successfully token with alg none", () => {

      const jwt: JWT = { header: { alg: 'none', typ: "JWT", }, payload: { sub: 'dvca', iat: 123123, isAdmin: true }, signature: "" };

      const jwtString = AlgorithmNegotiationService.JWTToString(jwt);
      const parsed = AlgorithmNegotiationService.parseToken(jwtString);

      expect(parsed);
      expect(parsed.header.alg).to.equal("none");
      expect(parsed.header.typ).to.equal("JWT");

      expect(parsed.payload.sub).to.equal("dvca");
      expect(parsed.payload.isAdmin).to.equal(true);
      expect(parsed.payload.iat).to.equal(123123);

    });
  });



});
Example #20
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 #21
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 #22
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 #23
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 #24
Source File: ChangeWorkspace.test.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
// eslint-disable-next-line prefer-arrow-callback
suite("GIVEN ChangeWorkspace command", function () {
  describeMultiWS("WHEN command is gathering inputs", {}, () => {
    let showOpenDialog: sinon.SinonStub;

    beforeEach(async () => {
      const cmd = new ChangeWorkspaceCommand();
      showOpenDialog = sinon.stub(window, "showOpenDialog");
      await cmd.gatherInputs();
    });
    afterEach(() => {
      showOpenDialog.restore();
    });

    test("THEN file picker is opened", (done) => {
      expect(showOpenDialog.calledOnce).toBeTruthy();
      done();
    });
  });

  describeMultiWS("WHEN command is run", {}, (ctx) => {
    describe("AND a code workspace is selected", () => {
      let openWS: sinon.SinonStub;
      let newWSRoot: string;
      before(async () => {
        const { wsRoot: currentWSRoot } = getDWorkspace();
        openWS = sinon.stub(VSCodeUtils, "openWS").resolves();

        const out = await setupLegacyWorkspaceMulti({
          ctx,
          workspaceType: WorkspaceType.CODE,
        });
        newWSRoot = out.wsRoot;
        expect(newWSRoot).toNotEqual(currentWSRoot);

        const cmd = new ChangeWorkspaceCommand();
        sinon.stub(cmd, "gatherInputs").resolves({ rootDirRaw: newWSRoot });
        await cmd.run();
      });
      after(() => {
        openWS.restore();
      });

      test("THEN workspace is opened", (done) => {
        expect(openWS.calledOnce).toBeTruthy();
        expect(openWS.calledOnceWithExactly(newWSRoot));
        done();
      });
    });

    describe("AND a native workspace is selected", () => {
      let openWS: sinon.SinonStub;
      let newWSRoot: string;
      before(async () => {
        const { wsRoot: currentWSRoot } = getDWorkspace();
        openWS = sinon.stub(VSCodeUtils, "openWS").resolves();

        const out = await setupLegacyWorkspaceMulti({
          ctx,
          workspaceType: WorkspaceType.NATIVE,
        });
        newWSRoot = out.wsRoot;
        expect(newWSRoot).toNotEqual(currentWSRoot);

        const cmd = new ChangeWorkspaceCommand();
        sinon.stub(cmd, "gatherInputs").resolves({ rootDirRaw: newWSRoot });
        await cmd.run();
      });
      after(() => {
        openWS.restore();
      });

      test("THEN workspace is opened", (done) => {
        expect(openWS.calledOnce).toBeTruthy();
        expect(openWS.calledOnceWithExactly(newWSRoot));
        done();
      });
    });
  });
});