ts-mockito#when TypeScript Examples

The following examples show how to use ts-mockito#when. 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: internal.spec.ts    From kin-node with MIT License 6 votes vote down vote up
function setGetServiceConfigResp(txClientV4: transactiongrpcv4.TransactionClient) {
    when(txClientV4.getServiceConfig(anything(), anything(), anything()))
        .thenCall((_, md: grpc.Metadata, callback) => {
            const subsidizerAccount = new commonpbv4.SolanaAccountId();
            subsidizerAccount.setValue(subsidizer);
            const tokenAccount = new commonpbv4.SolanaAccountId();
            tokenAccount.setValue(token);
            const tokenProgramAccount = new commonpbv4.SolanaAccountId();
            tokenProgramAccount.setValue(TOKEN_PROGRAM_ID.toBuffer());

            const resp = new transactionpbv4.GetServiceConfigResponse();
            resp.setSubsidizerAccount(subsidizerAccount);
            resp.setToken(tokenAccount);
            resp.setTokenProgram(tokenProgramAccount);

            const err = validateHeaders(md);
            if (err !== undefined) {
                callback(err, undefined);
                return;
            }

            callback(undefined, resp);
        });
}
Example #2
Source File: pastDate.validator.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('pastDate', () => {
  let control: AbstractControl;
  let validator: ValidatorFn;

  beforeEach(() => {
    control = mock(AbstractControl);
    validator = pastDateValidator();
  });

  it('returns a pastDate error if the date is not in the past', () => {
    when(control.value).thenReturn(format(addDays(new Date(), 10), 'yyyy-MM-dd'));

    expect(validator(instance(control))).toEqual({
      pastDate: true,
    });
  });

  it('returns null if the date is not a valid date', () => {
    when(control.value).thenReturn(null);

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if date is in the past', () => {
    when(control.value).thenReturn(format(subDays(new Date(), 10), 'yyyy-MM-dd'));

    expect(validator(instance(control))).toBe(null);
  });
});
Example #3
Source File: internal.spec.ts    From kin-node with MIT License 6 votes vote down vote up
function setGetMinBalanceResp(txClientV4: transactiongrpcv4.TransactionClient) {
    when(txClientV4.getMinimumBalanceForRentExemption(anything(), anything(), anything()))
        .thenCall((_, md: grpc.Metadata, callback) => {
            const resp = new transactionpbv4.GetMinimumBalanceForRentExemptionResponse();
            resp.setLamports(minBalanceForRentExemption);

            const err = validateHeaders(md);
            if (err !== undefined) {
                callback(err, undefined);
                return;
            }

            callback(undefined, resp);
        });
}
Example #4
Source File: PlaybackEngine.test.ts    From osmd-audio-player with MIT License 6 votes vote down vote up
function createOsmdMock(): OpenSheetMusicDisplay {
  const mockedOsmd = mock(OpenSheetMusicDisplay);
  const mockedSheet = mock(MusicSheet);
  const mockedPlaybackSettings = mock(PlaybackSettings);
  const mockedFraction = mock(Fraction);
  const mockedCursor = mock(Cursor);

  //@ts-ignore
  when(mockedCursor.Iterator).thenReturn({ EndReached: true });
  when(mockedOsmd.cursor).thenReturn(instance(mockedCursor));
  when(mockedSheet.Instruments).thenReturn([]);
  when(mockedPlaybackSettings.rhythm).thenReturn(instance(mockedFraction));
  when(mockedSheet.SheetPlaybackSetting).thenReturn(instance(mockedPlaybackSettings));
  when(mockedOsmd.Sheet).thenReturn(instance(mockedSheet));
  return instance(mockedOsmd);
}
Example #5
Source File: client.spec.ts    From kin-node with MIT License 6 votes vote down vote up
function setGetServiceConfigResp(client: InternalClient) {
    when(client.getServiceConfig())
        .thenCall(() => {
            const subsidizerAccount = new commonpbv4.SolanaAccountId();
            subsidizerAccount.setValue(subsidizer);
            const tokenAccount = new commonpbv4.SolanaAccountId();
            tokenAccount.setValue(token);
            const tokenProgramAccount = new commonpbv4.SolanaAccountId();
            tokenProgramAccount.setValue(tokenProgram);
            
            const resp = new transactionpbv4.GetServiceConfigResponse();
            resp.setSubsidizerAccount(subsidizerAccount);
            resp.setToken(tokenAccount);
            resp.setTokenProgram(tokenProgramAccount);
            
            return Promise.resolve(resp);
        });
}
Example #6
Source File: web3-provider.connector.test.ts    From limit-order-protocol-utils with MIT License 5 votes vote down vote up
describe('Web3ProviderConnector', () => {
    let web3Provider: Web3;
    let web3ProviderConnector: Web3ProviderConnector;

    const typedData = {
        primaryType: 'Order',
        types: {
            EIP712Domain: EIP712_DOMAIN,
            Order: ORDER_STRUCTURE,
        },
        domain: {
            name: PROTOCOL_NAME,
            version: PROTOCOL_VERSION,
            chainId: 1,
            verifyingContract: '',
        },
        message: {},
    };

    beforeEach(() => {
        web3Provider = mock<Web3>();
        web3ProviderConnector = new Web3ProviderConnector(
            instance(web3Provider)
        );
    });

    it('signTypedData() must call eth_signTypedData_v4 rpc method', async () => {
        const walletAddress = '0xasd';

        const extendedWeb3 = {
            signTypedDataV4: jest.fn(),
        };

        when(web3Provider.extend(anything())).thenReturn(extendedWeb3);

        await web3ProviderConnector.signTypedData(walletAddress, typedData, '');

        expect(extendedWeb3.signTypedDataV4).toHaveBeenCalledWith(
            walletAddress,
            JSON.stringify(typedData)
        );
    });

    it('contractEncodeABI() changed address from null to undefined for contract instance', async () => {
        const eth = mock<Eth>();
        class ContractMock {
            methods = {
                foo: () => ({encodeABI: () => ''}),
            };
        }

        /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
        when(eth.Contract).thenReturn(ContractMock as any);
        when(web3Provider.eth).thenReturn(instance(eth));

        web3ProviderConnector.contractEncodeABI(
            LIMIT_ORDER_PROTOCOL_ABI,
            null,
            'foo',
            []
        );

        verify(eth.Contract).once();
    });
});
Example #7
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test("requestAirdrop", async() => {
    const internal = mock(InternalClient);

    const pk = PrivateKey.random();
    let client = new Client(Environment.Prod, {
        internal: instance(internal),
    });

    interface airdropReq {
        publicKey: PublicKey,
        quarks: BigNumber,
        commitment?: Commitment,
    }
    let r: airdropReq | undefined;
    when(internal.requestAirdrop(anything(), anything(), anything()))
        .thenCall((publicKey: PublicKey, quarks: BigNumber, commitment: Commitment) => {
            r = {publicKey, quarks, commitment};
            return Promise.resolve(Buffer.alloc(32));
        });

    try {
        await client.requestAirdrop(pk.publicKey(), new BigNumber(10));
        fail();
    } catch (err) {
        expect(err).toContain('test');
        expect(r).toBeUndefined();
    }

    client = new Client(Environment.Test, {
        internal: instance(internal),
        defaultCommitment: Commitment.Recent,
    });
    
    let txID = await client.requestAirdrop(pk.publicKey(), new BigNumber(10));
    expect(txID).toEqual(Buffer.alloc(32));

    expect(r!.publicKey.buffer).toEqual(pk.publicKey().buffer);
    expect(r!.quarks).toEqual(new BigNumber(10));
    expect(r!.commitment).toEqual(Commitment.Recent);

    txID = await client.requestAirdrop(pk.publicKey(), new BigNumber(10), Commitment.Max);
    expect(txID).toEqual(Buffer.alloc(32));

    expect(r!.publicKey.buffer).toEqual(pk.publicKey().buffer);
    expect(r!.quarks).toEqual(new BigNumber(10));
    expect(r!.commitment).toEqual(Commitment.Max);
});
Example #8
Source File: mocks.ts    From xrp-api with MIT License 5 votes vote down vote up
when(mockedRippleApiService.connectHandleFunction()).thenReturn(function(req, res, next) {
  next();
});
Example #9
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
function setGetRecentBlockhashResp(client: InternalClient) {
    when(client.getRecentBlockhash())
        .thenCall(() => {
            return Promise.resolve(bs58.encode(recentBlockhash));
        });
}
Example #10
Source File: beforeDate.validator.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('beforeDate', () => {
  let control: AbstractControl;
  let validator: ValidatorFn;
  let dateToCompare: Date;
  let date: Date;

  beforeEach(() => {
    dateToCompare = new Date();
    control = mock(AbstractControl);
    validator = beforeDateValidator(dateToCompare);
  });

  describe('date to compare is not a valid date', () => {
    it('throws an error', () => {
      expect(() => beforeDateValidator(new Date('xx'))).toThrow();
    });
  });

  describe('date is after the specified date', () => {
    beforeEach(() => {
      date = addDays(dateToCompare, 10);
      when(control.value).thenReturn(format(date, 'yyyy-MM-dd'));
    });

    it('adds a beforeDate error', () => {
      expect(validator(instance(control))).toEqual(jasmine.any(Object));
    });

    it('includes the date to compare against', () => {
      expect(validator(instance(control)).beforeDate).toEqual(
        jasmine.objectContaining({
          required: format(dateToCompare, dateFormat),
        }),
      );
    });

    it('includes the date that was entered', () => {
      expect(validator(instance(control)).beforeDate).toEqual(
        jasmine.objectContaining({
          actual: format(date, dateFormat),
        }),
      );
    });
  });

  it('returns null if the date is null', () => {
    when(control.value).thenReturn(null);

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if the date is not a valid date', () => {
    when(control.value).thenReturn(new Date('not a date'));

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if date is before the specified date', () => {
    date = subDays(dateToCompare, 10);
    when(control.value).thenReturn(format(date, 'yyyy-MM-dd'));

    expect(validator(instance(control))).toEqual(null);
  });
});
Example #11
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
function setGetMinBalanceForRentExemptionResp(client: InternalClient) {
    when(client.getMinimumBalanceForRentExemption())
        .thenCall(() => {
            return Promise.resolve(minBalance);
        });
}
Example #12
Source File: roles.guard.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('RolesGuard(ts-mockito)', () => {
  let guard: RolesGuard;
  const reflecter = mock(Reflector);
  beforeEach(() => {
    guard = new RolesGuard(instance(reflecter));
  });

  afterEach(() => {
    reset();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    const context = mock<ExecutionContext>();
    when(context.getHandler()).thenReturn({} as any);

    const contextInstacne = instance(context);
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([] as RoleType[]);
    const result = await guard.canActivate(contextInstacne);

    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.USER] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    // logged in as USER
    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    // but requires ADMIN
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.ADMIN] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeFalsy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });
});
Example #13
Source File: users.spec.ts    From space-sdk with MIT License 5 votes vote down vote up
describe('Users...', () => {
  const config: UsersConfig = {
    endpoint: '',
    authChallengeSolver: async () => ({
      token: 'app-token',
      storageAuth: {
        key: '',
        token: 'mock-auth-token',
        sig: '',
        msg: '',
      },
    }),
  };

  describe('identity', () => {
    const users = new Users(config);

    it('create and authenticate', async () => {
      const identity = await users.createIdentity();
      const user = await users.authenticate(identity);

      expect(user.token).to.equal('app-token');
    });
  });

  describe('recoverKeysByPassPhrase', () => {
    it('should throw if vaultInit or vaultServiceConfig are missing', async () => {
      const users = new Users(config);
      await expect(users.recoverKeysByPassphrase('', '', VaultBackupType.Twitter)).to.eventually.be.rejected;
    });

    // it('should add new identity to identity storage', async () => {});
  });

  describe('backupKeysByPassphrase', () => {
    it('should throw if vaultInit or vaultServiceConfig is missing', async () => {
      const users = new Users(config);
      const mockIdentity: PrivateKey = mock();

      await expect(
        users.backupKeysByPassphrase('', '', VaultBackupType.Twitter, instance(mockIdentity)),
      ).to.eventually.be.rejectedWith('Either vaultServiceConfig or vaultInit configuration is required.');
    });

    it('should throw if identity provided is not a private key', async () => {
      const users = new Users(config);
      const mockIdentity: PrivateKey = mock();
      when(mockIdentity.privKey).thenReturn((null as unknown) as Uint8Array);

      await expect(
        users.backupKeysByPassphrase('', '', VaultBackupType.Twitter, instance(mockIdentity)),
      ).to.eventually.be.rejectedWith('identity provided is not a valid PrivateKey Identity.');
    });
  });
});
Example #14
Source File: internal.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test('internal retry Kin 4', async () => {
    let env = newTestEnv();
    const [accountClientV4, airdropClientV4] = [env.accountClientV4, env.airdropClientV4];
    let [client, txClientV4] = [env.client, env.txClientV4];

    const account = PrivateKey.random();
    when(accountClientV4.createAccount(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new accountpbv4.CreateAccountRequest());
        });
    when(accountClientV4.getAccountInfo(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new accountpbv4.GetAccountInfoResponse());
        });
    when(airdropClientV4.requestAirdrop(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new airdroppbv4.RequestAirdropResponse());
        });
    when(txClientV4.getTransaction(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetTransactionResponse());
        });
    when(txClientV4.submitTransaction(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.SubmitTransactionResponse());
        });

    setGetServiceConfigResp(txClientV4);
    setGetMinBalanceResp(txClientV4);
    setGetRecentBlockhashResp(txClientV4);

    try {
        await client.createAccount(account);
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(accountClientV4.createAccount(anything(), anything(), anything())).times(3);

    try {
        await client.getAccountInfo(new PublicKey(Buffer.alloc(32)));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(accountClientV4.createAccount(anything(), anything(), anything())).times(3);

    try {
        await client.getTransaction(Buffer.alloc(32));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getTransaction(anything(), anything(), anything())).times(3);

    const transaction = new SolanaTransaction({
        feePayer: PrivateKey.random().publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            PrivateKey.random().publicKey().solanaKey(),
            PrivateKey.random().publicKey().solanaKey(),
            PrivateKey.random().publicKey().solanaKey(),
            [],
            100,
        )
    );
    try {
        await client.submitTransaction(transaction);
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.submitTransaction(anything(), anything(), anything())).times(3);

    try {
        await client.requestAirdrop(account.publicKey(), new BigNumber(10));
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(airdropClientV4.requestAirdrop(anything(), anything(), anything())).times(3);

    env = newTestEnv();
    client = env.client;
    txClientV4 = env.txClientV4;

    when(txClientV4.getServiceConfig(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.SubmitTransactionResponse());
        });

    when(txClientV4.getRecentBlockhash(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetRecentBlockhashResponse());
        });

    when(txClientV4.getMinimumBalanceForRentExemption(anything(), anything(), anything()))
        .thenCall((_, __, callback) => {
            const err: grpc.ServiceError = {
                name: "",
                message: "",
                code: grpc.status.INTERNAL,
            };
            callback(err, new transactionpbv4.GetMinimumBalanceForRentExemptionResponse());
        });

    try {
        await client.getServiceConfig();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getServiceConfig(anything(), anything(), anything())).times(3);

    try {
        await client.getRecentBlockhash();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getRecentBlockhash(anything(), anything(), anything())).times(3);

    try {
        await client.getMinimumBalanceForRentExemption();
        fail();
    } catch (err) {
        expect(err).toBeDefined();
    }
    verify(txClientV4.getMinimumBalanceForRentExemption(anything(), anything(), anything())).times(3);
});
Example #15
Source File: private-key-provider.connector.test.ts    From limit-order-protocol-utils with MIT License 4 votes vote down vote up
describe('PrivateKeyProviderConnector', () => {
    let web3Provider: Web3;
    let privateKeyProviderConnector: PrivateKeyProviderConnector;

    const testPrivateKey =
        'd8d1f95deb28949ea0ecc4e9a0decf89e98422c2d76ab6e5f736792a388c56c7';
    const limitOrder: LimitOrder = {
        salt: '1469462901577',
        getMakerAmount:
            '0xf4a215c30000000000000000000000000000000000000000000000',
        getTakerAmount:
            '0x296637bf0000000000000000000000000000000000000000000000',
        makerAsset: '0x111111111117dc0aa78b770fa6a738034120c302',
        takerAsset: '0xe9e7cea3dedca5984780bafc599bd69add087d56',
        maker: '0xa07c1d51497fb6e66aa2329cecb86fca0a957fdb',
        receiver: '0x0000000000000000000000000000000000000000',
        allowedSender: '0x0000000000000000000000000000000000000000',
        makingAmount: '1000000000000000000000',
        takingAmount: '90000000000000000000',
        makerAssetData:
            '0x23b872dd000000000000000000000000fb3c7eb936caa12b5a884d612393969a557d43070000',
        takerAssetData:
            '0x23b872dd00000000000000000000000000000000000000000000000000000000000000000000',
        interaction: '0x',
        permit: '0x',
        predicate: '0x',
    };
    const typedData: EIP712TypedData = {
        primaryType: 'Order',
        types: {
            EIP712Domain: EIP712_DOMAIN,
            Order: ORDER_STRUCTURE,
        },
        domain: {
            name: PROTOCOL_NAME,
            version: PROTOCOL_VERSION,
            chainId: 1,
            verifyingContract: '',
        },
        message: limitOrder,
    };

    beforeEach(() => {
        web3Provider = mock<Web3>();
        privateKeyProviderConnector = new PrivateKeyProviderConnector(
            testPrivateKey,
            instance(web3Provider)
        );
    });

    it('signTypedData() must sign typed data by private key', async () => {
        const walletAddress = '0xa07c1d51497fb6e66aa2329cecb86fca0a957fdb';

        const signature = await privateKeyProviderConnector.signTypedData(
            walletAddress,
            typedData
        );

        expect(signature).toMatchSnapshot();
    });

    it('contractEncodeABI() changed address from null to undefined for contract instance', async () => {
        const eth = mock<Eth>();
        class ContractMock {
            methods = {
                foo: () => ({encodeABI: () => ''}),
            };
        }

        /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
        when(eth.Contract).thenReturn(ContractMock as any);
        when(web3Provider.eth).thenReturn(instance(eth));

        privateKeyProviderConnector.contractEncodeABI(
            LIMIT_ORDER_PROTOCOL_ABI,
            null,
            'foo',
            []
        );

        verify(eth.Contract).once();
    });
});
Example #16
Source File: internal.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test('resolveTokenAccounts', async() => {
    const env = newTestEnv();
    const [client, accountClientV4] = [env.client, env.accountClientV4];

    const tokenAccounts = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];

    const [account, subsidizer] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];
    const ownerAccountId = new commonpbv4.SolanaAccountId();
    ownerAccountId.setValue(account.buffer);
    const subsidizerId = new commonpbv4.SolanaAccountId();
    subsidizerId.setValue(subsidizer.buffer);

    let requestedNoInfo = false;
    let requestedWithInfo = false;

    // On first request of each type, do not include account info.
    when (accountClientV4.resolveTokenAccounts(anything(), anything(), anything()))
        .thenCall((req: accountpbv4.ResolveTokenAccountsRequest, md: grpc.Metadata, callback) => {
            const err = validateHeaders(md);
            if (err != undefined) {
                callback(err, undefined);
                return;
            }

            const resp = new accountpbv4.ResolveTokenAccountsResponse();
            if (Buffer.from(req.getAccountId()!.getValue_asU8()).equals(account.buffer)) {
                const ids: commonpbv4.SolanaAccountId[] = [];
                tokenAccounts.forEach(tokenAccount => {
                    const accountId = new commonpbv4.SolanaAccountId();
                    accountId.setValue(tokenAccount.buffer);
                    ids.push(accountId);
                });
                resp.setTokenAccountsList(ids);

                let setAccountInfos = false;
                if (req.getIncludeAccountInfo()) {
                    if (requestedWithInfo) {
                        setAccountInfos = true;
                    }

                    requestedWithInfo = true;
                } else {
                    if (requestedNoInfo) {
                        setAccountInfos = true;
                    }
                    requestedNoInfo = true;
                }

                if (setAccountInfos) {
                    const infos: accountpbv4.AccountInfo[] = [];
                    tokenAccounts.forEach((_, i) => {
                        const accountInfo = new accountpbv4.AccountInfo();
                        accountInfo.setAccountId(resp.getTokenAccountsList()[i]);
                        if (req.getIncludeAccountInfo()) {
                            accountInfo.setBalance("10");
                            accountInfo.setOwner(ownerAccountId);
                            accountInfo.setCloseAuthority(subsidizerId);
                        }
                        infos.push(accountInfo);
                    });
                    resp.setTokenAccountInfosList(infos);
                }
            }
            callback(undefined, resp);
        });

    // Account info not requested, only IDs available
    let accountInfos = await client.resolveTokenAccounts(account);
    expect(accountInfos.length).toEqual(tokenAccounts.length);
    for (let i = 0; i < tokenAccounts.length; i++) {
        expect(accountInfos[i].getAccountId()!.getValue_asU8()).toEqual(tokenAccounts[i].buffer);
        expect(accountInfos[i].getBalance()).toEqual("0");
        expect(accountInfos[i].getOwner()).toBeUndefined();
        expect(accountInfos[i].getCloseAuthority()).toBeUndefined();
    }

    // Account info not requested, info available
    accountInfos = await client.resolveTokenAccounts(account);
    expect(accountInfos.length).toEqual(tokenAccounts.length);
    for (let i = 0; i < tokenAccounts.length; i++) {
        expect(accountInfos[i].getAccountId()!.getValue_asU8()).toEqual(tokenAccounts[i].buffer);
        expect(accountInfos[i].getBalance()).toEqual("0");
        expect(accountInfos[i].getOwner()).toBeUndefined();
        expect(accountInfos[i].getCloseAuthority()).toBeUndefined();
    }

    // Account info requested, only IDs available
    try {
        await client.resolveTokenAccounts(account, true);
    } catch (error) {
        expect(error.toString()).toContain("server does not support resolving with account info");
    }

    // Account info requested, info available
    accountInfos = await client.resolveTokenAccounts(account, true);
    for (let i = 0; i < tokenAccounts.length; i++) {
        expect(accountInfos[i].getAccountId()!.getValue_asU8()).toEqual(tokenAccounts[i].buffer);
        expect(accountInfos[i].getBalance()).toEqual("10");
        expect(accountInfos[i].getOwner()!.getValue()).toEqual(account.buffer);
        expect(accountInfos[i].getCloseAuthority()!.getValue_asU8()).toEqual(subsidizer.buffer);
    }

    // No token accounts
    expect(await client.resolveTokenAccounts(tokenAccounts[0])).toHaveLength(0);
});
Example #17
Source File: multicall.service.test.ts    From multicall with MIT License 4 votes vote down vote up
describe('MultiCallService', () => {
    const multiCallAddress = '0x001';

    let multiCallService: MultiCallService;
    let connector: ProviderConnector;

    beforeEach(() => {
        connector = mock<ProviderConnector>();
        multiCallService = new MultiCallService(
            instance(connector),
            multiCallAddress
        );
    });

    beforeEach(() => {
        when(connector.contractEncodeABI(anything(), anything(), anything(), anything())).thenCall((
            _: unknown, __: string, methodName: string, params: unknown[],
        ) => {
            return {methodName, params};
        });

        when(connector.ethCall(anything(), anything(), anything())).thenCall((
            _: unknown, callData: {methodName: string, params: unknown[]}
        ) => {
            return callData;
        });
    });


    describe('callByGasLimit() full successful multicall', () => {
        beforeEach(() => {
            when(connector.decodeABIParameterList(anything(), anything())).thenCall((
                _: unknown, callData: {methodName: string, params: unknown[]}
            ) => {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                return {results: callData.params[0], lastSuccessIndex: callData.params[0].length};
            });
        });

        it('test', async () => {
            const gasLimit = 410;
            const requests: MultiCallRequestWithGas[] = [
                {to: '01', data: '01', gas: 100},
                {to: '02', data: '02', gas: 100},
                {to: '03', data: '03', gas: 100},
                {to: '04', data: '04', gas: 100},
                {to: '05', data: '05', gas: 100},
                {to: '06', data: '06', gas: 100},
                {to: '07', data: '07', gas: 100},
                {to: '08', data: '08', gas: 100},
                {to: '09', data: '09', gas: 100},
                {to: '10', data: '10', gas: 100},
            ];

            const result = await multiCallService.callByGasLimit(requests, gasLimit, {
                ...defaultParamsWithGas,
                maxChunkSize: 3,
            });

            expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
        });
    });

    describe('callByGasLimit() multicall with errors', () => {
        function getLastSuccessIndex(requests: MultiCallRequest[]): number {
            // lastSuccessIndex = 1, it means that only 01, 02 responses were successful
            if (requests.map(i => i.data).join('') === '010203') {
                return 1;
            }

            // lastSuccessIndex = 1, it means that only 04, 05 responses were successful
            if (requests.map(i => i.data).join('') === '040506') {
                return 1;
            }

            // lastSuccessIndex = 0, it means that only 7 responses were successful
            if (requests.map(i => i.data).join('') === '070809') {
                return 0;
            }

            return requests.length - 1;
        }

        beforeEach(() => {
            when(connector.decodeABIParameterList(anything(), anything())).thenCall((
                _: unknown, callData: {methodName: string, params: unknown[]}
            ) => {
                const results = callData.params[0] as MultiCallRequest[];

                return {results, lastSuccessIndex: getLastSuccessIndex(results)};
            });
        });

        it('test', async () => {
            const gasLimit = 300;
            const requests: MultiCallRequestWithGas[] = [
                {to: '01', data: '01', gas: 100},
                {to: '02', data: '02', gas: 100},
                {to: '03', data: '03', gas: 100},
                {to: '04', data: '04', gas: 100},
                {to: '05', data: '05', gas: 100},
                {to: '06', data: '06', gas: 100},
                {to: '07', data: '07', gas: 100},
                {to: '08', data: '08', gas: 100},
                {to: '09', data: '09', gas: 100},
                {to: '10', data: '10', gas: 100},
            ];
            const expectedRequestsByChunks = [
                [
                    {to: '01', data: '01'},
                    {to: '02', data: '02'},
                    {to: '03', data: '03'},
                ],
                [
                    {to: '04', data: '04'},
                    {to: '05', data: '05'},
                    {to: '06', data: '06'},
                ],
                [
                    {to: '07', data: '07'},
                    {to: '08', data: '08'},
                    {to: '09', data: '09'},
                ],
                [
                    {to: '10', data: '10'},
                ],
                [
                    {to: '03', data: '03'},
                    {to: '06', data: '06'},
                ],
                [
                    {to: '08', data: '08'},
                    {to: '09', data: '09'},
                ],
            ];

            const result = await multiCallService.callByGasLimit(requests, gasLimit, {
                ...defaultParamsWithGas,
                maxChunkSize: 3,
            });

            const ethCalls = capture(connector.ethCall);

            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            const ethCallArguments = [0,1,2,3,4,5].map(index => ethCalls.byCallIndex(index)[1]['params'][0]);

            expect(ethCallArguments).toEqual(expectedRequestsByChunks);
            expect(result).toEqual(requests.map(r => ({to: r.to, data: r.data})));
        });
    });
});
Example #18
Source File: swagger-provider.spec.ts    From adonis5-swagger with MIT License 4 votes vote down vote up
describe('Swagger provider', () => {
	async function createAdonisApp(mockedServices: Partial<ContainerBindings>) {
		const app = await new AdonisApplication([], []).loadApp()
		for (const [alias, mockedService] of Object.entries(mockedServices)) {
			app.iocContainer.bind(alias, () => mockedService)
		}

		return app
	}

	describe('Swagger enabled', () => {
		let testUrl = 'testUrl'
		let configMock: ConfigContract
		let routerMock: RouterContract
		let routerForMiddlewareMock: RouteContract
		let app: AdonisApplication

		beforeAll(async () => {
			configMock = mock(Config)
			when(configMock.get('swagger.uiEnabled', true)).thenReturn(true)
			when(configMock.get('swagger.specEnabled', true)).thenReturn(true)
			when(configMock.get('swagger.uiUrl', 'docs')).thenReturn('docs')
			when(configMock.get('swagger.specUrl')).thenReturn(testUrl)
			when(configMock.get('swagger.middleware', [])).thenReturn([])
			when(configMock.get('swagger.options', {})).thenReturn({})

			routerMock = mock(Router)
			routerForMiddlewareMock = mock(Route)
			const routeForMiddlewareInstance = instance(routerForMiddlewareMock)
			when(routerMock.get(`docs/:fileName?`, anything())).thenReturn(routeForMiddlewareInstance)
			when(routerMock.get(testUrl, anything())).thenReturn(routeForMiddlewareInstance)

			app = await createAdonisApp({
				'Adonis/Core/Config': instance(configMock),
				'Adonis/Core/Route': instance(routerMock),
			})
		})

		it('should instantiate provider with enabled swagger', async () => {
			const swaggerProvider = new SwaggerProvider(app.application)
			await swaggerProvider.register()
			await swaggerProvider.boot()

			verify(configMock.get('swagger.uiEnabled', true)).once()
			verify(configMock.get('swagger.specEnabled', true)).once()
			verify(configMock.get('swagger.uiUrl', 'docs')).once()
			verify(configMock.get('swagger.specUrl')).once()

			verify(routerMock.get(testUrl, anything())).once()
			verify(routerForMiddlewareMock.middleware(anything())).twice()
		})

		afterAll(async () => {
			await app.stopApp()
		})
	})

	describe('Swagger disabled', () => {
		let testUrl = 'testUrl'
		let configMock: ConfigContract
		let routerMock: RouterContract
		let adonisApp: AdonisApplication

		beforeAll(async () => {
			configMock = mock(Config)
			when(configMock.get('swagger.uiEnabled')).thenReturn(false)
			when(configMock.get('swagger.specEnabled')).thenReturn(false)

			routerMock = mock(Router)
			when(routerMock.get(testUrl, anything())).thenReturn({} as any)

			adonisApp = await createAdonisApp({
				'Adonis/Core/Config': instance(configMock),
				'Adonis/Core/Route': instance(routerMock),
			})
		})

		it('should not init swagger module, swagger was disabled', async () => {
			const swaggerProvider = new SwaggerProvider(adonisApp.application)
			await swaggerProvider.register()
			await swaggerProvider.boot()

			verify(configMock.get('swagger.specEnabled')).never()
			verify(configMock.get('swagger.uiEnabled')).never()
			verify(configMock.get('swagger.uiUrl', 'docs')).never()
			verify(configMock.get('swagger.specUrl')).never()

			verify(routerMock.get(testUrl, anything())).never()
		})

		afterAll(async () => {
			await adonisApp.stopApp()
		})
	})
})
Example #19
Source File: userStorage.spec.ts    From space-sdk with MIT License 4 votes vote down vote up
initStubbedStorage = (): { storage: UserStorage; mockBuckets: Buckets } => {
  const mockBuckets: Buckets = mock();
  when(mockBuckets.getOrCreate(anyString(), anything())).thenReturn(
    Promise.resolve({
      root: {
        ...mock<Root>(),
        key: 'myBucketKey',
      },
    }),
  );

  // const mockMetadataStore: UserMetadataStore = mock();
  // when(mockMetadataStore.findBucket(anyString())).thenReturn(Promise.resolve(undefined));
  // when(mockMetadataStore.createBucket(anyString(), anyString())).thenReturn(Promise.resolve({
  //   slug: 'myBucketKey',
  //   encryptionKey: new Uint8Array(80),
  //   dbId: 'dbId',
  // }));

  const storage = new UserStorage(
    {
      identity: mockIdentity,
      token: '',
      endpoint: 'http://space-auth-endpoint.com',
      storageAuth: {
        key: 'random-key',
        token: 'token',
        sig: 'sig',
        msg: 'msg',
      },
    },
    {
      bucketsInit: () => instance(mockBuckets),
      metadataStoreInit: async (): Promise<UserMetadataStore> =>
        // commenting this out now because it causes test to silently fail
        // return instance(mockMetadataStore); // to be fixed later
        // eslint-disable-next-line implicit-arrow-linebreak
        Promise.resolve({
          createBucket(bucketSlug: string, dbId: string): Promise<BucketMetadata> {
            return Promise.resolve({
              bucketKey: 'testkey',
              slug: 'myBucketKey',
              encryptionKey: new Uint8Array(80),
              dbId: 'dbId',
            });
          },
          findBucket(bucketSlug: string): Promise<BucketMetadata | undefined> {
            return Promise.resolve({
              bucketKey: 'testkey',
              slug: 'myBucketKey',
              encryptionKey: new Uint8Array(80),
              dbId: 'dbId',
            });
          },
          listBuckets(): Promise<BucketMetadata[]> {
            return Promise.resolve([]);
          },
          upsertFileMetadata(input: FileMetadata): Promise<FileMetadata> {
            return Promise.resolve({ ...input, bucketSlug: 'myBucket', dbId: '', path: '/' });
          },
          findFileMetadata(bucketSlug, dbId, path): Promise<FileMetadata | undefined> {
            return Promise.resolve({
              uuid: 'generated-uuid',
              mimeType: 'generic/type',
              encryptionKey,
              bucketSlug,
              dbId,
              path,
            });
          },
          findFileMetadataByUuid(): Promise<FileMetadata | undefined> {
            return Promise.resolve({
              mimeType: 'generic/type',
              bucketSlug: 'myBucket',
              bucketKey: 'myBucketKey',
              dbId: 'mockThreadId',
              path: '/',
              encryptionKey,
            });
          },
          setFilePublic(_metadata: FileMetadata): Promise<void> {
            return Promise.resolve();
          },
          async upsertSharedWithMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
            return data;
          },
          async listSharedWithMeFiles(): Promise<SharedFileMetadata[]> {
            return [];
          },
          async upsertSharedByMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
            return data;
          },
          async findSharedFilesByInvitation(id: string): Promise<SharedFileMetadata | undefined> {
            return undefined;
          },
          async listSharedByMeFiles(): Promise<SharedFileMetadata[]> {
            return [];
          },
          async addUserRecentlySharedWith(data: ShareUserMetadata): Promise<ShareUserMetadata> {
            return data;
          },
          async listUsersRecentlySharedWith(): Promise<ShareUserMetadata[]> {
            return [];
          },
          async getNotificationsLastSeenAt():Promise<number> {
            return Date.now();
          },
          async setNotificationsLastSeenAt(timestamp:number):Promise<void> {
            noop;
          },
        }),
    },
  );

  return { storage, mockBuckets };
}
Example #20
Source File: checkbox-group.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgCheckboxGroupComponent', () => {
  let fixture: ComponentFixture<TestCheckboxGroupComponent>;
  let groupDebugElement: DebugElement;
  let errorDebugElement: DebugElement;
  let hintDebugElement: DebugElement;
  let fieldsetDebugElement: DebugElement;
  let checkboxDebugElements: Array<DebugElement>;

  let groupInstance: LgCheckboxGroupComponent;
  let checkboxInstances: Array<LgToggleComponent>;
  let component: TestCheckboxGroupComponent;
  let errorStateMatcherMock: LgErrorStateMatcher;

  beforeEach(waitForAsync(() => {
    errorStateMatcherMock = mock(LgErrorStateMatcher);

    TestBed.configureTestingModule({
      imports: [ FormsModule, ReactiveFormsModule ],
      declarations: [
        TestCheckboxGroupComponent,
        LgCheckboxGroupComponent,
        LgToggleComponent,
        MockComponents(LgValidationComponent, LgHintComponent, LgIconComponent),
      ],
      providers: [
        {
          provide: LgErrorStateMatcher,
          useFactory: () => instance(errorStateMatcherMock),
        },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(TestCheckboxGroupComponent);
    component = fixture.componentInstance;

    groupDebugElement = fixture.debugElement.query(
      By.directive(LgCheckboxGroupComponent),
    );

    groupInstance = groupDebugElement.injector.get<LgCheckboxGroupComponent>(
      LgCheckboxGroupComponent,
    );

    hintDebugElement = fixture.debugElement.query(By.directive(LgHintComponent));

    fieldsetDebugElement = fixture.debugElement.query(By.css('fieldset'));

    checkboxDebugElements = fixture.debugElement.queryAll(By.css('lg-toggle'));

    checkboxInstances = checkboxDebugElements.map(debugEl => debugEl.componentInstance);

    fixture.detectChanges();
  }));

  it('sets the correct variant based on the selector', () => {
    fixture.detectChanges();

    expect(groupInstance.variant === 'filter').toBe(true);
  });

  it('sets the correct style variant on the toggle button based on the selector', () => {
    expect(fixture.debugElement.query(By.css('label')).nativeElement).toHaveClass(
      'lg-toggle__label--filter',
    );
  });

  it('adds the tabindex attribute to the fieldset element', () => {
    expect(fieldsetDebugElement.nativeElement.getAttribute('tabindex')).toBeNull();

    groupInstance.focus = true;
    fixture.detectChanges();

    expect(fieldsetDebugElement.nativeElement.getAttribute('tabindex')).toBe('-1');
  });

  it('sets all checkbox buttons to the same name', () => {
    expect(groupInstance.name.length > 0).toBe(true);
    const name = checkboxInstances.pop().name;

    for (const checkbox of checkboxInstances) {
      expect(checkbox.name).toBe(name);
    }
  });

  it('checks the selected checkbox button when a value is provided', () => {
    groupInstance.value = [ 'red' ];
    fixture.detectChanges();
    const checkedOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.checked === true,
    );

    expect(checkedOption.componentInstance.value).toContain('red');
  });

  it('unchecks the selected checkbox buttons when an empty array value is provided', () => {
    groupInstance.value = [ 'red' ];
    fixture.detectChanges();
    groupInstance.value = [];
    fixture.detectChanges();
    const checkedOptions: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.checked === true,
    );

    expect(checkedOptions).not.toBeDefined();
  });

  it('uses same unique id when setting the group id and the group name', () => {
    const checkboxGroupNextUniqueId = groupInstance['nextUniqueId'];
    const checkboxGroupId = groupInstance.id;
    const checkboxGroupName = groupInstance.name;

    expect(checkboxGroupId).toBe(`lg-checkbox-group-id-${checkboxGroupNextUniqueId}`);
    expect(checkboxGroupName).toBe(`lg-checkbox-group-${checkboxGroupNextUniqueId}`);
  });

  it('sets unique ids on all the checkbox buttons', () => {
    const checkboxIds = checkboxInstances.map(({ id }) => id);

    expect(new Set(checkboxIds).size).toBe(checkboxIds.length);

    for (const id of checkboxIds) {
      expect(/lg-toggle-\d{1,3}/.test(id)).toBe(true);
    }
  });

  it('marks the selected checkbox when the value is changed', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();
    const selected = checkboxInstances.find(checkbox => checkbox.value === 'red');

    expect(selected.checked).toBe(true);
    const notSelected = checkboxInstances.filter(checkbox => checkbox.value !== 'red');

    for (const checkbox of notSelected) {
      expect(checkbox.checked).toBe(false);
    }
  });

  it('updates the model value when a checkbox option is checked', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value).toContain('red');
  });

  it('updates the model value when multiple checkbox options are selected', () => {
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );
    const blueOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'blue',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    blueOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(2);
    expect(component.form.controls.color.value).toContain('red');
    expect(component.form.controls.color.value).toContain('blue');
  });

  it('updates the model value when selected checkbox options are unselected', () => {
    groupInstance.value = [ 'red', 'blue' ];
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(2);
    const redOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'red',
    );
    const blueOption: DebugElement = checkboxDebugElements.find(
      checkboxDebugElement => checkboxDebugElement.componentInstance.value === 'blue',
    );

    redOption.query(By.css('input')).triggerEventHandler('click', null);
    blueOption.query(By.css('input')).triggerEventHandler('click', null);
    fixture.detectChanges();

    expect(component.form.controls.color.value.length).toBe(0);
  });

  it('links the hint to the fieldset with the correct aria attributes', () => {
    expect(hintDebugElement.nativeElement.getAttribute('id').length).not.toEqual(0);

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedBy')).toContain(
      hintDebugElement.nativeElement.getAttribute('id'),
    );
  });

  it('links the error to the fieldset with the correct aria attributes', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();
    errorDebugElement = fixture.debugElement.query(By.directive(LgValidationComponent));

    expect(errorDebugElement.nativeElement.getAttribute('id').length).not.toEqual(0);

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedBy')).toContain(
      errorDebugElement.nativeElement.getAttribute('id'),
    );
  });

  it('combines both the hint and error ids to create the aria described attribute', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();
    errorDebugElement = fixture.debugElement.query(By.directive(LgValidationComponent));

    const errorId = errorDebugElement.nativeElement.getAttribute('id');
    const hintId = hintDebugElement.nativeElement.getAttribute('id');

    fixture.detectChanges();

    expect(fieldsetDebugElement.nativeElement.getAttribute('aria-describedby')).toBe(
      `${hintId} ${errorId}`,
    );
  });

  it('disables the options when the disabled property is set', () => {
    component.form.controls.color.disable();
    fixture.detectChanges();

    for (const checkbox of checkboxInstances) {
      expect(checkbox.disabled).toBe(true);
    }
  });

  it('adds the error class if the form field is invalid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(true);
    fixture.detectChanges();

    expect(groupDebugElement.nativeElement.className).toContain(
      'lg-checkbox-group--error',
    );
  });

  it('removes the error class if the form field is valid', () => {
    when(errorStateMatcherMock.isControlInvalid(anything(), anything())).thenReturn(
      false,
    );

    fixture.detectChanges();

    expect(groupDebugElement.nativeElement.className).not.toContain(
      'lg-checkbox-group--error',
    );
  });
});
Example #21
Source File: internal.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test('signTransaction invoice errors', async() => {
    const env = newTestEnv();
    const subsidizer = PrivateKey.random();
    const [client, txClientV4] = [env.client, env.txClientV4];
    const [sender, destination] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];

    const tx = new SolanaTransaction({
        feePayer: subsidizer.publicKey().solanaKey(),
        recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
    }).add(
        Token.createTransferInstruction(
            TOKEN_PROGRAM_ID,
            sender.solanaKey(),
            destination.solanaKey(),
            sender.solanaKey(),
            [],
            100,
        )
    );

    const invoices = [
        invoiceToProto({
            Items: [
                {
                    title: "1",
                    description: "2",
                    amount: new BigNumber(10),
                },
            ]
        }),
        invoiceToProto({
            Items: [
                {
                    title: "3",
                    description: "4",
                    amount: new BigNumber(10),
                },
            ]
        }),
        invoiceToProto({
            Items: [
                {
                    title: "5",
                    description: "6",
                    amount: new BigNumber(10),
                },
            ]
        }),
    ];

    when(txClientV4.signTransaction(anything(), anything(), anything()))
        .thenCall((req: transactionpbv4.SignTransactionRequest, md: grpc.Metadata, callback) => {
            const err = validateHeaders(md);
            if (err != undefined) {
                callback(err, undefined);
                return;
            }

            expect(Buffer.from(req.getTransaction()!.getValue_asU8())).toStrictEqual(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            }));

            const invoiceErrors = new Array<commonpb.InvoiceError>(3);
            for (let i = 0; i < invoices.length; i++) {
                invoiceErrors[i] = new commonpb.InvoiceError();
                invoiceErrors[i].setOpIndex(i);
                invoiceErrors[i].setReason(i + 1);
                invoiceErrors[i].setInvoice(invoices[i]);
            }

            const resp = new transactionpbv4.SignTransactionResponse();
            resp.setResult(transactionpbv4.SignTransactionResponse.Result.INVOICE_ERROR);
            resp.setInvoiceErrorsList(invoiceErrors);

            callback(undefined, resp);
        });

    const result = await client.signTransaction(tx);
    expect(result.InvoiceErrors).toHaveLength(3);
    result.InvoiceErrors?.forEach((err, i) => {
        expect(err.getOpIndex()).toBe(i);
        expect(err.getReason()).toBe((i + 1) as commonpb.InvoiceError.Reason);
        expect(err.getInvoice()).toBe(invoices[i]);
    });
});
Example #22
Source File: feature-toggle.directive.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgFeatureToggleDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let directive: LgFeatureToggleDirective;
  const lgFeatureToggleServiceMock = mock(LgFeatureToggleService);

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent, LgFeatureToggleDirective ],
      providers: [
        TemplateRef,
        ViewContainerRef,
        {
          provide: LgFeatureToggleService,
          useFactory: () => instance(lgFeatureToggleServiceMock),
        },
        LgFeatureToggleDirective,
      ],
    });

    fixture = TestBed.createComponent(TestComponent);
    directive = TestBed.inject(LgFeatureToggleDirective);
  });

  describe('when the toggle is set to true', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: true }));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the toggle is set to false', () => {
    it('should disable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: false }));
      fixture.detectChanges();

      const de = fixture.debugElement.query(By.css('#feature'));

      expect(de).toBeNull();
    });
  });

  describe('when the toggle is set to undefined', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the defaultHide is set to False and feature is undefined', () => {
    it('should enable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));
      directive.setOptions(null);
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('when the defaultHide is set to True and feature is undefined', () => {
    it('should disable a feature', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({ feature: undefined }));

      directive.setOptions({
        defaultHide: true,
      } as LgFeatureToggleOptions);

      const de = fixture.debugElement.query(By.css('#feature'));

      expect(de).toBeNull();
    });
  });

  describe('when toggles$ returns an empty object', () => {
    it('should enable the elements that have the lgFeatureToggle directive', () => {
      when(lgFeatureToggleServiceMock.toggles$).thenReturn(of({}));
      fixture.detectChanges();

      const el = fixture.debugElement.query(By.css('#feature')).nativeElement;

      expect(el.innerText).toEqual('Test feature');
    });
  });

  describe('cleanup', () => {
    it('should unsubscribe only when there is a subscription in ngOnDestroy', () => {
      const mockSubscription = jasmine.createSpyObj('Subscription', [ 'unsubscribe' ]);

      directive.subscription = mockSubscription;

      directive.ngOnDestroy();

      expect(mockSubscription.unsubscribe).toHaveBeenCalledTimes(1);
    });
  });
});
Example #23
Source File: userStorage.spec.ts    From space-sdk with MIT License 4 votes vote down vote up
describe('UserStorage', () => {
  describe('createFolder()', () => {
    it('should throw error if user is not authenticated', async () => {
      const storage = new UserStorage({ identity: mockIdentity, token: '', endpoint: '' });
      await expect(storage.createFolder({ bucket: '', path: '' })).to.eventually.be.rejectedWith(UnauthenticatedError);
    });

    it('should push empty .keep file to bucket at specified path', async () => {
      const createFolderRequest = { bucket: 'personal', path: 'topLevel' };
      const { storage, mockBuckets } = initStubbedStorage();

      await storage.createFolder(createFolderRequest);

      verify(
        mockBuckets.pushPath(
          'myBucketKey',
          '.keep',
          deepEqual({
            path: '/topLevel/.keep',
            content: Buffer.from(''),
          }),
        ),
      ).called();
    });
  });

  describe('listDirectory()', () => {
    it('should throw error if user is not authenticated', async () => {
      const storage = new UserStorage({ identity: mockIdentity, token: '', endpoint: '' });
      await expect(storage.listDirectory({ bucket: 'bucket', path: '' })).to.eventually.be.rejectedWith(
        UnauthenticatedError,
      );
    });

    it('should return list of items', async () => {
      const listDirectoryRequest = { bucket: 'personal', path: 'topLevel' };

      const mainItem = mock<PathItem>();

      const childItem = {
        name: 'folder',
        path: '/ipfs/Qm123/folder',
        cid: 'Qm...',
        isDir: true,
        size: 10,
      };

      const updatedAt = (new Date().getMilliseconds()) * 1000000;

      const { storage, mockBuckets } = initStubbedStorage();
      when(mockBuckets.listPath('myBucketKey', `/${listDirectoryRequest.path}`, 0)).thenResolve({
        item: {
          ...mainItem,
          items: [
            {
              ...childItem,
              metadata: {
                updatedAt,
                roles: new Map(),
              },
              items: [],
              count: 1,
            },
          ],
        },
      });

      const mockMembers = new Map<string, PathAccessRole>();
      const pubkey = 'bbaareieswor4fnmzdwmv6fwij2rxyyjmpc2izognkiqnfxlvnzzsvs7y5y';
      mockMembers.set(pubkey, PathAccessRole.PATH_ACCESS_ROLE_WRITER);
      when(mockBuckets.pullPathAccessRoles(anyString(), anyString())).thenResolve(mockMembers);

      const result = await storage.listDirectory(listDirectoryRequest);

      const expectedDate = dayjs(new Date(Math.round(updatedAt / 1000000))).format();

      expect(result).to.not.equal(undefined);
      expect(result.items[0]).to.not.equal(undefined);
      expect(result.items[0].name).to.equal(childItem.name);
      expect(result.items[0].bucket).to.not.be.empty;
      expect(result.items[0].dbId).to.not.be.empty;
      expect(result.items[0].ipfsHash).to.equal(childItem.cid);
      expect(result.items[0].isDir).to.equal(childItem.isDir);
      expect(result.items[0].sizeInBytes).to.equal(childItem.size);
      expect(result.items[0].created).to.equal(expectedDate);
      expect(result.items[0].updated).to.equal(expectedDate);
      expect(result.items[0].fileExtension).to.equal('');
      expect(result.items[0].isLocallyAvailable).to.equal(false);
      expect(result.items[0].backupCount).to.equal(1);
      expect(result.items[0].members).to.deep.equal([{
        publicKey: Buffer.from(tryParsePublicKey(pubkey).pubKey).toString('hex'),
        role: PathAccessRole.PATH_ACCESS_ROLE_WRITER,
        address: GetAddressFromPublicKey(pubkey),
      }]);
      expect(result.items[0].isBackupInProgress).to.equal(false);
      expect(result.items[0].isRestoreInProgress).to.equal(false);
      expect(result.items[0].uuid).to.equal('generated-uuid');
    });
  });

  describe('openFile()', () => {
    // it('should throw error if user is not authenticated', async () => {
    //   const storage = new UserStorage({ identity: mockIdentity, token: '' });
    //   await expect(storage.openFile({ bucket: 'bucket', path: '' })).to.eventually.be.rejectedWith(
    //     UnauthenticatedError,
    //   );
    // });

    it('should throw if file is not found', async () => {
      const { storage, mockBuckets } = initStubbedStorage();
      when(mockBuckets.pullPath('myBucketKey', '/file.txt', anything())).thenThrow(
        new Error('Error: no link named "file.txt" under QmVQWu2C3ZgdoAmBsffFASrgynAfgvYX8CCK4o9SxRvC4p'),
      );

      await expect(storage.openFile({ bucket: 'personal', path: '/file.txt' })).to.eventually.be.rejectedWith(
        DirEntryNotFoundError,
      );
    });

    it('should return a valid stream of files data', async () => {
      const { storage, mockBuckets } = initStubbedStorage();
      const actualFileContent = "file.txt's file content";

      when(mockBuckets.pullPath('myBucketKey', '/file.txt', anything())).thenReturn(
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        newEncryptedDataWriter(actualFileContent, decodeFileEncryptionKey(encryptionKey)),
      );

      const result = await storage.openFile({ bucket: 'personal', path: '/file.txt' });
      const filesData = await result.consumeStream();

      expect(new TextDecoder('utf8').decode(filesData)).to.equal(actualFileContent);
      expect(result.mimeType).to.equal('generic/type');
    });
  });

  describe('openFileByUuid', () => {
    // it('should throw if uuid is not found', async () => {
    //  // fix this when mocking metadatastore works
    // });

    it('should return a valid stream of files data', async () => {
      const { storage, mockBuckets } = initStubbedStorage();
      const fileUuid = v4();
      const actualFileContent = "file.txt's file content";
      when(mockBuckets.existing('mockThreadId')).thenReturn(Promise.resolve([
        {
          ...mock<Root>(),
          name: 'myBucket',
          key: 'myBucketKey',
        },
      ]));
      when(mockBuckets.listPath('myBucketKey', anyString())).thenResolve({
        item: {
          ...mock<PathItem>(),
          name: 'file.txt',
          path: '/ipfs/Qm123/file.txt',
          metadata: {
            updatedAt: (new Date().getMilliseconds()) * 1000000,
            roles: new Map(),
          },
          items: [],
        },
      });

      when(mockBuckets.pullPath('myBucketKey', anyString(), anything())).thenReturn(
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        newEncryptedDataWriter(actualFileContent, decodeFileEncryptionKey(encryptionKey)),
      );

      const mockMembers = new Map<string, PathAccessRole>();
      mockMembers.set('dummykey', PathAccessRole.PATH_ACCESS_ROLE_WRITER);
      when(mockBuckets.pullPathAccessRoles('myBucketKey', '/ipfs/Qm123/file.txt')).thenResolve(mockMembers);

      const result = await storage.openFileByUuid({ uuid: fileUuid });
      const filesData = await result.consumeStream();

      expect(new TextDecoder('utf8').decode(filesData)).to.equal(actualFileContent);
      expect(result.mimeType).to.equal('generic/type');
      expect(result.entry.bucket).to.not.be.empty;
      expect(result.entry.dbId).to.not.be.empty;
    });
  });

  describe('addItems()', () => {
    it('should publish data, error and done events correctly', async () => {
      const { storage, mockBuckets } = initStubbedStorage();
      const uploadError = new Error('update is non-fast-forward');
      when(mockBuckets.pushPath('myBucketKey', anyString(), anything(), anything())).thenResolve({
        ...mock<PushPathResult>(),
      });

      const childItem = {
        name: 'entryName',
        path: '/ipfs/Qm123/entryName',
        cid: 'Qm...',
        isDir: false,
        size: 10,
      };

      when(mockBuckets.listPath('myBucketKey', anyString())).thenResolve({
        item: {
          ...mock<PathItem>(),
          name: 'entryName',
          path: '/ipfs/Qm123/entryName',
          cid: 'Qm...',
          isDir: false,
          size: 10,
          metadata: {
            updatedAt: (new Date().getMilliseconds()) * 1000000,
            roles: new Map<string, PathAccessRole>(),
          },
          count: 0,
          items: [],
        },
      });

      // fail upload of b.txt
      when(mockBuckets.pushPath('myBucketKey', '/b.txt', anything(), anything())).thenReject(uploadError);
      const callbackData = {
        data: [] as AddItemsEventData[],
        error: [] as AddItemsEventData[],
        done: [] as AddItemsEventData[],
      };

      // upload files
      const uploadResponse = await storage.addItems({
        bucket: 'personal',
        files: [
          {
            path: '/top/a.txt',
            data: 'a content',
            mimeType: 'text/plain',
          },
          {
            path: 'b.txt',
            data: 'b content',
            mimeType: 'text/plain',
          },
        ],
      });

      // listen for status events
      uploadResponse.on('data', (it) => callbackData.data.push(it));
      uploadResponse.on('error', (err) => callbackData.error.push(err));
      await new Promise((resolve) => {
        uploadResponse.once('done', (it) => {
          callbackData.done.push(it);
          resolve();
        });
      });

      // verify callback data
      expect(callbackData.data).to.containSubset([
        { path: '/top/a.txt', status: 'success' },
        { path: '/top', status: 'success' },
      ]);
      expect(callbackData.error).to.containSubset([{ path: '/b.txt', status: 'error', error: uploadError }]);
      expect(callbackData.done).to.containSubset([
        {
          bucket: 'personal',
          files: [
            { path: '/top', status: 'success' },
            { path: '/top/a.txt', status: 'success' },
            { path: '/b.txt', status: 'error', error: uploadError },
          ],
        },
      ]);
    });
  });

  describe('shareViaPublicKey()', () => {
    let storage: UserStorage;
    let mockBuckets: Buckets;

    beforeEach(() => {
      const stub = initStubbedStorage();
      storage = stub.storage;
      mockBuckets = stub.mockBuckets;
    });

    it('should throw if public keys are empty', async () => {
      await expect(
        storage.shareViaPublicKey({
          publicKeys: [],
          paths: [
            {
              bucket: 'personal',
              path: '/randomPath',
              uuid: v4(),
            },
          ],
        }),
      ).to.eventually.be.rejected;
    });

    it('should throw if public keys are not valid', async () => {
      await expect(
        storage.shareViaPublicKey({
          publicKeys: [{
            id: '[email protected]',
            pk: 'invalid-pk-provided',
          }],
          paths: [
            {
              bucket: 'personal',
              path: '/randomPath',
              uuid: v4(),
            },
          ],
        }),
      ).to.eventually.be.rejectedWith('Unsupported encoding: i');
    });
  });
});
Example #24
Source File: brand-icon.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgBrandIconComponent', () => {
  let component: LgBrandIconComponent;
  let fixture: ComponentFixture<LgBrandIconComponent>;
  let brandIconRegistryMock: LgBrandIconRegistry;

  beforeEach(waitForAsync(() => {
    brandIconRegistryMock = mock(LgBrandIconRegistry);

    TestBed.configureTestingModule({
      declarations: [ LgBrandIconComponent ],
      providers: [
        {
          provide: LgBrandIconRegistry,
          useFactory: () => instance(brandIconRegistryMock),
        },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LgBrandIconComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should add the generic brand-icon class', () => {
    expect(fixture.nativeElement.getAttribute('class')).toContain('lg-brand-icon');
  });

  it('should set `aria-hidden` to true', () => {
    expect(fixture.nativeElement.getAttribute('aria-hidden')).toBe('true');
  });

  describe('setting the name', () => {
    it('should append the correct svg element to the component', () => {
      expect(fixture.nativeElement.querySelector('#test')).toBeNull();
      expect(fixture.nativeElement.querySelector('svg')).toBeNull();

      when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
        '<svg id="test">test-svg<path id="lg-icon-fill-primary"></path></svg>',
      );

      component.name = 'sun';
      fixture.detectChanges();

      expect(fixture.nativeElement.querySelector('#test')).toBeNull();

      expect(
        /lg-brand-icon-\d-\d/.test(
          fixture.nativeElement.querySelector('svg').getAttribute('id'),
        ),
      ).toBeTrue();

      const pathEl = fixture.nativeElement.querySelector('path');

      expect(pathEl.getAttribute('id')).not.toContain('lg-icon-fill-primary');
      expect(pathEl.getAttribute('data-colour')).toContain('lg-icon-fill-primary');
    });
  });

  describe('the colour input', () => {
    beforeEach(() => {
      when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
        '<svg id="test">test-svg<path id="lg-icon-fill-primary"></path></svg>',
      );

      component.name = 'sun';
    });

    describe('when not specified', () => {
      it('shouldn\'t set the fill colour', () => {
        fixture.detectChanges();
        const el = fixture.nativeElement.querySelector(
          '[data-colour="lg-icon-fill-primary"]',
        );

        expect(el.style.fill).toEqual('');
      });
    });

    describe('when specified', () => {
      it('should apply the specific colour', () => {
        component.colour = '--colour-css-variable';
        fixture.detectChanges();
        const el = fixture.nativeElement.querySelector(
          '[data-colour="lg-icon-fill-primary"]',
        );

        expect(el.style.fill).toEqual('var(--colour-css-variable)');
      });
    });
  });

  it('when the icon isn\'t coloured it should not set the fill style', () => {
    when(brandIconRegistryMock.getBrandIcon('sun')).thenReturn(
      '<svg id="test">test-svg<path id="no-color"></path></svg>',
    );

    component.name = 'sun';

    fixture.detectChanges();
    const el = fixture.nativeElement.querySelector('path[id^="lg-brand-icon-"]');

    expect(el.getAttribute('data-colour')).toBeNull();
    expect(el.style.fill).toEqual('');
  });

  describe('the size input', () => {
    describe('when not specified', () => {
      it('should set the `sm` class modifier', () => {
        expect(fixture.nativeElement.getAttribute('class')).toContain(
          'lg-brand-icon--sm',
        );
      });
    });

    describe('when specified', () => {
      it('should set the correct class modifier', () => {
        component.size = 'md';
        fixture.detectChanges();

        expect(fixture.nativeElement.getAttribute('class')).not.toContain(
          'lg-brand-icon--sm',
        );

        expect(fixture.nativeElement.getAttribute('class')).toContain(
          'lg-brand-icon--md',
        );
      });
    });
  });
});
Example #25
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch", async() => {
    const sender = PrivateKey.random();

    const expectedDestinations: PublicKey[] = [];
    const earns = new Array<Earn>();
    for (let i = 0; i < 15; i++) {
        const dest = PrivateKey.random();
        earns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        });
        expectedDestinations.push(dest.publicKey());
    }
    const invoiceEarns = new Array<Earn>();
    for (let i = 0; i < 15; i++) {
        const dest = PrivateKey.random();
        invoiceEarns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
            invoice: {
                Items: [
                    {
                        title: "test",
                        amount: new BigNumber(i + 1),
                    }
                ]
            },
        });
    }

    const batches: EarnBatch[] = [
        {
            sender: sender,
            earns: earns,
            dedupeId: Buffer.from(uuidv4())
        },
        {
            sender: sender,
            earns: earns,
            memo: "somememo",
        },
        {
            sender: sender,
            earns: invoiceEarns,
        },
    ];
    
    let signReq: signRequest | undefined;
    let submitReq: submitRequest | undefined;

    const internal = mock(InternalClient);
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList) => {
            // Make a copy of the transaction since we're modifying it

            signReq = {tx: Transaction.from(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            })), il};

            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
    .thenCall((tx: Transaction, il?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            submitReq = {tx, il, commitment, dedupeId};

            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;

            return Promise.resolve(result);
        });

    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);    

    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });

    for (const b of batches) {
        signReq = undefined;
        submitReq = undefined;

        const result = await client.submitEarnBatch(b);
        expect(result.txId.length).toEqual(64);
        expect(result.txId.equals(Buffer.alloc(64).fill(0))).toBeFalsy();
        expect(result.txError).toBeUndefined();
        expect(result.earnErrors).toBeUndefined();

        expect(signReq).toBeDefined();

        const signTx = signReq!.tx;
        expect(signTx.signatures).toHaveLength(2);
        expect(signTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(signTx.signatures[0].signature).toBeNull();
        expect(signTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(signTx.serializeMessage(), signTx.signatures[1].signature!)).toBeTruthy();

        const memoInstruction = MemoInstruction.decodeMemo(signTx.instructions[0]);
        
        if (b.memo) { 
            expect(memoInstruction.data).toEqual(b.memo);
        } else if (b.earns[0].invoice) {
            const serialized = submitReq!.il!.serializeBinary();
            const buf = Buffer.from(hash.sha224().update(serialized).digest('hex'), "hex");
            const expected = Memo.new(1, TransactionType.Earn, 1, buf);
            
            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        } else {
            // since we have an app index configured, we still expect a memo
            const expected = Memo.new(1, TransactionType.Earn, 1, Buffer.alloc(29));
            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        }
        
        expect(signTx.instructions).toHaveLength(16);  // including memo

        for (let i = 0; i < 15; i++) {
            const tokenInstruction = TokenInstruction.decodeTransfer(signTx.instructions[i + 1]);    
            expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);

            expect(tokenInstruction.dest.toBuffer()).toEqual(b.earns[i].destination.buffer);
            expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.amount).toEqual(BigInt((i + 1)));
        }
        
        expect(submitReq).toBeDefined();
        expect(submitReq!.dedupeId).toEqual(b.dedupeId);
        
        const submitTx = submitReq!.tx;
        expect(submitTx.signatures).toHaveLength(2);
        expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(subsidizerKey.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
        expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

        expect(submitTx.serializeMessage()).toEqual(signTx.serializeMessage());
    }
});
Example #26
Source File: post.controller.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 4 votes vote down vote up
describe('Post Controller', () => {
  describe('Replace PostService in provider(useClass: PostServiceStub)', () => {
    let controller: PostController;

    beforeEach(async () => {
      const module: TestingModule = await Test.createTestingModule({
        providers: [
          {
            provide: PostService,
            useClass: PostServiceStub,
          },
        ],
        controllers: [PostController],
      }).compile();

      controller = await module.resolve<PostController>(PostController);
    });

    it('should be defined', () => {
      expect(controller).toBeDefined();
    });

    it('GET on /posts should return all posts', async () => {
      const posts = await lastValueFrom(controller.getAllPosts());
      expect(posts.length).toBe(3);
    });

    it('GET on /posts/:id should return one post ', (done) => {
      controller.getPostById('1').subscribe((data) => {
        expect(data._id).toEqual('1');
        done();
      });
    });

    it('POST on /posts should save post', async () => {
      const post: CreatePostDto = {
        title: 'test title',
        content: 'test content',
      };
      const saved = await lastValueFrom(
        controller.createPost(
          post,
          createMock<Response>({
            location: jest.fn().mockReturnValue({
              status: jest.fn().mockReturnValue({
                send: jest.fn().mockReturnValue({
                  headers: { location: '/posts/post_id' },
                  status: 201,
                }),
              }),
            }),
          }),
        ),
      );
      // console.log(saved);
      expect(saved.status).toBe(201);
    });

    it('PUT on /posts/:id should update the existing post', (done) => {
      const post: UpdatePostDto = {
        title: 'test title',
        content: 'test content',
      };
      controller
        .updatePost(
          '1',
          post,
          createMock<Response>({
            status: jest.fn().mockReturnValue({
              send: jest.fn().mockReturnValue({
                status: 204,
              }),
            }),
          }),
        )
        .subscribe((data) => {
          expect(data.status).toBe(204);
          done();
        });
    });

    it('DELETE on /posts/:id should delete post', (done) => {
      controller
        .deletePostById(
          '1',
          createMock<Response>({
            status: jest.fn().mockReturnValue({
              send: jest.fn().mockReturnValue({
                status: 204,
              }),
            }),
          }),
        )
        .subscribe((data) => {
          expect(data).toBeTruthy();
          done();
        });
    });

    it('POST on /posts/:id/comments', async () => {
      const result = await lastValueFrom(
        controller.createCommentForPost(
          'testpost',
          { content: 'testcomment' },
          createMock<Response>({
            location: jest.fn().mockReturnValue({
              status: jest.fn().mockReturnValue({
                send: jest.fn().mockReturnValue({
                  headers: { location: '/posts/post_id/comments/comment_id' },
                  status: 201,
                }),
              }),
            }),
          }),
        ),
      );

      expect(result.status).toBe(201);
    });

    it('GET on /posts/:id/comments', async () => {
      const result = await lastValueFrom(
        controller.getAllCommentsOfPost('testpost'),
      );

      expect(result.length).toBe(1);
    });
  });

  describe('Replace PostService in provider(useValue: fake object)', () => {
    let controller: PostController;

    beforeEach(async () => {
      const module: TestingModule = await Test.createTestingModule({
        providers: [
          {
            provide: PostService,
            useValue: {
              findAll: (_keyword?: string, _skip?: number, _limit?: number) =>
                of<any[]>([
                  {
                    _id: 'testid',
                    title: 'test title',
                    content: 'test content',
                  },
                ]),
            },
          },
        ],
        controllers: [PostController],
      }).compile();

      controller = await module.resolve<PostController>(PostController);
    });

    it('should get all posts(useValue: fake object)', async () => {
      const result = await lastValueFrom(controller.getAllPosts());
      expect(result[0]._id).toEqual('testid');
    });
  });

  describe('Replace PostService in provider(useValue: jest mocked object)', () => {
    let controller: PostController;
    let postService: PostService;

    beforeEach(async () => {
      const module: TestingModule = await Test.createTestingModule({
        providers: [
          {
            provide: PostService,
            useValue: {
              constructor: jest.fn(),
              findAll: jest
                .fn()
                .mockImplementation(
                  (_keyword?: string, _skip?: number, _limit?: number) =>
                    of<any[]>([
                      {
                        _id: 'testid',
                        title: 'test title',
                        content: 'test content',
                      },
                    ]),
                ),
            },
          },
        ],
        controllers: [PostController],
      }).compile();

      controller = await module.resolve<PostController>(PostController);
      postService = module.get<PostService>(PostService);
    });

    it('should get all posts(useValue: jest mocking)', async () => {
      const result = await lastValueFrom(controller.getAllPosts('test', 10, 0));
      expect(result[0]._id).toEqual('testid');
      expect(postService.findAll).toBeCalled();
      expect(postService.findAll).lastCalledWith('test', 0, 10);
    });
  });

  describe('Mocking PostService using ts-mockito', () => {
    let controller: PostController;
    const mockedPostService: PostService = mock(PostService);

    beforeEach(async () => {
      controller = new PostController(instance(mockedPostService));
    });

    it('should get all posts(ts-mockito)', async () => {
      when(
        mockedPostService.findAll(anyString(), anyNumber(), anyNumber()),
      ).thenReturn(
        of([
          { _id: 'testid', title: 'test title', content: 'content' },
        ]) as Observable<Post[]>,
      );
      const result = await lastValueFrom(controller.getAllPosts('', 10, 0));
      expect(result.length).toEqual(1);
      expect(result[0].title).toBe('test title');
      verify(
        mockedPostService.findAll(anyString(), anyNumber(), anyNumber()),
      ).once();
    });
  });
});
Example #27
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("mergeTokenAccounts", async() => {
    const internal = mock(InternalClient);
    const client = new Client(Environment.Test, {
        appIndex: 0,
        internal: instance(internal),
    });

    const appSubsidizer = PrivateKey.random();
    const priv = PrivateKey.random();
    
    const ownerId = new commonpbv4.SolanaAccountId();
    ownerId.setValue(priv.publicKey().buffer);

    const closeAuthId = new commonpbv4.SolanaAccountId();
    
    // No accounts to merge
    when(internal.resolveTokenAccounts(anything(), anything()))
    .thenCall(() => {
        return Promise.resolve([]);
    });
    
    let txId = await client.mergeTokenAccounts(priv, false);
    expect(txId).toBeUndefined();
    
    // One resolved account, no create assoc
    let resolvedKeys = [PrivateKey.random().publicKey()];
    let infos: accountpbv4.AccountInfo[] = [];
    
    setGetServiceConfigResp(internal);
    when(internal.resolveTokenAccounts(anything(), anything()))
    .thenCall(() => {
        infos = [];
        resolvedKeys.forEach((key, i) => {
            const id = new commonpbv4.SolanaAccountId();
            id.setValue(key.buffer);
            const info = new accountpbv4.AccountInfo();
            info.setAccountId(id);
            info.setBalance(new BigNumber(1 + i).toString());
            info.setOwner(ownerId);
            info.setCloseAuthority(closeAuthId);
            
            infos.push(info);    
        });
        return Promise.resolve(infos);
    });
    
    txId = await client.mergeTokenAccounts(priv, false);
    expect(txId).toBeUndefined();

    // Multiple accounts
    resolvedKeys = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];
    
    let signReq: signRequest | undefined;
    let submitReq: submitRequest | undefined;
    setGetRecentBlockhashResp(internal);
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList) => {
            // Make a copy of the transaction since we're modifying it
            signReq = {tx: Transaction.from(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            })), il};

            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    when(internal.submitTransaction!(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            submitReq = {tx, il: il, commitment, dedupeId};
            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;
            return Promise.resolve(result);
        });

    interface testCase {
        createAssoc: boolean;
        subsidizer?: PrivateKey;
        shouldClose: boolean;
    }

    const tcs: testCase[] = [
        {
            createAssoc: false,
            shouldClose: false,
        },
        {
            createAssoc: true,
            shouldClose: false,
        },
        {
            createAssoc: false,
            subsidizer: appSubsidizer,
            shouldClose: false,
        },
        {
            createAssoc: true,
            subsidizer: appSubsidizer,
            shouldClose: false,
        },
        {
            createAssoc: false,
            shouldClose: true,

        },
    ];

    for (const tc of tcs) {
        signReq = undefined;
        submitReq = undefined;
        
        if (tc.shouldClose) {
            if (tc.subsidizer) {
                closeAuthId.setValue(tc.subsidizer.publicKey().buffer);
            } else {
                closeAuthId.setValue(subsidizer);
            }
        } else {
            closeAuthId.setValue('');
        }

        txId = await client.mergeTokenAccounts(priv, tc.createAssoc, Commitment.Single, tc.subsidizer);
        expect(txId).toBeDefined();

        if (tc.subsidizer) {
            expect(signReq).toBeUndefined();
            expect(submitReq).toBeDefined();

            const submitTx = submitReq!.tx;
            expect(submitTx.signatures).toHaveLength(2);
            expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(tc.subsidizer.publicKey().buffer);
            expect(tc.subsidizer.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
            expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(priv.publicKey().buffer);
            expect(priv.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();
            await assertMergeTx(submitTx, priv, infos, tc.createAssoc, tc.shouldClose, Buffer.from(closeAuthId.getValue_asU8()), tc.subsidizer);

            // The returned txId should be the one in the submit request
            expect(txId!.equals(submitTx.signature!)).toBeTruthy();
        } else {
            expect(signReq).toBeDefined();
            const signTx = signReq!.tx;
            expect(signTx.signatures).toHaveLength(2);
            expect(signTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
            expect(signTx.signatures[0].signature).toBeNull();
            expect(signTx.signatures[1].publicKey.toBuffer()).toEqual(priv.publicKey().buffer);
            expect(priv.kp.verify(signTx.serializeMessage(), signTx.signatures[1].signature!)).toBeTruthy();
            await assertMergeTx(signTx, priv, infos, tc.createAssoc, tc.shouldClose, Buffer.from(closeAuthId.getValue_asU8()));
            
            expect(submitReq).toBeDefined();

            const submitTx = submitReq!.tx;
            expect(submitTx.signatures).toHaveLength(2);
            expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
            expect(subsidizerKey.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
            expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(priv.publicKey().buffer);
            expect(priv.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

            expect(submitTx.serializeMessage().equals(signTx.serializeMessage())).toBeTruthy();

            // The returned txId should be the one in the submit request
            expect(txId!.equals(submitTx.signature!)).toBeTruthy();
        }
    }
});
Example #28
Source File: ModelManager.test.ts    From aem-spa-page-model-manager with Apache License 2.0 4 votes vote down vote up
describe('ModelManager ->', () => {
    const PAGE_MODEL_LOAD_EVENT_OPTIONS = {
        detail: {
            model: PAGE_MODEL
        }
    };

    function expectPageModelLoadedEventFired() {
        expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalled();
        expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalledWith(EventType.PAGE_MODEL_LOADED, PAGE_MODEL_LOAD_EVENT_OPTIONS);
    }

    function assertAsyncModelFetched() {
        expectPageModelLoadedEventFired();

        return ModelManager.getData().then((data) => {
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
        });
    }

    function mockTheFetch(path: any, data: any) {
        REQUEST_MAP[path] = data;
    }

    let pathName = '';
    let metaProps: { [key: string]: string } = {};
    const isRouteExcludedSpy = isRouteExcluded as jest.MockedFunction<(route: string) => boolean>;

    beforeEach(() => {
        metaProps = {};
        metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
        pathName = PAGE_PATH;

        when(ModelClientMock.fetch(anyString())).thenReturn(Promise.resolve(PAGE_MODEL));
        when(ModelClientMock.fetch(PAGE_MODEL_URL)).thenReturn(Promise.resolve(PAGE_MODEL));
        when(ModelClientMock.fetch(CHILD_MODEL_URL)).thenReturn(Promise.resolve(content_test_page_root_child0000_child0010));
        when(ModelClientMock.fetch(NON_EXISTING_MODEL_URL))
            .thenReturn(Promise.reject({ response: { status: 404, statusText: 'Could not find page' } }));
        when(ModelClientMock.fetch(ERROR_MODEL_URL)).thenReturn(Promise.reject('Some Error without json'));

        when(ModelClientMock.fetch(ERROR_MODEL_URL_404)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_404));
        when(ModelClientMock.fetch(ERROR_MODEL_URL_500)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_500));

        modelClient = instance(ModelClientMock);
        jest.spyOn(PathUtils, 'getMetaPropertyValue').mockImplementation((val) => metaProps[val]);
        jest.spyOn(PathUtils, 'dispatchGlobalCustomEvent');
        jest.spyOn(PathUtils, 'getCurrentPathname').mockImplementation(() => pathName);
        isRouteExcludedSpy.mockImplementation(() => false);
        mockTheFetch(PAGE_MODEL_URL, PAGE_MODEL);
    });

    afterEach(() => {
        reset(ModelClientMock);
        pathName = '';
    });

    describe('initialize ->', () => {
        describe('Initialization without config object ->', () => {
            it('should NOT fetch remote data on initialization when the model is provided', () => {
                return ModelManager.initialize({ model: PAGE_MODEL }).then((data) => {
                    expectPageModelLoadedEventFired();
                    expect(data).toEqual(PAGE_MODEL);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as meta property', () => {
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;

                return ModelManager.initialize().then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as currentPathname', () => {
                pathName = PAGE_MODEL_URL;

                return ModelManager.initialize().then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch remote data on initialization - root path as a parameter', () => {
                return ModelManager.initialize(PAGE_PATH).then((data) => {
                    expectPageModelLoadedEventFired();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch remote data on initialization', () => {
            return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                verify(modelClient.fetch(anyString()));
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should fail when initialized on non-browser with invlid config', () => {
            pathName = '';

            // disable console.error within the test
            jest.spyOn(console, 'error').mockImplementation();

            //simulate non browser for the test
            const windowSpy = jest.spyOn(global, 'window', 'get');

            windowSpy.mockImplementation();

            try {
                ModelManager.initialize();
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
            windowSpy.mockRestore();
        });

        it('should throw error when initialized without model url', () => {
            metaProps = {};
            pathName = '';
            try {
                ModelManager.initialize();
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
        });

        it('should throw error when initialized with invalid model url', () => {
            try {
                ModelManager.initialize({ path: '?abc' });
            } catch (err) {
                assert.strictEqual(err.name, 'Error');
            }
        });

        it('should not make concurrent server calls on duplicate request', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();
                pathName = '/content/test/duplicate/request';

                when(ModelClientMock.fetch(pathName)).thenReturn(new Promise((resolve) => {
                    setTimeout(() => resolve(PAGE_MODEL), 200);
                }));

                const promises: any[] = [];

                promises.push(ModelManager._fetchData(pathName));
                promises.push(ModelManager._fetchData(pathName));
                promises.push(ModelManager._fetchData(pathName));

                return Promise.all(promises).then(() => {
                    for (let i = 0; i < promises.length - 1; ++i) {
                        expect(promises[i]).toEqual(promises[i + 1]);
                    }
                });
            });
        });

        describe('when the request is for an asynchronous subpage -- ', () => {
            beforeEach(() => {
                pathName = '/content/test/pageNotInModel';
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = '/content/test';
            });

            it('should fetch data twice on initialization', () => {
                return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                    expectPageModelLoadedEventFired();
                    verify(ModelClientMock.fetch(anyString())).times(2);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });

            it('should fetch data once on initialization when sub page route path is excluded', () => {
                isRouteExcludedSpy.mockReturnValue(true);
                return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
                    expectPageModelLoadedEventFired();
                    verify(ModelClientMock.fetch(anyString())).times(1);
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
         });

        it('should not fetch data on initialization', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then((data) => {
                expectPageModelLoadedEventFired();
                // verify(ModelClientMock.fetch(anyString())).never();
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should not fetch data', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData(CHILD_PATH).then((data) => {
                    verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
                    assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
                });
            });
        });

        it('should fetch all the data', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData().then((data) => {
                    verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch data if forced', () => {
            return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
                expectPageModelLoadedEventFired();

                return ModelManager.getData({ path: CHILD_PATH, forceReload: true }).then((data) => {
                    verify(ModelClientMock.fetch(anyString())).times(1);
                    assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
                });
            });
        });
    });

    describe('initializeAsync ->', () => {
        describe('Initialization without config object ->', () => {
            it('should fetch remote data on initialization - root path as meta property', () => {
                metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
                ModelManager.initializeAsync();
                assertAsyncModelFetched();
            });

            it('should fetch remote data on initialization - root path as currentPathname', () => {
                pathName = PAGE_MODEL_URL;
                ModelManager.initializeAsync();
                assertAsyncModelFetched();
            });

            it('should initialize model store when no root path is provided', () => {
                metaProps = {};
                pathName = '';
                ModelManager.initializeAsync();

                return ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
                    assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
                });
            });
        });

        it('should fetch standalone item data', () => {
            metaProps = {};
            pathName = '';
            ModelManager.initializeAsync();

            return ModelManager.getData({ path: CHILD_PATH }).then((data) => {
                assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
            });
        });
        it('should throw error when fetching data without initialization', () => {
            ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
                assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
            });
        });

        it('should NOT fetch remote data on initialization when the model is provided', () => {
            ModelManager.initializeAsync({ model: PAGE_MODEL });
            assertAsyncModelFetched();
        });

        it('should fetch remote data on initialization - root path as a parameter', () => {
            ModelManager.initializeAsync(PAGE_PATH);
            assertAsyncModelFetched();
        });

        it('should fetch remote data on initialization', () => {
            ModelManager.initializeAsync({ path: PAGE_PATH, modelClient: modelClient });
            verify(modelClient.fetch(anyString()));
            assertAsyncModelFetched();
        });

        it('should load a 404 error page.', async () => {

            const configuration:ModelManagerConfiguration = {
                path: PAGE_PATH,
                modelClient: modelClient,
                errorPageRoot: ERROR_PAGE_ROOT
            };
            const data:Model = await ModelManager.initialize(configuration);
            verify(modelClient.fetch(anyString()));
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');

            const nonExistingData = await ModelManager._fetchData(NON_EXISTING_PATH);
            assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_404, 'data should be correct');

        });

        it('should load a 500 error page.', async () => {

            const configuration:ModelManagerConfiguration = {
                path: PAGE_PATH,
                modelClient: modelClient,
                errorPageRoot: ERROR_PAGE_ROOT
            };
            const data:Model = await ModelManager.initialize(configuration);
            verify(modelClient.fetch(anyString()));
            assert.deepEqual(data, PAGE_MODEL, 'data should be correct');

            const nonExistingData = await ModelManager._fetchData(PAGE_WITH_ERROR_PATH);
            assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_500, 'data should be correct');

        });
    });
});
Example #29
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitPayment", async() => {
    const internal = mock(InternalClient);

    let signReq: signRequest | undefined;
    let submitReq: submitRequest | undefined;
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList) => {
            // Make a copy of the transaction since we're modifying it
            signReq = {tx: Transaction.from(tx.serialize({
                requireAllSignatures: false,
                verifySignatures: false,
            })), il};
            const result = new SignTransactionResult();
            if (tx.feePayer!.toBuffer().equals(subsidizer)){
                tx.partialSign(new Account(subsidizerKey.secretKey()));
            }
            result.TxId = tx.signature ? tx.signature : undefined;
            return Promise.resolve(result);
        });
    when(internal.submitTransaction!(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            submitReq = {tx, il: il, commitment, dedupeId};
            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;
            return Promise.resolve(result);
        });
    
    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();

    const payments: Payment[] = [
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
        },
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
            dedupeId: Buffer.from(uuidv4()),
        },
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
            memo: "1-test",
        },
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
            invoice: {
                Items: [
                    {
                        title: "test",
                        amount: new BigNumber(10),
                    }
                ]
            },
        },
    ];

    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });
    for (const p of payments) {
        const txId = await client.submitPayment(p);
        
        expect(signReq).toBeDefined();
        const signTx = signReq!.tx;
        expect(signTx.signatures).toHaveLength(2);
        expect(signTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(signTx.signatures[0].signature).toBeNull();
        expect(signTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(signTx.serializeMessage(), signTx.signatures[1].signature!)).toBeTruthy();

        expect(signTx.instructions).toHaveLength(2);

        const memoInstruction = MemoInstruction.decodeMemo(signTx.instructions[0]);
        if (p.memo) {
            expect(memoInstruction.data).toEqual(p.memo);
        } else if (p.invoice) {
            const serialized = submitReq!.il!.serializeBinary();
            const buf = Buffer.from(hash.sha224().update(serialized).digest('hex'), "hex");
            const expected = Memo.new(1, p.type, 1, buf);

            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        } else {
            const expected = Memo.new(1, p.type, 1, Buffer.alloc(29));
            expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        }
        
        const tokenInstruction = TokenInstruction.decodeTransfer(signTx.instructions[1]);
        expect(tokenInstruction.source.toBuffer()).toEqual(p.sender.publicKey().buffer);
        expect(tokenInstruction.dest.toBuffer()).toEqual(p.destination.buffer);
        expect(tokenInstruction.owner.toBuffer()).toEqual(p.sender.publicKey().buffer);
        expect(tokenInstruction.amount).toEqual(BigInt(p.quarks));
        
        expect(submitReq).toBeDefined();
        expect(submitReq!.dedupeId).toEqual(p.dedupeId);

        const submitTx = submitReq!.tx;
        expect(submitTx.signatures).toHaveLength(2);
        expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(subsidizer);
        expect(subsidizerKey.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
        expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

        expect(submitTx.serializeMessage().equals(signTx.serializeMessage())).toBeTruthy();

        // The returned txId should be the one in the submit request
        expect(txId.equals(submitTx.signature!)).toBeTruthy();
    }
});