vitest#it TypeScript Examples

The following examples show how to use vitest#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: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#isEmpty', () => {
  it('returns true if pad is empty', () => {
    const wrapper = shallowMount(VPerfectSignature)

    expect(wrapper.vm.isEmpty()).toBe(true)
  })

  it('returns false if pad is not empty', () => {
    const wrapper = shallowMount(VPerfectSignature)

    wrapper.setData({
      allInputPoints: inputPointsMockData,
    })

    expect(wrapper.vm.isEmpty()).toBe(false)
  })
})
Example #2
Source File: assert-known-address.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("assertKnownAddress", () => {
  const from = "0x0a7943653138accf65145bbfdf3dfbc124267a61";
  const addresses = [
    "0xbba0631f67f6eff9d5a86052244ee477dd85b010",
    "0x137e74c5986e81a26e76a7fe47553fe2f1361b57",
    "0x569a6dc26ba89b30f94708fddc5b760ed5974eaf",
  ];

  describe("when pass to known address", () => {
    it("nothing", async () => {
      assertKnownAddress(from, [from, ...addresses]);
    });
  });
  describe("when pass to unknown address", () => {
    it("throw error", async () => {
      expect(() => assertKnownAddress(from, addresses)).toThrow(
        /from is unknown address/
      );
    });
  });
});
Example #3
Source File: ethers-send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("ethers", () => {
  beforeEach(async () => {
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    const wallet = provider.getSigner();

    const signer = new KmsEthersSigner({ keyId, kmsClientConfig: { region } });

    await wallet.sendTransaction({
      to: await signer.getAddress(),
      value: ethers.utils.parseEther("1"),
    });
  });

  it("send eth", async () => {
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    const signer = new KmsEthersSigner({
      keyId,
      kmsClientConfig: { region },
    }).connect(provider);

    const target = crypto.randomBytes(20).toString("hex");

    const value = ethers.utils.parseEther("0.5");

    const transaction = await signer.sendTransaction({
      to: target,
      value,
    });

    await transaction.wait();

    const actual = await provider.getBalance(target);
    expect(actual.eq(value)).toBeTruthy();
  });
});
Example #4
Source File: web3-send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
it("web3.js", async () => {
  const target = crypto.randomBytes(20).toString("hex");
  const provider = new KmsProvider(rpcUrl, { region, keyIds: [keyId] });

  const web3 = new Web3(provider);
  const accounts = await web3.eth.getAccounts();

  const value = web3.utils.toWei("0.5", "ether");
  await web3.eth.sendTransaction({
    from: accounts[0],
    to: target,
    value,
  });

  await expect(web3.eth.getBalance(target)).resolves.toBe(value);
});
Example #5
Source File: web3-sign.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
it("web3.js", async () => {
  const provider = new KmsProvider(rpcUrl, { region, keyIds: [keyId] });

  const web3 = new Web3(provider);

  const accounts = await web3.eth.getAccounts();

  const message = "poyo";
  const signature = await web3.eth.sign(message, accounts[0]);

  await expect(web3.eth.personal.ecRecover(message, signature)).resolves.toBe(
    accounts[0].toLowerCase()
  );
  expect(web3.eth.accounts.recover(message, signature)).toBe(accounts[0]);
});
Example #6
Source File: normalize-url.test.ts    From osmosfeed with MIT License 6 votes vote down vote up
describe("normalizeUrl", () => {
  it("handles url that doesn't need encoding", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com")).toEqual("https://www.mockdomain.com");
  });

  it("handles url that needs encoding", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com/hello world")).toEqual(
      "https://www.mockdomain.com/hello%20world"
    );
  });

  it("handles url that is encoded", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com/hello%20world")).toEqual(
      "https://www.mockdomain.com/hello%20world"
    );
  });

  it("handles url unicode characters", async () => {
    await expect(normalizeUrl("https://www.你好.com?query=世界")).toEqual(
      "https://www.%E4%BD%A0%E5%A5%BD.com?query=%E4%B8%96%E7%95%8C"
    );
  });
});
Example #7
Source File: parse-public-key.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("parsePublicKey", () => {
  it("should be parse (AWS KMS)", () => {
    const bytes = Bytes.fromString(
      "3056301006072a8648ce3d020106052b8104000a034200046ce651c2445abd0915d97b683ff35cc6de4c340b8759918fd34cacf4395c39b0e2ad7517c9ab585ed5213ef0c00a1896f390eb03ff1ef8a13e18f036fa62a9e4"
    );

    const publicKey = parsePublicKey(bytes.buffer);

    const expected = Address.fromBytes(
      Bytes.fromString("0b45ff0aea02cb12b8923743ecebc83fe437c614")
    );

    expect(
      expected.equals(
        PublicKey.fromBytes(Bytes.fromArrayBuffer(publicKey)).toAddress()
      )
    );
  });

  it("should be parse (Cloud KMS)", () => {
    const bytes = Bytes.fromString(
      "3056301006072a8648ce3d020106052b8104000a03420004d4f664a42f91df474e4e97549f773a187ed85f93af9fc4053a29961d9c810ea33c8894a313631c7eee83916ef32ad5dbc321f06b1d600f039eee22488d6b48d1"
    );

    const publicKey = parsePublicKey(bytes.buffer);

    const expected = Address.fromBytes(
      Bytes.fromString("0x9f60980a13f74d79214e258d2f52fd846a3a5511")
    );

    expect(
      expected.equals(
        PublicKey.fromBytes(Bytes.fromArrayBuffer(publicKey)).toAddress()
      )
    );
  });
});
Example #8
Source File: processDatabase.test.ts    From kanel with MIT License 6 votes vote down vote up
describe('processDatabase', () => {
  it('should process the dvd rental example according to the snapshot', async () => {
    await processDatabase({
      connection: {},

      preDeleteModelFolder: false,

      customTypeMap: {
        tsvector: {
          name: 'TsVector',
          module: 'ts-vector',
          absoluteImport: true,
          defaultImport: true,
        },
        bpchar: 'string',
      },

      resolveViews: true,

      schemas: [
        {
          name: 'public',
          modelFolder: '/models',
          ignore: ['film_list', 'staff'],
        },
      ],
    });

    // @ts-ignore
    const results = writeFile.mock.calls;
    expect(results).toMatchSnapshot();
  });
});
Example #9
Source File: time.test.ts    From osmosfeed with MIT License 6 votes vote down vote up
describe("getOffsetFromTimezoneName", () => {
  it("handles url that doesn't need encoding", () => {
    // Note that the symbol is inverted from international convention
    // Source: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
    expect(getOffsetFromTimezoneName("Asia/Shanghai")).toBe(-480); // GMT+8
    expect(getOffsetFromTimezoneName("Asia/Tokyo")).toBe(-540); // GMT+9
    expect(getOffsetFromTimezoneName("UTC")).toBe(0);
    expect(getOffsetFromTimezoneName("EST")).toBe(300); // GMT-5
    expect(getOffsetFromTimezoneName("Pacific/Honolulu")).toBe(600); //GMT-10
  });
});
Example #10
Source File: index.spec.ts    From volar with MIT License 6 votes vote down vote up
describe(`vue-tsc`, () => {
	it(`vue-tsc no errors`,  () => new Promise((resolve, reject) => {
		const cp = fork(
			binPath,
			['--noEmit'],
			{
				silent: true,
				cwd: path.resolve(__dirname, '../../vue-test-workspace')
			},
		);

		cp.stdout.setEncoding('utf8');
		cp.stdout.on('data', (data) => {
			console.log(data);
		});
		cp.stderr.setEncoding('utf8');
		cp.stderr.on('data', (data) => {
			console.error(data);
		});

		cp.on('exit', (code) => {
			if(code === 0) {
				resolve();
			} else {
				reject(new Error(`Exited with code ${code}`));
			}
		});
 	}), 40_000);
});
Example #11
Source File: defineTypeCheck.ts    From volar with MIT License 6 votes vote down vote up
export function defineTypeCheck(fileName: string) {

	describe(`type check to ${path.relative(volarRoot, fileName)}`, () => {

		const uri = shared.fsPathToUri(fileName);
		const script = tester.host.getScriptSnapshot(fileName);

		let errors: vscode.Diagnostic[] | undefined;

		beforeAll(async () => {
			errors = await tester.languageService.doValidation(uri);
		});

		it(`should has script snapshot`, async () => {
			expect(!!script).toEqual(true);
		});

		it(`should has 0 errors`, async () => {
			if (errors?.length) {
				console.log(errors);
			}
			expect(errors?.length).toEqual(0);
		});
	});
}
Example #12
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#props', () => {
  it('should receive default props', () => {
    const wrapper = shallowMount(VPerfectSignature)

    const expectedWidth = '100%'
    const expectedHeight = '100%'
    const expectedPenColor = '#000'
    const expectedBackgroundColor = 'rgba(0,0,0,0)'
    const expectedStrokeOptions = {}

    expect(wrapper.props().width).toBe(expectedWidth)
    expect(wrapper.props().height).toBe(expectedHeight)
    expect(wrapper.props().penColor).toBe(expectedPenColor)
    expect(wrapper.props().backgroundColor).toBe(expectedBackgroundColor)
    expect(wrapper.props().strokeOptions).toEqual(expectedStrokeOptions)
  })
})
Example #13
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#toDataURL', () => {
  it('throws error if invalid type', () => {
    const wrapper = shallowMount(VPerfectSignature)

    expect(() => wrapper.vm.toDataURL('text/html')).toThrow()
  })

  it('returns undefined if pad is empty', () => {
    const wrapper = shallowMount(VPerfectSignature)

    expect(wrapper.vm.toDataURL()).toBeUndefined()
  })

  // TODO: Returns incorrect data url. Bug?
  // it('should return data uri', () => {
  //     const wrapper = shallowMount(VPerfectSignature)

  //     wrapper.setData({
  //         allInputPoints: inputPointsMockData
  //     })

  //     expect(wrapper.vm.toDataURL()).toBe(mockDataURL)
  // })
})
Example #14
Source File: markdown-image-parsing.test.ts    From obsidian-imgur-plugin with MIT License 6 votes vote down vote up
describe("isWrapped type predicate", () => {
  it("treats simple image as not-wrapped", () => {
    const matchedPieces = findImgurMarkdownImage(
      "![](https://i.imgur.com/m3RpPCV.png)",
      0
    ).mdImagePieces;
    expect(isWrapped(matchedPieces)).toBeFalsy();
  });

  it("correctly detects wrapped image", () => {
    const matchedPieces = findImgurMarkdownImage(
      "[![](https://i.imgur.com/m3RpPCVs.png)](https://i.imgur.com/m3RpPCV.png)",
      0
    ).mdImagePieces;
    expect(isWrapped(matchedPieces)).toBeTruthy();
  });
});
Example #15
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#fromDataURL', () => {
  it('should set signature from data uri', async() => {
    const wrapper = shallowMount(VPerfectSignature)
    await expect(wrapper.vm.fromDataURL(mockDataURL)).resolves.toBe(true)
  })

  spyOn(console, 'error').mockImplementation(() => {})

  it('fails if data uri is incorrect', async() => {
    const wrapper = shallowMount(VPerfectSignature)

    await expect(wrapper.vm.fromDataURL('random string')).rejects.toThrow(
      'Incorrect data uri provided',
    )
  })
})
Example #16
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#toData', () => {
  it('returns array of array input points', () => {
    const wrapper = shallowMount(VPerfectSignature)

    wrapper.setData({
      allInputPoints: inputPointsMockData,
    })

    expect(wrapper.vm.toData()).toEqual(inputPointsMockData)
  })

  it('should set signature from array of array of input points', () => {
    const wrapper = shallowMount(VPerfectSignature)

    expect(wrapper.vm.fromData(inputPointsMockData)).toBeUndefined()
    expect(wrapper.vm.toData()).toEqual(inputPointsMockData)
  })
})
Example #17
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#clear', () => {
  it('clears data structures and pad', () => {
    const wrapper = shallowMount(VPerfectSignature)

    wrapper.setData({
      allInputPoints: inputPointsMockData,
    })
    wrapper.vm.clear()

    expect(wrapper.vm.toData()).toEqual([])
  })
})
Example #18
Source File: send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("web3.js send-eth", () => {
  it.skip("CloudKmsSigner", async () => {
    const name =
      "projects/aws-kms-provider/locations/asia-northeast1/keyRings/for-e2e-test/cryptoKeys/for-e2e-test/cryptoKeyVersions/1";

    const cloudKmsSigner = new CloudKmsSigner(name);
    const provider = createProvider({ signers: [cloudKmsSigner], rpcUrl });
    const web3 = new Web3(provider as never);

    const accounts = await web3.eth.getAccounts();

    const target = crypto.randomBytes(20).toString("hex");

    await prepare(rpcUrl, accounts[0]);

    const value = web3.utils.toWei("0.1", "ether");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(accounts[0], target, value, web3);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(new BN(value))
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(new BN(value))).toBeTruthy();
  });

  it("AwsKmsSigner", async () => {
    const keyId = "e9005048-475f-4767-9f2d-0d1fb0c89caf";
    const region = "us-east-1";
    const awsKmsSigner = new AwsKmsSigner(keyId, { region });

    const provider = createProvider({ signers: [awsKmsSigner], rpcUrl });
    const web3 = new Web3(provider as never);

    const accounts = await web3.eth.getAccounts();

    const target = crypto.randomBytes(20).toString("hex");

    await prepare(rpcUrl, accounts[0]);

    const value = web3.utils.toWei("0.1", "ether");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(accounts[0], target, value, web3);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(new BN(value))
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(new BN(value))).toBeTruthy();
  });
});
Example #19
Source File: send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("ethers.js send-eth", () => {
  it.skip("CloudKmsSigner", async () => {
    const name =
      "projects/aws-kms-provider/locations/asia-northeast1/keyRings/for-e2e-test/cryptoKeys/for-e2e-test/cryptoKeyVersions/1";
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);

    const ethersSigner = await provider.getSigner();
    const cloudKmsSigner = new CloudKmsSigner(name);
    const cloudSigner = new EthersAdapter({ signer: cloudKmsSigner }).connect(
      provider
    );

    await sendEth(
      ethersSigner,
      await cloudSigner.getAddress(),
      ethers.utils.parseEther("1"),
      provider
    );

    const value = ethers.utils.parseEther("0.1");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(cloudSigner, dummyAddress, value, provider);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(value)
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(value)).toBeTruthy();
  });
  it("AwsKmsSigner", async () => {
    const keyId = "e9005048-475f-4767-9f2d-0d1fb0c89caf";
    const region = "us-east-1";
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);

    const ethersSigner = await provider.getSigner();
    const awsKmsSigner = new AwsKmsSigner(keyId, { region });
    const cloudSigner = new EthersAdapter({ signer: awsKmsSigner }).connect(
      provider
    );

    await sendEth(
      ethersSigner,
      await cloudSigner.getAddress(),
      ethers.utils.parseEther("1"),
      provider
    );

    const value = ethers.utils.parseEther("0.1");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(cloudSigner, dummyAddress, value, provider);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(value)
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(value)).toBeTruthy();
  });
});
Example #20
Source File: public-key.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("PublicKey", () => {
  describe("validate", () => {
    describe("when buffer.length isn't 64", () => {
      it("should be throw TypeError", () => {
        expect(() => PublicKey.fromBytes(Bytes.fromString("0xab"))).toThrow(
          TypeError
        );
      });
    });
  });

  describe("toAddress", () => {
    it("should be calculate address", () => {
      const bytes = Bytes.fromString(
        "20d55983d1707ff6e9ce32d583ad0f7acb3b0beb601927c4ff05f780787f377afe463d329f4535c82457f87df56d0a70e16a9442c6ff6d59b8f113d6073e9744"
      );
      const publicKey = PublicKey.fromBytes(bytes);
      expect(publicKey.toAddress()).toBeInstanceOf(Address);
      expect(publicKey.toAddress().toString()).toBe(
        "0x8e926dF9926746ba352F4d479Fb5DE47382e83bE"
      );
    });
  });

  describe("equals", () => {
    describe("when same public-key", () => {
      it("should be return true", () => {
        const bytes = Bytes.fromString(
          "20d55983d1707ff6e9ce32d583ad0f7acb3b0beb601927c4ff05f780787f377afe463d329f4535c82457f87df56d0a70e16a9442c6ff6d59b8f113d6073e9744"
        );
        const publicKey1 = PublicKey.fromBytes(bytes);
        const publicKey2 = PublicKey.fromBytes(bytes);

        expect(publicKey1.equals(publicKey2)).toBeTruthy();
        expect(publicKey2.equals(publicKey1)).toBeTruthy();
      });
    });
    describe("when different address", () => {
      it("should be return false", () => {
        const bytes1 = Bytes.fromString(
          "20d55983d1707ff6e9ce32d583ad0f7acb3b0beb601927c4ff05f780787f377afe463d329f4535c82457f87df56d0a70e16a9442c6ff6d59b8f113d6073e9744"
        );
        const bytes2 = Bytes.fromString(
          "377ada780e5cb7ddd628b02e5d1a9989ed8c0f83b81a4c2b4b861454367f8aade2fb2695b8480260ab6fdb8fd8db07cf6986aa789ce170e82d3fff9d31013982"
        );
        const publicKey1 = PublicKey.fromBytes(bytes1);
        const publicKey2 = PublicKey.fromBytes(bytes2);

        expect(publicKey1.equals(publicKey2)).toBeFalsy();
        expect(publicKey2.equals(publicKey1)).toBeFalsy();
      });
    });
  });
});
Example #21
Source File: get-common.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("getCommon", () => {
  const rpcUrl = "http://locahost:8545";

  const server = getServer(rpcUrl, []);

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  describe("when return gas", () => {
    const chainId = "0x1";

    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_chainId",
          result: chainId,
        })
      );
    });

    it("shoud be get common", async () => {
      const common = await getCommon(rpcUrl);

      expect(`0x${common.chainIdBN().toString("hex")}`).toBe(chainId);
    });
  });
  describe("when return null", () => {
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_estimateGas",
          result: null,
        })
      );
    });

    it("shoud be throw error", async () => {
      await expect(getCommon(rpcUrl)).rejects.toThrow(
        /can't get result of eth_chainId/
      );
    });
  });
});
Example #22
Source File: get-nonce.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("getNonce", () => {
  const rpcUrl = "http://locahost:8545";
  const from = "0x9f60980a13f74d79214E258D2F52Fd846A3a5511";

  const server = getServer(rpcUrl, []);

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  describe("when return nonce", () => {
    const nonce = "0x10";
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_getTransactionCount",
          result: nonce,
        })
      );
    });

    it("shoud be get nonce", async () => {
      await expect(getNonce(rpcUrl, from)).resolves.toBe(nonce);
    });
  });

  describe("when return null", () => {
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_getTransactionCount",
          result: null,
        })
      );
    });

    it("shoud be throw error", async () => {
      await expect(getNonce(rpcUrl, from)).rejects.toThrow(
        /can't get result of eth_getTransactionCount/
      );
    });
  });
});
Example #23
Source File: get-gas.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("getGas", () => {
  const rpcUrl = "http://locahost:8545";

  const server = getServer(rpcUrl, []);
  const txParams = { from: "0x9f60980a13f74d79214E258D2F52Fd846A3a5511" };

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  describe("when return gas", () => {
    const gas = "0x5208";

    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_estimateGas",
          result: gas,
        })
      );
    });

    it("shoud be get gas", async () => {
      await expect(getGas(rpcUrl, txParams)).resolves.toBe(gas);
    });
  });
  describe("when return null", () => {
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_estimateGas",
          result: null,
        })
      );
    });

    it("shoud be throw error", async () => {
      await expect(getGas(rpcUrl, txParams)).rejects.toThrow(
        /can't get result of eth_estimateGas/
      );
    });
  });
});
Example #24
Source File: config.test.ts    From d3-graph-controller with MIT License 5 votes vote down vote up
describe.concurrent('Config', () => {
  describe('can be defined', () => {
    it('using default values', () => {
      const config = defineGraphConfig()
      expect(config).toMatchSnapshot()
    })

    it('with deep merging', () => {
      const defaultConfig = defineGraphConfig()
      const customConfig = defineGraphConfig({
        simulation: {
          forces: {
            collision: {
              radiusMultiplier: 42,
            },
          },
        },
      })
      const customCollisionForce = customConfig.simulation.forces.collision
      expect(customCollisionForce).not.toBe(false)
      // @ts-expect-error It has been asserted that the force is not false
      expect(customCollisionForce.radiusMultiplier).toEqual(42)
      expect(customConfig).not.toEqual(defaultConfig)

      const customMerge = {
        ...defaultConfig,
        simulation: {
          ...defaultConfig.simulation,
          forces: {
            ...defaultConfig.simulation.forces,
            collision: {
              ...defaultConfig.simulation.forces.collision,
              radiusMultiplier: 42,
            },
          },
        },
      }
      expect(customMerge.simulation.forces).toStrictEqual(
        customConfig.simulation.forces
      )
    })
  })
})
Example #25
Source File: address.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("Address", () => {
  describe("toChecksumAddress", () => {
    it.each([
      "52908400098527886E0F7030069857D2E4169EE7",
      "8617E340B3D01FA5F11F306F4090FD50E238070D",
      "de709f2102306220921060314715629080e2fb77",
      "27b1fdb04752bbc536007a920d24acb045561c26",
      "5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
      "fB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
      "dbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB",
      "D1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb",
    ])("should be return correct address: %s", (testAddress) => {
      const address = Address.fromBytes(
        Bytes.fromString("52908400098527886E0F7030069857D2E4169EE7")
      );
      expect(address["toChecksumAddress"](testAddress.toLowerCase())).toBe(
        testAddress
      );
    });
  });

  describe("equals", () => {
    describe("when same address", () => {
      it("should be return true", () => {
        const addressBytes = Bytes.fromString(
          "52908400098527886E0F7030069857D2E4169EE7"
        );
        const address1 = Address.fromBytes(addressBytes);
        const address2 = Address.fromBytes(addressBytes);

        expect(address1.equals(address2)).toBeTruthy();
        expect(address2.equals(address1)).toBeTruthy();
      });
    });
    describe("when different address", () => {
      it("should be return false", () => {
        const addressBytes1 = Bytes.fromString(
          "52908400098527886E0F7030069857D2E4169EE7"
        );
        const addressBytes2 = Bytes.fromString(
          "8617E340B3D01FA5F11F306F4090FD50E238070D"
        );
        const address1 = Address.fromBytes(addressBytes1);
        const address2 = Address.fromBytes(addressBytes2);

        expect(address1.equals(address2)).toBeFalsy();
        expect(address2.equals(address1)).toBeFalsy();
      });
    });
  });

  describe("toString", () => {
    it("should be return string", () => {
      const address = Address.fromBytes(
        Bytes.fromString("52908400098527886E0F7030069857D2E4169EE7")
      );

      expect(address.toString()).toBe(
        "0x52908400098527886E0F7030069857D2E4169EE7"
      );
    });
  });

  describe("validation", () => {
    describe("when buffer.length isn't 20", () => {
      it("should be throw TypeError", () => {
        expect(() => Address.fromBytes(Bytes.fromString("0xab"))).toThrow(
          TypeError
        );
      });
    });
  });
});
Example #26
Source File: cloud-kms-signer.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("CloudKmsSigner", () => {
  let cloudKmsSigner: CloudKmsSigner;

  beforeEach(() => {
    cloudKmsSigner = new CloudKmsSigner("keyName");
  });

  describe("getPublicKey", () => {
    it("should be return public key", async () => {
      mockGetPublicKey(cloudKmsSigner["client"]);
      const publicKey = await cloudKmsSigner.getPublicKey();

      const expected = PublicKey.fromBytes(
        Bytes.fromString(
          "0xd4f664a42f91df474e4e97549f773a187ed85f93af9fc4053a29961d9c810ea33c8894a313631c7eee83916ef32ad5dbc321f06b1d600f039eee22488d6b48d1"
        )
      );
      expect(expected.equals(publicKey)).toBeTruthy();
    });

    describe("when incorrect crc32c value", () => {
      it("should be throw Error", async () => {
        mockGetPublicKey(cloudKmsSigner["client"], {
          pemCrc32c: { value: "42" },
        });

        await expect(cloudKmsSigner.getPublicKey()).rejects.toThrow(
          /CloudKmsSigner: failed to validate of crc32c publicKeyResponse.pem./
        );
      });
    });
  });

  describe("sign", () => {
    it("should be return signature", async () => {
      const hash = Bytes.fromString(
        "0x8f5c4a30797ff58826711013473057e15ab305046fc5d2f76699769ed30d40f6"
      );
      mockGetPublicKey(cloudKmsSigner["client"]);
      mockAsymmetricSign(cloudKmsSigner["client"]);

      const expected = Bytes.fromString(
        "0xf66b26e8370aead7cab0fedd9650705be79be165ba807b5e2d1b18030d726d234e77b43a05c5901c38ed60957bc38dadea4a6b91837815f197a520871fa53e721c"
      );
      const signature = await cloudKmsSigner.sign(hash);

      expect(expected.equals(signature.bytes)).toBeTruthy();
    });

    describe("when incorrect crc32c value", () => {
      it("should be throw Error", async () => {
        const hash = Bytes.fromString(
          "0x8f5c4a30797ff58826711013473057e15ab305046fc5d2f76699769ed30d40f6"
        );
        mockGetPublicKey(cloudKmsSigner["client"]);
        mockAsymmetricSign(cloudKmsSigner["client"], {
          signatureCrc32c: { value: "42" },
        });

        await expect(cloudKmsSigner.sign(hash)).rejects.toThrow(
          /CloudKmsSigner: failed to validate of crc32c signResponse.signature./
        );
      });
    });
  });
});
Example #27
Source File: parse-signature.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("parseSignature", () => {
  describe("when 142-length signature", () => {
    it("should be parse", () => {
      const bytes = Bytes.fromString(
        "304502201fa98c7c5f1b964a6b438d9283adf30519aaea2d1a2b25ac473ac0f85d6e08c0022100e26f7c547cf497959af070ec7c43ebdbb3e4341395912d6ccc950b43e886781b"
      );

      const signature = parseSignature(bytes.buffer);

      const r = Bytes.fromArrayBuffer(signature.r);
      const s = Bytes.fromArrayBuffer(signature.s);

      expect(
        r.equals(
          Bytes.fromString(
            "1fa98c7c5f1b964a6b438d9283adf30519aaea2d1a2b25ac473ac0f85d6e08c0"
          )
        )
      ).toBeTruthy();
      expect(
        s.equals(
          Bytes.fromString(
            "e26f7c547cf497959af070ec7c43ebdbb3e4341395912d6ccc950b43e886781b"
          )
        )
      ).toBeTruthy();

      expect(r.length).toBe(32);
      expect(s.length).toBe(32);
    });
  });
  describe("when 140-length signature", () => {
    it("should be parse", () => {
      const bytes = Bytes.fromString(
        "30440221009c68bf9b88814142fef77d95956b21625789c34fde9b853653b24fc23515577f021f74e3e4d71e7385ae71042b0f99f7fbbf66e7760dd513ed2fcea754e2a9131c"
      );

      const signature = parseSignature(bytes.buffer);

      const r = Bytes.fromArrayBuffer(signature.r);
      const s = Bytes.fromArrayBuffer(signature.s);

      expect(
        r.equals(
          Bytes.fromString(
            "9c68bf9b88814142fef77d95956b21625789c34fde9b853653b24fc23515577f"
          )
        )
      ).toBeTruthy();
      expect(
        s.equals(
          Bytes.fromString(
            "0074e3e4d71e7385ae71042b0f99f7fbbf66e7760dd513ed2fcea754e2a9131c"
          )
        )
      ).toBeTruthy();

      expect(r.length).toBe(32);
      expect(s.length).toBe(32);
    });
  });

  describe("when invalid input", () => {
    it("should be throw Error", () => {
      const bytes = Bytes.fromString("abcd");

      expect(() => parseSignature(bytes.buffer)).toThrow(
        /parseSignature: failed to parse/
      );
    });
  });
});
Example #28
Source File: importGenerator.test.ts    From kanel with MIT License 5 votes vote down vote up
describe('ImportGenerator', () => {
  it('should generate an import statement', () => {
    const ig = new ImportGenerator('/src');

    ig.addImport('func', true, '/src/lib/func', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual(["import func from './lib/func';"]);
  });

  it('should support various cases', () => {
    const ig = new ImportGenerator('/package/src');

    ig.addImport('defaultFunc', true, '/package/src/lib/defaultFunc', false);

    ig.addImport('namedFunc1', false, '/package/src/lib/namedFunc', false);
    ig.addImport('namedFunc2', false, '/package/src/lib/namedFunc', false);

    ig.addImport('pck', true, '/package/package.json', false);

    ig.addImport('sister', true, '/package/sister-src/sister', false);

    ig.addImport('defComb', true, '/package/src/comb', false);
    ig.addImport('defNamed1', false, '/package/src/comb', false);
    ig.addImport('defNamed2', false, '/package/src/comb', false);
    ig.addImport('defNamed3', false, '/package/src/comb', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import defaultFunc from './lib/defaultFunc';",
      "import { namedFunc1, namedFunc2 } from './lib/namedFunc';",
      "import pck from '../package.json';",
      "import sister from '../sister-src/sister';",
      "import defComb, { defNamed1, defNamed2, defNamed3 } from './comb';",
    ]);
  });

  it('should ignore duplicates', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('def', true, './pkg', false);
    ig.addImport('def', true, './pkg', false);

    ig.addImport('named1', false, './pkg', false);
    ig.addImport('named2', false, './pkg', false);
    ig.addImport('named1', false, './pkg', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import def, { named1, named2 } from './pkg';",
    ]);
  });

  it('should complain about multiple (different) default imports', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('def', true, './pkg', false);

    expect(() => ig.addImport('def2', true, './pkg', false)).toThrow(
      "Multiple default imports attempted: def and def2 from './pkg'"
    );
  });

  it('should support aboslute imports', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('path', true, 'path', true);
    ig.addImport('existsSync', false, 'fs', true);
    ig.addImport('mkDirSync', false, 'fs', true);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import path from 'path';",
      "import { existsSync, mkDirSync } from 'fs';",
    ]);
  });
});
Example #29
Source File: defineRename.ts    From volar with MIT License 5 votes vote down vote up
export function defineRename(action: {
	fileName: string,
	position: vscode.Position,
	newName: string,
	length: number,
}, expectedResult: Record<string, string>) {

	const fileName = action.fileName;
	const uri = shared.fsPathToUri(fileName);

	describe(`renaming ${path.basename(fileName)}`, () => {
		for (let i = 0; i < action.length; i++) {
			const location = `${path.relative(volarRoot, fileName)}:${action.position.line + 1}:${action.position.character + i + 1}`;
			it(`rename ${location} => ${action.newName}`, async () => {
				const result = await tester.languageService.doRename(
					uri,
					{ line: action.position.line, character: action.position.character + i },
					action.newName,
				);

				expect(!!result?.changes).toEqual(true);
				if (!result?.changes) return;

				expect(Object.keys(result.changes).length).toEqual(Object.keys(expectedResult).length);

				for (const fileName in expectedResult) {

					const textEdits = result?.changes?.[shared.fsPathToUri(fileName)];
					expect(!!textEdits).toEqual(true);
					if (!textEdits) continue;

					const renameScript = tester.host.getScriptSnapshot(fileName);
					expect(!!renameScript).toEqual(true);
					if (!renameScript) continue;

					const renameScriptText = renameScript.getText(0, renameScript.getLength());
					const renameScriptResult = TextDocument.applyEdits(TextDocument.create('', '', 0, renameScriptText), textEdits);
					expect(normalizedText(renameScriptResult)).toEqual(normalizedText(expectedResult[fileName]));

				}
			});
		}
	});
}