assert#AssertionError TypeScript Examples

The following examples show how to use assert#AssertionError. 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: nexpect.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function createUnexpectedEndError(message: string, remainingQueue: ExecutionStep[]) {
  const desc: string[] = remainingQueue.map(function (it) {
    return it.description;
  });
  var msg = message + '\n' + desc.join('\n');

  return new AssertionError({
    message: msg,
    expected: [],
    actual: desc,
  });
}
Example #2
Source File: nexpect.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function createExpectationError(expected: string | RegExp, actual: string) {
  var expectation;
  if (isRegExp(expected)) {
    expectation = 'to match ' + expected;
  } else {
    expectation = 'to contain ' + JSON.stringify(expected);
  }

  var err = new AssertionError({
    message: format('expected %j %s', actual, expectation),
    actual: actual,
    expected: expected,
  });
  return err;
}
Example #3
Source File: dategrid.ts    From calendar-hack with MIT License 6 votes vote down vote up
swapDow(dow1: dayOfWeek, dow2: dayOfWeek) {
        if (dow1 === dow2)
            return;

        const firstSelection = this.selectAll(dow1);
        const secondSelection = this.selectAll(dow2);
        if (firstSelection.length !== secondSelection.length) {
            throw new AssertionError({ message: `selection lengths do not match` })
        }

        for (let i = 0; i < firstSelection.length; i++) {
            this.swap(firstSelection[i], secondSelection[i]);
        }
    }
Example #4
Source File: hive-engine.utils.test.ts    From hive-keychain-extension with MIT License 5 votes vote down vote up
describe('hive-engine.utils tests:\n', () => {
  describe('Mocking HIVE APIs:\n', () => {
    afterAll(() => {
      jest.clearAllMocks();
    });

    describe('getUserBalance tests:\n', () => {
      test('Passing an existing account with tokens, must return balances object with the properties defined bellow', async () => {
        hsc.find = jest
          .fn()
          .mockReturnValueOnce(utilsT.fakeResponseHavingTokenBalances);
        const propertiesArray = [
          '_id',
          'account',
          'balance',
          'delegationsIn',
          'delegationsOut',
          'pendingUndelegations',
          'pendingUnstake',
          'stake',
          'symbol',
        ];
        const result = await HiveEngineUtils.getUserBalance(
          utilsT.userData.username,
        );
        expect(result).not.toBeNull();
        expect(result.length).toBeDefined();
        expect(result.length).not.toBe(0);
        propertiesArray.map((property) => {
          expect(result[0][property]).toBeDefined();
        });
      });
      test('Passing an existing account with no tokens, must return an empty array', async () => {
        hsc.find = jest.fn().mockReturnValueOnce([]);
        const result = await HiveEngineUtils.getUserBalance(
          utilsT.userData2.username,
        );
        expect(result.length).toBeDefined();
        expect(result.length).toBe(0);
      });

      test('Passing an non existing account must return an empty array', async () => {
        hsc.find = jest.fn().mockReturnValueOnce([]);
        const result = await HiveEngineUtils.getUserBalance(
          'NonExistingAccountName',
        );
        expect(result.length).toBeDefined();
        expect(result.length).toBe(0);
      });
    });

    describe('stakeToken tests:\n', () => {
      test('Trying to stake using a public active password must generate an error on DHive, before submitting the json', async () => {
        //NOTE: This test even when is not mocking do not rely on network connection as the failing condition will be catched by Dhive
        //before submitting the json, so can be considered as local test.
        const symbolToken = 'HIVE';
        const amount = '1';
        const activeAccountName = utilsT.userData.username;
        const showError = false;
        const expectedErrorMessage = 'private key network id mismatch';
        try {
          await HiveEngineUtils.stakeToken(
            utilsT.userData.encryptKeys.active,
            utilsT.userData.username,
            symbolToken,
            amount,
            activeAccountName,
          )
            .then((response) => {})
            .catch((e) => {
              if (showError) {
                console.log('Error:');
                console.log(e);
              }
              expect(e).toEqual(
                new AssertionError({
                  message: expectedErrorMessage,
                }),
              );
            });
        } catch (error) {
          if (showError) {
            console.log(error);
          }
        }
      });

      test('Trying to stake using the active password must return a valid TransactionConfirmation Object', async () => {
        HiveUtils.getClient().broadcast.json = jest
          .fn()
          .mockImplementationOnce((...args) => {
            return {
              id: '803e8c82a48d5c9a452df2eb96bf49996f300f06',
            };
          });
        const symbolToken = 'CTPM';
        const amount = '10';
        const activeAccountName = utilsT.userData.username;
        const response = await HiveEngineUtils.stakeToken(
          utilsT.userData.nonEncryptKeys.active,
          utilsT.userData.username,
          symbolToken,
          amount,
          activeAccountName,
        );
        expect(response.id).toBeDefined();
      });
    });

    describe('unstakeToken tests:\n', () => {
      test('Trying to unstake a token but using a public key, will fire a Dhive error before transmitting the json', async () => {
        //NOTE: This test even when is not mocking do not rely on network connection as the failing condition will be catched by Dhive
        //before submitting the json, so can be considered as local test.
        const symbolToken = 'HIVE';
        const amount = '1';
        const activeAccountName = utilsT.userData.username;
        const showError = false;
        const expectedErrorMessage = 'private key network id mismatch';
        try {
          await HiveEngineUtils.unstakeToken(
            utilsT.userData.encryptKeys.active,
            symbolToken,
            amount,
            activeAccountName,
          )
            .then((response) => {})
            .catch((e) => {
              if (showError) {
                console.log('Error:');
                console.log(e);
              }
              expect(e).toEqual(
                new AssertionError({
                  message: expectedErrorMessage,
                }),
              );
            });
        } catch (error) {
          if (showError) {
            console.log(error);
          }
        }
      });

      test('Trying to unstake using the active password must return a valid TransactionConfirmation Object', async () => {
        HiveUtils.getClient().broadcast.json = jest
          .fn()
          .mockImplementationOnce((...args) => {
            return {
              id: '803e8c82a48d5c9a452df2eb96bf49996f300f06',
            };
          });
        const symbolToken = 'CTPM';
        const amount = '10';
        const activeAccountName = utilsT.userData.username;
        const response = await HiveEngineUtils.unstakeToken(
          utilsT.userData.nonEncryptKeys.active,
          symbolToken,
          amount,
          activeAccountName,
        );
        expect(response.id).toBeDefined();
      });
    });

    describe('delegateToken tests:\n', () => {
      test('Trying to delegate a token but using a public key, will fire a Dhive error before transmitting the json', async () => {
        //NOTE: This test even when is not mocking do not rely on network connection as the failing condition will be catched by Dhive
        //before submitting the json, so can be considered as local test.
        const symbolToken = 'HIVE';
        const amount = '1000';
        const activeAccountName = utilsT.userData.username;
        const showError = false;
        const expectedErrorMessage = 'private key network id mismatch';
        try {
          await HiveEngineUtils.delegateToken(
            utilsT.userData.encryptKeys.active,
            utilsT.userData2.username,
            symbolToken,
            amount,
            activeAccountName,
          )
            .then((response) => {})
            .catch((e) => {
              if (showError) {
                console.log('Error:');
                console.log(e);
              }
              expect(e).toEqual(
                new AssertionError({
                  message: expectedErrorMessage,
                }),
              );
            });
        } catch (error) {
          if (showError) {
            console.log(error);
          }
        }
      });

      test('Trying to delegate using the active password must return a valid TransactionConfirmation Object', async () => {
        HiveUtils.getClient().broadcast.json = jest
          .fn()
          .mockImplementationOnce((...args) => {
            return {
              id: '803e8c82a48d5c9a452df2eb96bf49996f300f06',
            };
          });
        const symbolToken = 'CTPM';
        const amount = '10';
        const activeAccountName = utilsT.userData.username;
        const response = await HiveEngineUtils.delegateToken(
          utilsT.userData.nonEncryptKeys.active,
          utilsT.userData2.username,
          symbolToken,
          amount,
          activeAccountName,
        );
        expect(response.id).toBeDefined();
      });
    });

    describe('cancelDelegationToken tests:\n', () => {
      test('Trying to cancel a delegation of a token but using a public key, will fire a Dhive error before transmitting the json', async () => {
        //NOTE: This test even when is not mocking do not rely on network connection as the failing condition will be catched by Dhive
        //before submitting the json, so can be considered as local test.
        const symbolToken = 'HIVE';
        const amount = '1000';
        const activeAccountName = utilsT.userData.username;
        const showError = false;
        const expectedErrorMessage = 'private key network id mismatch';
        try {
          await HiveEngineUtils.cancelDelegationToken(
            utilsT.userData.encryptKeys.active,
            utilsT.userData2.username,
            symbolToken,
            amount,
            activeAccountName,
          )
            .then((response) => {})
            .catch((e) => {
              if (showError) {
                console.log('Error:');
                console.log(e);
              }
              expect(e).toEqual(
                new AssertionError({
                  message: expectedErrorMessage,
                }),
              );
            });
        } catch (error) {
          if (showError) {
            console.log(error);
          }
        }
      });

      test('Trying to cancel a delegation using the active password must return a valid TransactionConfirmation Object', async () => {
        HiveUtils.getClient().broadcast.json = jest
          .fn()
          .mockImplementationOnce((...args) => {
            return {
              id: '803e8c82a48d5c9a452df2eb96bf49996f300f06',
            };
          });
        const symbolToken = 'CTPM';
        const amount = '10';
        const activeAccountName = utilsT.userData.username;
        const response = await HiveEngineUtils.cancelDelegationToken(
          utilsT.userData.nonEncryptKeys.active,
          utilsT.userData2.username,
          symbolToken,
          amount,
          activeAccountName,
        );
        expect(response.id).toBeDefined();
      });
    });

    describe('getIncomingDelegations tests:\n', () => {
      test('Passing a valid token symbol and account that has delegations must return an array of results', async () => {
        hsc.find = jest
          .fn()
          .mockResolvedValueOnce(utilsT.fakeIncommingDelegations);
        const response = await HiveEngineUtils.getIncomingDelegations(
          'BEE',
          'upfundme',
        );
        expect(response.length).not.toBe(0);
      });
      test('Passing a valid token symbol and account that No has delegations must return an empty array', async () => {
        hsc.find = jest.fn().mockResolvedValueOnce([]);
        const response = await HiveEngineUtils.getIncomingDelegations(
          'BEE',
          'upfundme',
        );
        expect(response.length).toBe(0);
      });
    });

    describe('getOutgoingDelegations tests:\n', () => {
      test('Passing a valid token symbol and account that has made delegations, must return an array of results', async () => {
        hsc.find = jest
          .fn()
          .mockResolvedValueOnce(utilsT.fakeOutgoingDelegations);
        const response = await HiveEngineUtils.getOutgoingDelegations(
          'BEE',
          'coininstant',
        );
        expect(response.length).not.toBe(0);
        expect(response[0].quantity).toBeDefined();
      });
      test('Passing a valid token symbol and account that has no made delegations, must return an empty array', async () => {
        hsc.find = jest.fn().mockResolvedValueOnce([]);
        const response = await HiveEngineUtils.getOutgoingDelegations(
          'BEE',
          'upfundme',
        );
        expect(response.length).toBe(0);
      });
    });

    describe('sendToken tests:\n', () => {
      type SendTokenProps = {
        username: string;
        currency: string;
        to: string;
        amount: string;
        memo: string;
      };
      test('Passing requested data, must broadcast the json and return a valid TransactionConfirmation Object', async () => {
        HiveUtils.getClient().broadcast.json = jest
          .fn()
          .mockImplementationOnce((...args) => {
            return {
              id: '803e8c82a48d5c9a452df2eb96bf49996f300f06',
            };
          });
        const data: SendTokenProps = {
          username: utilsT.userData.username,
          currency: 'BEE',
          to: utilsT.userData2.username,
          amount: '10.000',
          memo: 'This is a Test.',
        };
        const privateKey = PrivateKey.fromString(
          utilsT.userData.nonEncryptKeys.active,
        );
        const result = await HiveEngineUtils.sendToken(data, privateKey);
        expect(result.id).toBeDefined();
      });
    });
  });
});
Example #5
Source File: hive.utils.test.ts    From hive-keychain-extension with MIT License 5 votes vote down vote up
describe('hive.utils tests:\n', () => {
  describe('getClient tests:\n', () => {
    test('calling getclient must return an instance of Client', () => {
      const getClientObj = HiveUtils.getClient();
      expect(getClientObj instanceof Client).toBe(true);
      expect(getClientObj.address).toBeDefined();
    });
  });
  describe('setRpc tests:\n', () => {
    test('Passing uri as "DEFAULT" will set the uri of the Client class as the return value from KeychainApi.get', async () => {
      const returnedUriValue = 'https://ValueFromHive/rpc/api';
      KeychainApi.get = jest
        .fn()
        .mockResolvedValueOnce({ data: { rpc: returnedUriValue } });
      const fakeRpc: Rpc = {
        uri: 'DEFAULT',
        testnet: true,
      };
      expect(HiveUtils.getClient().address).toBe('https://api.hive.blog');
      const result = await HiveUtils.setRpc(fakeRpc);
      expect(result).toBeUndefined();
      expect(HiveUtils.getClient().address).toBe(returnedUriValue);
    });

    test('Passing uri different from "DEFAULT" will override the uri value on the Client Class', async () => {
      const overridingValue = 'https://overridingValue/rpc/api';
      const fakeRpc: Rpc = {
        uri: overridingValue,
        testnet: true,
      };
      expect(HiveUtils.getClient().address).toBe('https://api.hive.blog');
      const result = await HiveUtils.setRpc(fakeRpc);
      expect(result).toBeUndefined();
      expect(HiveUtils.getClient().address).toBe(overridingValue);
    });
  });

  describe('getVP tests:\n', () => {
    test('Passing an ExtendedAccount Obj with no account property must return null', () => {
      const fakeExtended = {} as ExtendedAccount;
      const result = HiveUtils.getVP(fakeExtended);
      expect(result).toBeNull();
    });
    test('Passing a valid ExtendedAccount Obj with 0 values, will return NaN', () => {
      const fakeExtendedData = {
        name: utilsT.dataUserExtended.name,
        vesting_withdraw_rate: '0.000 VESTS',
        voting_manabar: {
          current_mana: 0,
          last_update_time: 0, //1615046820
        },
        vesting_shares: '0.000 VESTS',
        delegated_vesting_shares: '0.000 VESTS',
        received_vesting_shares: '0.000 VESTS',
      } as ExtendedAccount;
      const result = HiveUtils.getVP(fakeExtendedData);
      expect(result).toBe(NaN);
    });
    test('Passing a valid ExtendedAccount Obj(cedricDataSample) with specific values, must return and estimated_pct=100', () => {
      const fakeExtendedData = {
        name: utilsT.cedricDataSample.name,
        vesting_withdraw_rate: utilsT.cedricDataSample.vesting_withdraw_rate,
        voting_manabar: utilsT.cedricDataSample.voting_manabar,
        vesting_shares: utilsT.cedricDataSample.vesting_shares,
        delegated_vesting_shares:
          utilsT.cedricDataSample.delegated_vesting_shares,
        received_vesting_shares:
          utilsT.cedricDataSample.received_vesting_shares,
      } as ExtendedAccount;
      const result = HiveUtils.getVP(fakeExtendedData);
      expect(result).toBe(100);
    });
  });

  describe('getVotingDollarsPerAccount tests:\n', () => {
    const price = new Price(new Asset(0.49, 'HBD'), new Asset(1, 'HIVE'));
    const rewardFund: RewardFund = {
      id: 0,
      name: 'post',
      reward_balance: '794370.819 HIVE',
      recent_claims: '618003654293909260',
      last_update: '2022-05-13T13:59:27',
      content_constant: '2000000000000',
      percent_curation_rewards: 5000,
      percent_content_rewards: 10000,
      author_reward_curve: 'linear',
      curation_reward_curve: 'linear',
    };
    const properties: GlobalProperties = {
      globals: utilsT.dynamicPropertiesObj,
      price: price,
      rewardFund: rewardFund,
    };
    const fakeExtendedData = {
      name: utilsT.cedricDataSample.name,
      vesting_withdraw_rate: utilsT.cedricDataSample.vesting_withdraw_rate,
      voting_manabar: utilsT.cedricDataSample.voting_manabar,
      vesting_shares: utilsT.cedricDataSample.vesting_shares,
      delegated_vesting_shares:
        utilsT.cedricDataSample.delegated_vesting_shares,
      received_vesting_shares: utilsT.cedricDataSample.received_vesting_shares,
    } as ExtendedAccount;
    test('Passing the testing data above, must return a voteValue="0.12"', async () => {
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).not.toBeNull();
      expect(result).toBe('0.12');
    });
    test('Passing the testing data above, but with voteWeight=50, must return a voteValue="0.06"', async () => {
      const result = HiveUtils.getVotingDollarsPerAccount(
        50,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).not.toBeNull();
      expect(result).toBe('0.06');
    });
    test('Passing the testing data above, but with voteWeight=0, must return a voteValue="0.00"', async () => {
      const result = HiveUtils.getVotingDollarsPerAccount(
        0,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).not.toBeNull();
      expect(result).toBe('0.00');
    });
    test('Passing a GlobalProperties without globals property, must return null', () => {
      const _properties = {} as GlobalProperties;
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        _properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBeNull();
    });
    test('Passing an Extended Account without name property must return null', () => {
      const _fakeExtendedData = {} as ExtendedAccount;
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        _fakeExtendedData,
        false,
      );
      expect(result).toBeNull();
    });
    test('If getRewardBalance returns 0, must return undefined', () => {
      const spyGetRewardBalance = jest
        .spyOn(HiveUtils, 'getRewardBalance')
        .mockReturnValueOnce(0);
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBeUndefined();
      expect(spyGetRewardBalance).toBeCalledTimes(1);
      expect(spyGetRewardBalance).toBeCalledWith(properties);
    });
    test('If getRecentClaims returns 0, must return undefined', () => {
      const spyGetRecentClaims = jest
        .spyOn(HiveUtils, 'getRecentClaims')
        .mockReturnValueOnce(0);
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBeUndefined();
      expect(spyGetRecentClaims).toBeCalledTimes(1);
      expect(spyGetRecentClaims).toBeCalledWith(properties);
    });
    test('If getHivePrice returns 0, must return undefined', () => {
      const spyGetHivePrice = jest
        .spyOn(HiveUtils, 'getHivePrice')
        .mockReturnValueOnce(0);
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBeUndefined();
      expect(spyGetHivePrice).toBeCalledTimes(1);
      expect(spyGetHivePrice).toBeCalledWith(properties);
    });
    test('If getVotePowerReserveRate returns 0, must return undefined', () => {
      const spyGetVotePowerReserveRate = jest
        .spyOn(HiveUtils, 'getVotePowerReserveRate')
        .mockReturnValueOnce(0);
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBeUndefined();
      expect(spyGetVotePowerReserveRate).toBeCalledTimes(1);
      expect(spyGetVotePowerReserveRate).toBeCalledWith(properties);
    });
    test('If getRewardBalance returns Infinity, will return "Infinity"', () => {
      const spyGetRewardBalance = jest
        .spyOn(HiveUtils, 'getRewardBalance')
        .mockReturnValueOnce(Infinity);
      const result = HiveUtils.getVotingDollarsPerAccount(
        100,
        properties,
        fakeExtendedData,
        false,
      );
      expect(result).toBe('Infinity');
      expect(spyGetRewardBalance).toBeCalledTimes(1);
      expect(spyGetRewardBalance).toBeCalledWith(properties);
    });
  });

  describe('getTimeBeforeFull tests:\n', () => {
    test('Passing a votingPower=100.0 must return the message "popup_utils_full" from i18n', () => {
      const expectedMessage = 'popup_utils_full';
      chrome.i18n.getMessage = jest.fn().mockImplementationOnce((...args) => {
        return args;
      });
      const result = HiveUtils.getTimeBeforeFull(100.0);
      expect(result).not.toBeNull();
      expect(result).toEqual([expectedMessage]);
    });
    test('Passing different values of votingPower(votingPowerArrayTest) must return the expectedMessageArray', () => {
      const showIteration = false;
      const votingPowerArrayTest = [...utilsT.votingPowerArrayTest];
      chrome.i18n.getMessage = jest.fn().mockImplementation((...args) => {
        return args;
      });
      votingPowerArrayTest.forEach((testCase) => {
        if (showIteration) {
          console.log(
            `About to test, votingPower: ${testCase.votingPower}\nMust return: ${testCase.expectedMessageArray}`,
          );
        }
        expect(HiveUtils.getTimeBeforeFull(testCase.votingPower)).toEqual(
          testCase.expectedMessageArray,
        );
      });
    });
    test('Passing a negative votingPower value will return undefined', () => {
      chrome.i18n.getMessage = jest.fn().mockImplementationOnce((...args) => {
        return args;
      });
      const result = HiveUtils.getTimeBeforeFull(-50.0);
      expect(result).toBeUndefined();
    });
  });

  describe('getConversionRequests tests:\n', () => {
    test('Fecthing 2 arrays(hbdConversions, hiveConversions) must order them by convertion_date and reestructure hiveConversions Array, and return one new array', async () => {
      const expectedNewArray = [
        {
          amount: '22.500 HIVE',
          collaterized: true,
          conversion_date: '2022-05-10T11:02:09',
          id: 275431,
          owner: 'wesp05',
          requestid: 1,
        },
        {
          amount: '2.500 HBD',
          conversion_date: '2022-05-15T11:02:09',
          id: 275431,
          owner: 'wesp05',
          requestid: 1,
        },
      ];
      HiveUtils.getClient().database.call = jest
        .fn()
        .mockImplementation((...args) => {
          if (args[0] === 'get_conversion_requests') {
            return utilsT.fakeHbdConversionsResponse;
          } else if (args[0] === 'get_collateralized_conversion_requests') {
            return utilsT.fakeHiveConversionsResponse;
          }
        });
      const result = await HiveUtils.getConversionRequests('wesp05');
      expect(result).toEqual(expectedNewArray);
    });
    test('Fetching 1 arrays(hiveConversions) will reestructure hiveConversions Array, and return one new array', async () => {
      const expectedNewArray = [
        {
          amount: '22.500 HIVE',
          collaterized: true,
          conversion_date: '2022-05-10T11:02:09',
          id: 275431,
          owner: 'wesp05',
          requestid: 1,
        },
      ];
      HiveUtils.getClient().database.call = jest
        .fn()
        .mockImplementation((...args) => {
          if (args[0] === 'get_conversion_requests') {
            return [];
          } else if (args[0] === 'get_collateralized_conversion_requests') {
            return utilsT.fakeHiveConversionsResponse;
          }
        });
      const result = await HiveUtils.getConversionRequests('wesp05');
      expect(result).toEqual(expectedNewArray);
    });
    test('Fetching 2 empty arrays will return an empty array', async () => {
      HiveUtils.getClient().database.call = jest
        .fn()
        .mockImplementation((...args) => {
          if (args[0] === 'get_conversion_requests') {
            return [];
          } else if (args[0] === 'get_collateralized_conversion_requests') {
            return [];
          }
        });
      const result = await HiveUtils.getConversionRequests('wesp05');
      expect(result).toEqual([]);
    });
    test('If hiveConversions lack one of the used properties, will return an array with undefined values', async () => {
      HiveUtils.getClient().database.call = jest
        .fn()
        .mockImplementation((...args) => {
          if (args[0] === 'get_conversion_requests') {
            return [];
          } else if (args[0] === 'get_collateralized_conversion_requests') {
            return [{ anyOther: 'anyOther' }];
          }
        });
      const result = await HiveUtils.getConversionRequests('wesp05');
      expect(result).toEqual([
        {
          amount: undefined,
          collaterized: true,
          conversion_date: undefined,
          id: undefined,
          owner: undefined,
          requestid: undefined,
        },
      ]);
    });
  });

  describe('getDelegators tests:\n', () => {
    test('Passing an account with delegators must return an array of results', async () => {
      const spyKeychainApiGet = jest.spyOn(KeychainApi, 'get');
      spyKeychainApiGet.mockResolvedValueOnce({
        data: utilsT.fakeGetDelegatorsResponse,
      });
      const username = 'blocktrades';
      const result = await getDelegators(username);
      expect(result.length).toBeDefined();
      expect(spyKeychainApiGet).toBeCalledTimes(1);
      expect(spyKeychainApiGet).toBeCalledWith(`/hive/delegators/${username}`);
    });
    test('Passing an account with No delegators must return an Empty array', async () => {
      const spyKeychainApiGet = jest.spyOn(KeychainApi, 'get');
      spyKeychainApiGet.mockResolvedValueOnce({ data: [] });
      const username = 'blocktrades';
      const result = await getDelegators(username);
      expect(result.length).toBeDefined();
      expect(result.length).toBe(0);
      expect(spyKeychainApiGet).toBeCalledTimes(1);
      expect(spyKeychainApiGet).toBeCalledWith(`/hive/delegators/${username}`);
    });
    test('Passing an account with delegators must return an array filtered and sorted, see conditions bellow', async () => {
      //To filter (vesting_shares !== 0)
      //To order (b.vesting_shares - a.vesting_shares)
      const spyKeychainApiGet = jest.spyOn(KeychainApi, 'get');
      spyKeychainApiGet.mockResolvedValueOnce({
        data: [
          {
            delegation_date: '2017-08-09T15:30:36.000Z',
            delegator: 'kriborin',
            vesting_shares: 0,
          },
          {
            delegation_date: '2017-08-09T15:29:42.000Z',
            delegator: 'kevtorin',
            vesting_shares: 1000.0,
          },
          {
            delegation_date: '2017-08-09T15:31:48.000Z',
            delegator: 'lessys',
            vesting_shares: 1000000.0,
          },
        ],
      });
      const expectedArrayOrdered = [
        {
          delegation_date: '2017-08-09T15:31:48.000Z',
          delegator: 'lessys',
          vesting_shares: 1000000,
        },
        {
          delegation_date: '2017-08-09T15:29:42.000Z',
          delegator: 'kevtorin',
          vesting_shares: 1000,
        },
      ] as Delegator[];
      const username = 'blocktrades';
      const result = await getDelegators(username);
      expect(result.length).toBe(2);
      expect(result).toEqual(expectedArrayOrdered);
      expect(spyKeychainApiGet).toBeCalledTimes(1);
      expect(spyKeychainApiGet).toBeCalledWith(`/hive/delegators/${username}`);
    });
  });

  describe('getDelegatees tests:\n', () => {
    test('Passing an account with delegators must return an array filtered and sorted, see conditions bellow', async () => {
      //To filter parseFloat(e.vesting_shares + '') !== 0
      //To order parseFloat(b.vesting_shares + '') - parseFloat(a.vesting_shares + '')
      let mockedGetVestingDelegations =
        (HiveUtils.getClient().database.getVestingDelegations = jest.fn());
      const username = 'blocktrades';
      mockedGetVestingDelegations.mockResolvedValueOnce(
        utilsT.fakeGetDelegateesResponse,
      );
      const argumentsCallingApi = [username, '', 1000];
      const expectedArrayOrdered = [
        {
          id: 1350016,
          delegator: 'blocktrades',
          delegatee: 'usainvote',
          vesting_shares: '300.000000 VESTS',
          min_delegation_time: '2020-08-16T05:34:33',
        },
        {
          id: 933999,
          delegator: 'blocktrades',
          delegatee: 'ocdb',
          vesting_shares: '200.902605 VESTS',
          min_delegation_time: '2018-05-25T22:14:30',
        },
        {
          id: 270663,
          delegator: 'blocktrades',
          delegatee: 'buildawhale',
          vesting_shares: '100.000000 VESTS',
          min_delegation_time: '2017-09-29T02:19:03',
        },
      ];
      const result = await getDelegatees(username);
      expect(result.length).toBe(3);
      expect(result).toEqual(expectedArrayOrdered);
      expect(mockedGetVestingDelegations).toBeCalledTimes(1);
      expect(mockedGetVestingDelegations).toBeCalledWith(
        ...argumentsCallingApi,
      );
    });
    test('Passing an account with No delegators must return an Empty array', async () => {
      let mockedGetVestingDelegations =
        (HiveUtils.getClient().database.getVestingDelegations = jest.fn());
      mockedGetVestingDelegations.mockResolvedValueOnce([]);
      const username = 'theghost1980';
      const argumentsCallingApi = [username, '', 1000];
      const result = await getDelegatees(username);
      expect(result.length).toBe(0);
      expect(mockedGetVestingDelegations).toBeCalledTimes(1);
      expect(mockedGetVestingDelegations).toBeCalledWith(
        ...argumentsCallingApi,
      );
    });
  });

  describe('claimRewards tests:\n', () => {
    let spyLogger = jest.spyOn(Logger, 'error');
    let loggerCallParams: any[] = [];
    let dispatchCallParams: {};
    beforeEach(() => {
      store.dispatch = jest.fn();
    });
    afterEach(() => {
      jest.clearAllMocks();
    });
    test('Passing an empty ActiveAccount with rewards to claim must call Logger, dispatch a TypeError and return false', async () => {
      loggerCallParams = [
        'Error while claiming rewards',
        "TypeError: Cannot read properties of undefined (reading 'posting')",
      ];
      dispatchCallParams = {
        payload: {
          key: 'popup_html_claim_error',
          params: [],
          type: 'ERROR',
        },
        type: 'SET_MESSAGE',
      };
      const activeAccountEmpty = {} as ActiveAccount;
      const result = await HiveUtils.claimRewards(
        activeAccountEmpty,
        '1.000 HIVE',
        '1.000 HBD',
        '1.000 VESTS',
      );
      expect(result).toBe(false);
      expect(spyLogger).toBeCalledTimes(1);
      expect(spyLogger).toBeCalledWith(...loggerCallParams);
      expect(store.dispatch).toBeCalledTimes(1);
      expect(store.dispatch).toBeCalledWith(dispatchCallParams);
    });
    test('Passing an ActiveAccount with active key, must dispatch a TypeError and return false', async () => {
      loggerCallParams = [
        'Error while claiming rewards',
        'TypeError: Expected String',
      ];
      dispatchCallParams = {
        payload: {
          key: 'popup_html_claim_error',
          params: [],
          type: 'ERROR',
        },
        type: 'SET_MESSAGE',
      };
      const activeAccountUsingActivekey = {
        keys: {
          active: utilsT.userData.nonEncryptKeys.active,
          activePubkey: utilsT.userData.encryptKeys.active,
        },
      } as ActiveAccount;
      const result = await HiveUtils.claimRewards(
        activeAccountUsingActivekey,
        '1.000 HIVE',
        '1.000 HBD',
        '1.000 VESTS',
      );
      expect(result).toBe(false);
      expect(spyLogger).toBeCalledTimes(1);
      expect(spyLogger).toBeCalledWith(...loggerCallParams);
      expect(store.dispatch).toBeCalledTimes(1);
      expect(store.dispatch).toBeCalledWith(dispatchCallParams);
    });
    test('Passing valid Data with reward_hive, must pass the steps bellow and return true', async () => {
      //Steps:
      // 1. Broadcast the claim and get a valid transaction Object with an id property with status as 'within_mempool'.
      // 2. Wait for a valid TransactionStatus from getClient().transaction.findTransaction, as 'within_reversible_block', using the id from step 1.
      // 3. Call Logger.info with the message 'Transaction confirmed'
      // 4. Dispatch a successMessage as 'popup_html_claim_success' containing the claimedResources.
      // 5. Return true
      const transactionObjWaiting = {
        id: '001199xxdass990',
        status: 'within_mempool',
      };
      const transactionObjConfirmed = {
        id: '001199xxdass990',
        status: 'within_reversible_block',
      };
      const sendOperationCallParams: any[] = [
        [
          [
            'claim_reward_balance',
            {
              account: 'keychain.tests',
              reward_hbd: '0.00 HBD',
              reward_hive: '1.00 HIVE',
              reward_vests: '0.00 VESTS',
            },
          ],
        ],
        PrivateKey.fromString(utilsT.userData.nonEncryptKeys.posting as string),
      ];
      const loggerInfoConfirmedMessage = 'Transaction confirmed';
      const expectedDispatchSuccessParams = {
        payload: {
          key: 'popup_html_claim_success',
          params: ['1.00 HIVE'],
          type: 'SUCCESS',
        },
        type: 'SET_MESSAGE',
      };
      const mockedGetClientSendOperations =
        (HiveUtils.getClient().broadcast.sendOperations = jest
          .fn()
          .mockResolvedValueOnce(transactionObjWaiting));
      const mockedGetClientFindTransaction =
        (HiveUtils.getClient().transaction.findTransaction = jest
          .fn()
          .mockResolvedValueOnce(transactionObjConfirmed));
      const spySendOperationWithConfirmation = jest.spyOn(
        HiveUtils,
        'sendOperationWithConfirmation',
      );
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      const activeAccountusingActivekey = {
        name: utilsT.userData.username,
        keys: {
          posting: utilsT.userData.nonEncryptKeys.posting,
          postingPubkey: utilsT.userData.encryptKeys.posting,
        },
      } as ActiveAccount;
      const result = await HiveUtils.claimRewards(
        activeAccountusingActivekey,
        '1.00 HIVE',
        '0.00 HBD',
        '0.00 VESTS',
      );
      expect(result).toBe(true);
      expect(mockedGetClientSendOperations).toBeCalledTimes(1);
      expect(mockedGetClientSendOperations).toBeCalledWith(
        ...sendOperationCallParams,
      );
      expect(mockedGetClientFindTransaction).toBeCalledTimes(1);
      expect(mockedGetClientFindTransaction).toBeCalledWith(
        transactionObjWaiting.id,
      );
      expect(spySendOperationWithConfirmation).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith(loggerInfoConfirmedMessage);

      expect(store.dispatch).toBeCalledTimes(1);
      expect(store.dispatch).toBeCalledWith(expectedDispatchSuccessParams);
    });
    test('Passing valid Data with all rewards, must pass the steps bellow and return true', async () => {
      //Steps:
      // 1. Broadcast the claim and get a valid transaction Object with an id property with status as 'within_mempool'.
      // 2. Wait for a valid TransactionStatus from getClient().transaction.findTransaction, as 'within_reversible_block', using the id from step 1.
      // 3. Call Logger.info with the message 'Transaction confirmed'
      // 4. Dispatch a successMessage as 'popup_html_claim_success' containing the claimedResources.
      // 5. Return true
      const transactionObjWaiting = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      const transactionObjConfirmed = {
        id: '002299xxdass990',
        status: 'within_reversible_block',
      };
      const sendOperationCallParams: any[] = [
        [
          [
            'claim_reward_balance',
            {
              account: 'keychain.tests',
              reward_hive: '10.00 HIVE',
              reward_hbd: '11.00 HBD',
              reward_vests: '12.00 VESTS',
            },
          ],
        ],
        PrivateKey.fromString(utilsT.userData.nonEncryptKeys.posting as string),
      ];
      const loggerInfoConfirmedMessage = 'Transaction confirmed';
      const expectedDispatchSuccessParams = {
        payload: {
          key: 'popup_html_claim_success',
          params: ['11.00 HBD, 10.00 HIVE, 12.000 HP'],
          type: 'SUCCESS',
        },
        type: 'SET_MESSAGE',
      };
      const mockedGetClientSendOperations =
        (HiveUtils.getClient().broadcast.sendOperations = jest
          .fn()
          .mockResolvedValueOnce(transactionObjWaiting));
      const mockedGetClientFindTransaction =
        (HiveUtils.getClient().transaction.findTransaction = jest
          .fn()
          .mockResolvedValueOnce(transactionObjConfirmed));
      const mockFormatUtilsToHP = (FormatUtils.toHP = jest
        .fn()
        .mockReturnValueOnce(12));
      const spySendOperationWithConfirmation = jest.spyOn(
        HiveUtils,
        'sendOperationWithConfirmation',
      );
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      const activeAccountusingActivekey = {
        name: utilsT.userData.username,
        keys: {
          posting: utilsT.userData.nonEncryptKeys.posting,
          postingPubkey: utilsT.userData.encryptKeys.posting,
        },
      } as ActiveAccount;
      const result = await HiveUtils.claimRewards(
        activeAccountusingActivekey,
        '10.00 HIVE',
        '11.00 HBD',
        '12.00 VESTS',
      );
      expect(result).toBe(true);
      expect(mockedGetClientSendOperations).toBeCalledTimes(1);
      expect(mockedGetClientSendOperations).toBeCalledWith(
        ...sendOperationCallParams,
      );
      expect(mockedGetClientFindTransaction).toBeCalledTimes(1);
      expect(mockedGetClientFindTransaction).toBeCalledWith(
        transactionObjWaiting.id,
      );
      expect(mockFormatUtilsToHP).toBeCalledTimes(1);

      expect(spySendOperationWithConfirmation).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith(loggerInfoConfirmedMessage);

      expect(store.dispatch).toBeCalledTimes(1);
      expect(store.dispatch).toBeCalledWith(expectedDispatchSuccessParams);
    });

    test('Passing all valid Data, but making fail sendOperationWithConfirmation must return false and pass steps bellow', async () => {
      //Steps:
      //1. Call Logger.info(`Transaction failed with status: ${transaction.status}`);
      //2. Return as false.
      const transactionObjWaiting = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      const transactionObjConfirmed = {
        id: '002299xxdass990',
        status: 'error_message',
      };
      const sendOperationCallParams: any[] = [
        [
          [
            'claim_reward_balance',
            {
              account: 'keychain.tests',
              reward_hive: '10.00 HIVE',
              reward_hbd: '11.00 HBD',
              reward_vests: '12.00 VESTS',
            },
          ],
        ],
        PrivateKey.fromString(utilsT.userData.nonEncryptKeys.posting as string),
      ];
      const loggerInfoErrorMessage = `Transaction failed with status: ${transactionObjConfirmed.status}`;
      const mockedGetClientSendOperations =
        (HiveUtils.getClient().broadcast.sendOperations = jest
          .fn()
          .mockResolvedValueOnce(transactionObjWaiting));
      const mockedGetClientFindTransaction =
        (HiveUtils.getClient().transaction.findTransaction = jest
          .fn()
          .mockResolvedValueOnce(transactionObjConfirmed));
      const spySendOperationWithConfirmation = jest.spyOn(
        HiveUtils,
        'sendOperationWithConfirmation',
      );
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      const activeAccountusingActivekey = {
        name: utilsT.userData.username,
        keys: {
          posting: utilsT.userData.nonEncryptKeys.posting,
          postingPubkey: utilsT.userData.encryptKeys.posting,
        },
      } as ActiveAccount;
      const result = await HiveUtils.claimRewards(
        activeAccountusingActivekey,
        '10.00 HIVE',
        '11.00 HBD',
        '12.00 VESTS',
      );
      expect(result).toBe(false);
      expect(mockedGetClientSendOperations).toBeCalledTimes(1);
      expect(mockedGetClientSendOperations).toBeCalledWith(
        ...sendOperationCallParams,
      );
      expect(mockedGetClientFindTransaction).toBeCalledTimes(1);
      expect(mockedGetClientFindTransaction).toBeCalledWith(
        transactionObjWaiting.id,
      );

      expect(spySendOperationWithConfirmation).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith(loggerInfoErrorMessage);
    });
  });

  describe('powerUp tests"\n', () => {
    afterEach(() => {
      jest.clearAllMocks();
    });
    test('Power up the activeAccount user, must call Logger with "Transaction confirmed" and return true', async () => {
      const transactionObjWaiting = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      const transactionObjConfirmed = {
        id: '002299xxdass990',
        status: 'within_reversible_block',
      };
      PrivateKey.fromString = jest.fn(); //no implementation.
      HiveUtils.getClient().broadcast.sendOperations = jest
        .fn()
        .mockResolvedValueOnce(transactionObjWaiting);
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce(transactionObjConfirmed);
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      const spySendOperationWithConfirmation = jest.spyOn(
        HiveUtils,
        'sendOperationWithConfirmation',
      );
      const result = await HiveUtils.powerUp(
        utilsT.userData.username,
        utilsT.userData.username,
        '0.001 HIVE',
      );
      expect(result).toBe(true);
      expect(spySendOperationWithConfirmation).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith('Transaction confirmed');
    });
  });

  describe('powerDown tests:\n', () => {
    afterEach(() => {
      jest.clearAllMocks();
    });
    test('Powerdown the activeAccount user, must call Logger with "Transaction confirmed" and return true', async () => {
      const transactionObjWaiting = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      const transactionObjConfirmed = {
        id: '002299xxdass990',
        status: 'within_reversible_block',
      };
      PrivateKey.fromString = jest.fn(); //no implementation.
      HiveUtils.getClient().broadcast.sendOperations = jest
        .fn()
        .mockResolvedValueOnce(transactionObjWaiting);
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce(transactionObjConfirmed);
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      const spySendOperationWithConfirmation = jest.spyOn(
        HiveUtils,
        'sendOperationWithConfirmation',
      );
      const result = await HiveUtils.powerDown(
        utilsT.userData.username,
        '0.1 HIVE',
      );
      expect(result).toBe(true);
      expect(spySendOperationWithConfirmation).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith('Transaction confirmed');
    });
  });

  describe('transfer tests:\n', () => {
    afterEach(() => {
      jest.clearAllMocks();
    });
    test('Executing a non recurrent transfer, should return true and log a success message', async () => {
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      store.getState().activeAccount.keys.active =
        utilsT.userData.nonEncryptKeys.active;
      let transactionObj = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      HiveUtils.getClient().broadcast.sendOperations = jest
        .fn()
        .mockResolvedValueOnce(transactionObj);
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce({
          id: transactionObj.id,
          status: 'within_reversible_block',
        });
      const result = await HiveUtils.transfer(
        utilsT.userData.username,
        'blocktrades',
        '100.000 HBD',
        '',
        false,
        0,
        0,
      );
      expect(result).toBe(true);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith('Transaction confirmed');
    });
    test('Executing a non recurrent transfer, but making it to fail(get an error status) should return false and log an error message', async () => {
      //Note: the expected commented line can be uncommented as soon as the function get refactored.
      const spyLoggerInfo = jest.spyOn(Logger, 'info');
      store.getState().activeAccount.keys.active =
        utilsT.userData.nonEncryptKeys.active;
      let transactionObj = {
        id: '002299xxdass990',
        status: 'within_mempool',
      };
      HiveUtils.getClient().broadcast.sendOperations = jest
        .fn()
        .mockResolvedValueOnce(transactionObj);
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce({
          id: transactionObj.id,
          status: 'error',
        });
      const result = await HiveUtils.transfer(
        utilsT.userData.username,
        'blocktrades',
        '100.000 HBD',
        '',
        false,
        0,
        0,
      );
      //expect(result).toBe(false);
      console.log(result);
      expect(spyLoggerInfo).toBeCalledTimes(1);
      expect(spyLoggerInfo).toBeCalledWith(
        'Transaction failed with status: error',
      );
    });
  });

  describe('signMessage tests:\n', () => {
    test('Passing a message and valid private key, must return the expected signature', () => {
      const signature = require('@hiveio/hive-js/lib/auth/ecc');
      const spySignature = jest.spyOn(signature.Signature, 'signBuffer');
      const callingParams = [
        'test message',
        '5K3R75h6KGBLbEHkmkL34MND95bMveeEu8jPSZWLh5X6DhcnKzM',
      ];
      const expectedSignature =
        '1f4aa1439a8a3c1f559eec87b4ada274698138efc6ba4e5b7cabffa32828943e6251aca3b097b5c422f8689cb13b933b49c32b81064bfb8662e423a281142f1286';
      const result = HiveUtils.signMessage(
        'test message',
        utilsT.userData.nonEncryptKeys.posting,
      );
      expect(result).toBe(expectedSignature);
      expect(spySignature).toBeCalledTimes(1);
      expect(spySignature).toBeCalledWith(...callingParams);
    });
    test('Passing a message and public key, must throw an AssertionError', () => {
      try {
        const result = HiveUtils.signMessage(
          'test message',
          utilsT.userData.encryptKeys.posting,
        );
        expect(result).toBe(1);
      } catch (error) {
        expect(error).toEqual(
          new AssertionError({
            message: 'Expected version 128, instead got 38',
            actual: 128,
            expected: 38,
            operator: '==',
          }),
        );
      }
    });
  });

  describe('sendOperationWithConfirmation tests:\n', () => {
    let transactionObj: TransactionConfirmation = {
      id: '002299xxdass990',
      block_num: 1990,
      trx_num: 1234,
      expired: false,
    };
    const spyLogger = jest.spyOn(Logger, 'info');
    afterEach(() => {
      jest.clearAllMocks();
    });
    test('If findTransaction returns a transaction object with status="within_reversible_block" must return true', async () => {
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce({
          id: transactionObj.id,
          status: 'within_reversible_block',
        });
      const result = await HiveUtils.sendOperationWithConfirmation(
        Promise.resolve(transactionObj),
      );
      expect(result).toBeTruthy();
      expect(spyLogger).toBeCalledTimes(1);
      expect(spyLogger).toBeCalledWith('Transaction confirmed');
    });
    test('If findTransaction returns a transaction object with status!="within_reversible_block" must return false', async () => {
      HiveUtils.getClient().transaction.findTransaction = jest
        .fn()
        .mockResolvedValueOnce({
          id: transactionObj.id,
          status: 'error',
        });
      const result = await HiveUtils.sendOperationWithConfirmation(
        Promise.resolve(transactionObj),
      );
      expect(result).toBe(undefined);
      expect(spyLogger).toBeCalledTimes(1);
      expect(spyLogger).toBeCalledWith('Transaction failed with status: error');
    });
  });
});
Example #6
Source File: extension.ts    From plugin-vscode with Apache License 2.0 4 votes vote down vote up
init(_onBeforeInit: Function): Promise<void> {
        // Register show logs command.
        const showLogs = commands.registerCommand('ballerina.showLogs', () => {
            outputChannel.show();
        });
        this.context!.subscriptions.push(showLogs);

        try {
            // Register pre init handlers.
            this.registerPreInitHandlers();

            // Check if ballerina home is set.
            if (this.overrideBallerinaHome()) {
                if (!this.getConfiguredBallerinaHome()) {
                    const message = "Trying to get ballerina version without setting ballerina home.";
                    sendTelemetryEvent(this, TM_EVENT_ERROR_INVALID_BAL_HOME_CONFIGURED, CMP_EXTENSION_CORE, message);
                    throw new AssertionError({
                        message: message
                    });
                }

                debug("Ballerina home is configured in settings.");
                this.ballerinaHome = this.getConfiguredBallerinaHome();
            }

            // Validate the ballerina version.
            const pluginVersion = this.extension.packageJSON.version.split('-')[0];
            return this.getBallerinaVersion(this.ballerinaHome, this.overrideBallerinaHome()).then(runtimeVersion => {
                this.ballerinaVersion = runtimeVersion.split('-')[0];
                if (!this.overrideBallerinaHome()) {
                    const { home } = this.autoDetectBallerinaHome();
                    this.ballerinaHome = home;
                }
                log(`Plugin version: ${pluginVersion}\nBallerina version: ${this.ballerinaVersion}`);
                this.sdkVersion.text = `Ballerina SDK: ${this.ballerinaVersion}`;

                if (this.ballerinaVersion.match(SWAN_LAKE_REGEX)) {
                    this.isSwanLake = true;
                } else if (this.ballerinaVersion.match(PREV_REGEX)) {
                    this.is12x = true;
                }

                if (!this.isSwanLake && !this.is12x) {
                    this.showMessageOldBallerina();
                    const message = `Ballerina version ${this.ballerinaVersion} is not supported. 
                        Please use a compatible VSCode extension version.`;
                    sendTelemetryEvent(this, TM_EVENT_ERROR_OLD_BAL_HOME_DETECTED, CMP_EXTENSION_CORE, message);
                    throw new AssertionError({
                        message: message
                    });
                }

                // if Home is found load Language Server.
                let serverOptions: ServerOptions;
                serverOptions = getServerOptions(this.ballerinaCmd);
                this.langClient = new ExtendedLangClient('ballerina-vscode', 'Ballerina LS Client', serverOptions,
                    this.clientOptions, false);

                // Following was put in to handle server startup failures.
                const disposeDidChange = this.langClient.onDidChangeState(stateChangeEvent => {
                    if (stateChangeEvent.newState === LS_STATE.Stopped) {
                        const message = "Couldn't establish language server connection.";
                        sendTelemetryEvent(this, TM_EVENT_EXTENSION_INI_FAILED, CMP_EXTENSION_CORE, message);
                        log(message);
                        this.showPluginActivationError();
                    }
                });

                let disposable = this.langClient.start();
                this.langClient.onReady().then(() => {
                    disposeDidChange.dispose();
                    this.context!.subscriptions.push(disposable);
                });
            }, (reason) => {
                sendTelemetryException(this, reason, CMP_EXTENSION_CORE);
                throw new Error(reason);
            }).catch(e => {
                const msg = `Error when checking ballerina version. ${e.message}`;
                sendTelemetryException(this, e, CMP_EXTENSION_CORE, msg);
                this.telemetryReporter.dispose();
                throw new Error(msg);
            });
        } catch (ex) {
            const msg = "Error while activating plugin. " + (ex.message ? ex.message : ex);
            // If any failure occurs while initializing show an error message
            this.showPluginActivationError();
            sendTelemetryException(this, ex, CMP_EXTENSION_CORE, msg);
            this.telemetryReporter.dispose();
            return Promise.reject(msg);
        }
    }
Example #7
Source File: helpers.ts    From language-tools with MIT License 4 votes vote down vote up
export function test_samples(dir: string, transform: TransformSampleFn, jsx: 'jsx' | 'tsx') {
    const js = jsx.slice(0, 2);
    for (const sample of each_sample(dir)) {
        const svelteFile = sample.find_file('*.svelte');
        const config = {
            filename: svelteFile,
            sampleName: sample.name,
            emitOnTemplateError: false,
            preserveAttributeCase: sample.name.endsWith('-foreign-ns'),
            useNewTransformation: false
        };
        let testingV2 = false;

        if (process.env.CI) {
            sample.checkDirectory({
                required: ['*.svelte', `expected.${jsx}`, `expectedv2.${js}`],
                allowed: ['expected.js', 'expected.error.json']
            });
        } else {
            sample.checkDirectory({
                required: ['*.svelte'],
                allowed: [
                    'expected.js',
                    `expected.${jsx}`,
                    `expectedv2.${js}`,
                    'expected.error.json'
                ]
            });

            if (
                sample.hasOnly(svelteFile) ||
                sample.hasOnly(svelteFile, 'expected.js') ||
                sample.hasOnly(svelteFile, 'expected.js', `expected.${jsx}`) ||
                sample.hasOnly(svelteFile, `expected.${jsx}`)
            ) {
                sample.generateDeps((generate) => {
                    const input = sample.get(svelteFile);
                    try {
                        transform(input, config);
                    } catch (error) {
                        generate('expected.error.json', print_error(error));
                        config.emitOnTemplateError = true;
                    }
                    generate(`expected.${jsx}`, transform(input, config).code);
                    generate(
                        `expectedv2.${js}`,
                        transform(input, { ...config, useNewTransformation: true }).code
                    );
                });
            }

            sample.onError(function (generate, err: AssertionError) {
                if (!err || err.code !== 'ERR_ASSERTION') return;
                const { message, actual } = err;
                switch (message) {
                    case TestError.WrongExpected: {
                        generate(testingV2 ? `expectedv2.${js}` : `expected.${jsx}`, actual);
                        break;
                    }
                    case TestError.WrongError: {
                        generate('expected.error.json', print_error(actual));
                        break;
                    }
                }
            });
        }

        sample.it(function () {
            const input = sample.get(svelteFile);

            if (sample.has('expected.error.json')) {
                let hadError = false;
                try {
                    transform(input, config);
                } catch (error) {
                    hadError = true;
                    assert.deepEqual(
                        JSON.parse(JSON.stringify(error)),
                        JSON.parse(sample.get('expected.error.json')),
                        TestError.WrongError
                    );
                    config.emitOnTemplateError = true;
                }
                assert(hadError, TestError.MissingError);
            }

            const output = transform(input, config);

            assert.strictEqual(
                normalize(output.code),
                sample.get(`expected.${jsx}`),
                TestError.WrongExpected
            );

            if (sample.has('expected.js')) {
                sample.eval('expected.js', output);
            }

            testingV2 = true;
            assert.strictEqual(
                normalize(transform(input, { ...config, useNewTransformation: true }).code),
                sample.get(`expectedv2.${js}`),
                TestError.WrongExpected
            );
        });
    }
}