ts-mockito#mock TypeScript Examples

The following examples show how to use ts-mockito#mock. 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: client.spec.ts    From kin-node with MIT License 6 votes vote down vote up
test("submitPayment invalid", async () => {
    const internal = mock(InternalClient);
    const client = new Client(Environment.Test, {
        internal: instance(internal),
    });

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const payments: Payment[] = [
        {
            sender: sender,
            destination: dest.publicKey(),
            type: TransactionType.Spend,
            quarks: new BigNumber(11),
            invoice: {
                Items: [
                    {
                        title: "test",
                        amount: new BigNumber(10),
                    }
                ]
            },
        }
    ];

    for (const p of payments) {
        try {
            await client.submitPayment(p);
            fail();
        } catch (error) {
            expect(typeof error).toBe('string');
        }
    }
});
Example #2
Source File: app.component.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(waitForAsync(() => {
    const formBuilderMock = mock(FormBuilder);

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [MockModule(CanopyModule)],
      providers: [{ provide: FormBuilder, useFactory: () => instance(formBuilderMock) }],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

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

  it(`should have as title 'canopy-test-app'`, () => {
    expect(component.title).toEqual('canopy-test-app');
  });
});
Example #3
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 #4
Source File: client.spec.ts    From kin-node with MIT License 6 votes vote down vote up
test("getBalance with account resolution", async () => {
    const internal = mock(InternalClient);

    const account = PrivateKey.random();
    const balances = ["10", "15"];
    
    when(internal.getAccountInfo(anything(), anything()))
        .thenCall(() => {
            return Promise.reject(new AccountDoesNotExist());
        });

    when(internal.resolveTokenAccounts(anything(), anything()))
        .thenCall((key: PublicKey) => {
            if (key.toBase58() == account.publicKey().toBase58()) {
                const infos: accountpbv4.AccountInfo[] = [];
                balances.forEach(balance => {
                    const id = new commonpbv4.SolanaAccountId();
                    id.setValue(PrivateKey.random().publicKey().buffer);
                    const info = new accountpbv4.AccountInfo();
                    info.setAccountId(id);
                    info.setBalance(balance);
                    infos.push(info);
                });

                return Promise.resolve(infos);
            }
        
            return Promise.resolve([]);
        });

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

    expect(await client.getBalance(account.publicKey())).toStrictEqual(new BigNumber(10));
});
Example #5
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 #6
Source File: internal.spec.ts    From kin-node with MIT License 6 votes vote down vote up
function newTestEnv(appIndex?: number): TestEnv {
    const accountClientV4 = mock(accountgrpcv4.AccountClient);
    const airdropClientV4 = mock(airdropgrpcv4.AirdropClient);
    const txClientV4 = mock(transactiongrpcv4.TransactionClient);

    return {
        'client': new InternalClient({
            accountClientV4: instance(accountClientV4),
            airdropClientV4: instance(airdropClientV4),
            txClientV4: instance(txClientV4),
            appIndex: appIndex,
        }),
        'accountClientV4': accountClientV4,
        'airdropClientV4': airdropClientV4,
        'txClientV4': txClientV4,
    };
}
Example #7
Source File: play.tests.ts    From sixpg with MIT License 6 votes vote down vote up
describe.skip('commands/play', () => {
    it('null query, throws error', () =>
    {
        const ctx = mock<CommandContext>();
        ctx.member = { voice: { channel: null }} as any;
        
        const result = () => new PlayCommand().execute(ctx);

        result().should.eventually.throw();
    });
    
    it('null channel, throws error', () =>
    {
        const ctx = mock<CommandContext>();
        ctx.member = { voice: { channel: null }} as any;
        
        const result = () => new PlayCommand().execute(ctx, 'a');

        result().should.eventually.throw();
    });
});
Example #8
Source File: mocks.ts    From xrp-api with MIT License 5 votes vote down vote up
mockedRippleApiService = mock(RippleApiService)
Example #9
Source File: ModelManager.test.ts    From aem-spa-page-model-manager with Apache License 2.0 5 votes vote down vote up
ModelClientMock = mock(ModelClient)
Example #10
Source File: c-copy.test.ts    From bindable with MIT License 5 votes vote down vote up
jest.mock('../../../helpers/copy-to-clipboard');
Example #11
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 #12
Source File: mocks.ts    From xrp-api with MIT License 5 votes vote down vote up
mockedDebuglog = mock(Debuglog)
Example #13
Source File: PlaybackEngine.test.ts    From osmd-audio-player with MIT License 5 votes vote down vote up
jest.mock("./PlaybackScheduler");
Example #14
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test("client account management", async () => {
    const internal = mock(InternalClient);

    const accountBalances = new Map<string, BigNumber>();
    when(internal.createAccount(anything(), anything(), anything()))
        .thenCall((account: PrivateKey) => {
            if (accountBalances.has(account.publicKey().toBase58())) {
                throw new AccountExists();
            }

            return Promise.resolve(accountBalances.set(account.publicKey().toBase58(), new BigNumber(10)));
        });
    when(internal.getAccountInfo(anything(), anything()))
        .thenCall((account: PublicKey) => {
            const balance = accountBalances.get(account.toBase58());
            if (!balance) {
                throw new AccountDoesNotExist();
            }

            const account_info = new accountpbv4.AccountInfo();
            account_info.setBalance(balance.toString());
            return Promise.resolve(account_info);
        });


    const account = PrivateKey.random();
    const client = new Client(Environment.Test, {
        appIndex: 0,
        internal: instance(internal),
    });

    await client.createAccount(account);

    try {
        await client.createAccount(account);
        fail();
    } catch (err) {
        expect(err).toBeInstanceOf(AccountExists);
    }

    expect(await client.getBalance(account.publicKey())).toStrictEqual(new BigNumber(10));
});
Example #15
Source File: command.service.tests.ts    From sixpg with MIT License 5 votes vote down vote up
describe('services/command-service', () => {
    let service: CommandService;
    beforeEach(() => {
        Deps.testing = true;

        service = new CommandService(
            mock<Bots>(),
            mock<AutoMod>(),
            mock<Leveling>(),
            mock<Logs>(),
            mock(Commands));
    });

    describe('handle', () => {
        it('empty message gets ignored', () => {
            const msg: any = { content: '', channel: { reply: () => { throw Error() }}};

            const result = () => service.handle(msg);

            expect(result()).to.eventually.throw();
        });

        it('no found command message gets ignored', () => {
            const msg: any = { content: '.pong', reply: () => { throw Error(); }};

            const result = () => service.handle(msg);

            expect(result()).to.eventually.throw();
        });

        it('found command gets executed', () => {
            const msg: any = { content: '.ping', reply: () => { throw Error(); }};

            const result = () => service.handle(msg);

            expect(result()).to.eventually.throw();
        });

        it('found command, with extra args, gets executed', async () => {
            const msg: any = { content: '.ping pong', reply: () => { throw Error(); }};
            
            const result = () => service.handle(msg);

            expect(result()).to.eventually.throw();
        });

        it('found command, with unmet precondition, gets ignored', async () => {
            const msg: any = { content: '.warnings', reply: () => { throw Error(); }};

            await service.handle(msg);
        });

        it('command override disabled command, throws error', () => {
            const clients = {
                get() {
                    const client = new SavedBot();
                    guild.commands.configs.push({ name: 'ping', enabled: false });
                    return guild;
                }
            };
            service = new CommandService(
                guilds as any,
                mock<AutoMod>(),
                mock<Leveling>(),
                mock<Logs>(),
                mock(Cooldowns),
                mock(Commands));
            
            const msg: any = { content: '.ping', reply: () => { throw Error(); }};

            expect(service.handle(msg)).to.eventually.throw();
        });
    });
});
Example #16
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test("submitPayment with no service subsidizer", async() => {
    const internal = mock(InternalClient);

    const submitReqs: submitRequest[] = [];

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const appSubsidizer = PrivateKey.random();
    
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, il?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            submitReqs.push({tx, il, commitment, dedupeId});
            
            const result = new SubmitTransactionResult();
            result.TxId = tx.signature!;
            return Promise.resolve(result);
        });
    
    setGetServiceConfigRespNoSubsidizer(internal);
    setGetRecentBlockhashResp(internal);

    let p: Payment = {
        sender: sender,
        destination: dest.publicKey(),
        type: TransactionType.Spend,
        quarks: new BigNumber(11),
    };

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

    try {
        await client.submitPayment(p);
        fail();
    } catch (error) {
        expect(error).toBeInstanceOf(NoSubsidizerError);
    }

    p = {
        sender: sender,
        destination: dest.publicKey(),
        type: TransactionType.Spend,
        quarks: new BigNumber(11),
        subsidizer: appSubsidizer,
    };
    
    const txId = await client.submitPayment(p);
    
    expect(submitReqs).toHaveLength(1);

    const request = submitReqs[0];
    expect(request).toBeDefined();

    const submitTx = request!.tx;
    expect(submitTx.signatures).toHaveLength(2);
    expect(submitTx.signatures[0].publicKey.toBuffer()).toEqual(appSubsidizer.publicKey().buffer);
    expect(appSubsidizer.kp.verify(submitTx.serializeMessage(), submitTx.signatures[0].signature!)).toBeTruthy();
    expect(txId).toEqual(submitTx.signatures[0].signature!);

    expect(submitTx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
    expect(sender.kp.verify(submitTx.serializeMessage(), submitTx.signatures[1].signature!)).toBeTruthy();

    expect(submitTx.instructions).toHaveLength(2);
    
    const memoInstruction = MemoInstruction.decodeMemo(submitTx.instructions[0]);
    
    const expected = Memo.new(1, p.type, 1, Buffer.alloc(29));
    expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
    
    const tokenInstruction = TokenInstruction.decodeTransfer(submitTx.instructions[1]);
    
    expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);
    expect(tokenInstruction.dest.toBuffer()).toEqual(dest.publicKey().buffer);
    expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
    expect(tokenInstruction.amount).toEqual(BigInt(p.quarks));
});
Example #17
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 #18
Source File: client.spec.ts    From kin-node with MIT License 5 votes vote down vote up
test("submitPayment sign errors", async() => {
    const internal = mock(InternalClient);

    const sender = PrivateKey.random();
    const dest = PrivateKey.random();
    const payment: Payment = {
        sender: sender,
        destination: dest.publicKey(),
        type: TransactionType.Spend,
        quarks: new BigNumber(11),
        invoice: {
            Items: [
                {
                    title: "test",
                    amount: new BigNumber(11),
                }
            ]
        }
    };

    let reason = 1;
    when(internal.signTransaction(anything(), anything()))
        .thenCall(() => {
            const invoiceError = new commonpb.InvoiceError();
            invoiceError.setOpIndex(0);
            invoiceError.setReason(reason);
            invoiceError.setInvoice(invoiceToProto(payment.invoice!));

            const result: SignTransactionResult = {
                TxId: Buffer.alloc(64),
                InvoiceErrors: [
                    invoiceError,
                ],
            };

            reason = (reason % 3) + 1;
            return Promise.resolve(result);
        });        
    
    setGetServiceConfigResp(internal);
    setGetRecentBlockhashResp(internal);    
    
    const client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });
    for (let i = 1; i <= 3; i++) {
        try {
            await client.submitPayment(payment);
            fail();
        } catch (err) {
            switch (i) {
                case commonpb.InvoiceError.Reason.ALREADY_PAID:
                    expect(err).toBeInstanceOf(AlreadyPaid);
                    break;
                case commonpb.InvoiceError.Reason.WRONG_DESTINATION:
                    expect(err).toBeInstanceOf(WrongDestination);
                    break;
                case commonpb.InvoiceError.Reason.SKU_NOT_FOUND:
                    expect(err).toBeInstanceOf(SkuNotFound);
                    break;
                default:
                    fail();
            }
        }
    }
});
Example #19
Source File: date-field.component.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
errorStateMatcherMock = mock(LgErrorStateMatcher)
Example #20
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 #21
Source File: sort-code.directive.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgSortCodeDirective', () => {
  let fixture: ComponentFixture<TestInputComponent>;
  let component: TestInputComponent;
  let inputDebugElement: DebugElement;
  let inputInstance: LgSortCodeDirective;
  let control: NgControl;

  beforeEach(
    waitForAsync(() => {
      control = mock(NgControl);

      TestBed.configureTestingModule({
        imports: [ FormsModule, ReactiveFormsModule ],
        declarations: [ LgSortCodeDirective, TestInputComponent ],
        providers: [ { provide: NgControl, useValue: instance(control) } ],
      }).compileComponents();

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

      inputDebugElement = fixture.debugElement.query(By.directive(LgSortCodeDirective));

      inputInstance =
        inputDebugElement.injector.get<LgSortCodeDirective>(LgSortCodeDirective);
    }),
  );

  it('adds a placeholder', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.placeholder).toContain('00-00-00');
  });

  it('adds a required attribute', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.required).toBe(true);
  });

  it('adds a numeric inputmode attribute', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.getAttribute('inputmode')).toBe('numeric');
  });

  it('adds a maxlength attribute', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.getAttribute('maxlength')).toBe('8');
  });

  it('adds a size attribute', () => {
    fixture.detectChanges();

    expect(inputDebugElement.nativeElement.getAttribute('size')).toBe('7');
  });

  describe('#format', () => {
    it('should add dashes between the numbers', () => {
      expect(inputInstance['format']('000000')).toEqual('00-00-00');
      expect(inputInstance['format']('00 00 00')).toEqual('00-00-00');
      expect(inputInstance['format']('00-00-00')).toEqual('00-00-00');
    });

    it('should be called on a focusout event', () => {
      component.form.get('sortCode').setValue('000');
      const spy = spyOn<any>(inputInstance, 'format');

      fixture.detectChanges();
      inputDebugElement.nativeElement.dispatchEvent(new Event('focusout'));

      expect(spy).toHaveBeenCalledOnceWith('000');
    });
  });
});
Example #22
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 #23
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch with preferred account resolution", async() => {
    const internal = mock(InternalClient);

    const appSubsidizer = PrivateKey.random();
    const sender = PrivateKey.random();
    const resolvedSender = PrivateKey.random();
    const resolvedAccounts = new Map<string, PublicKey>([
        [sender.publicKey().toBase58(), resolvedSender.publicKey()],
    ]);
    
    const originalDests: PublicKey[] = [];
    const resolvedDests: PublicKey[] = [];
    
    const earnCount = 15;
    const earns = new Array<Earn>(earnCount);
    for (let i = 0; i < earnCount; i++) {
        const dest = PrivateKey.random();
        earns[i] = {
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        };
        originalDests.push(dest.publicKey());
        
        const resolvedDest = PrivateKey.random().publicKey();
        resolvedDests.push(resolvedDest);
        resolvedAccounts.set(dest.publicKey().toBase58(), resolvedDest);
    }

    interface submitRequest {
        tx: Transaction,
        invoiceList?: commonpb.InvoiceList,
        commitment?: Commitment,
        dedupeId?: Buffer,
    }
    const requests: submitRequest[] = [];

    let attemptedSubmission = false;
    when(internal.submitTransaction(anything(), anything(), anything(), anything()))
        .thenCall((tx: Transaction, invoice?: commonpb.InvoiceList, commitment?: Commitment, dedupeId?: Buffer) => {
            requests.push({tx, invoiceList: invoice, commitment, dedupeId});

            if (!attemptedSubmission) {
                attemptedSubmission = true;
                return Promise.resolve({
                    TxId: tx.signature!,
                    Errors: {
                        TxError: new AccountDoesNotExist(),
                    },
                });
            } else {
                attemptedSubmission = false;  // reset for next request
                return Promise.resolve({
                    TxId: tx.signature!,
                });
            }
        });

    when(internal.resolveTokenAccounts(anything(), anything()))
        .thenCall((key: PublicKey) => {
            const resolvedAccount = resolvedAccounts.get(key.toBase58());

            if (resolvedAccount) {
                const id = new commonpbv4.SolanaAccountId();
                id.setValue(resolvedAccount.buffer);
    
                const info = new accountpbv4.AccountInfo();
                info.setAccountId(id);
    
                return Promise.resolve([info]);
            }

            return Promise.resolve([]);
        });

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

    const result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
        subsidizer: appSubsidizer,
    });
    
    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(requests).toHaveLength(2);
    for (let reqId = 0; reqId < requests.length; reqId++) {
        const batchIndex = Math.floor(reqId / 2);
        const resolved = (reqId % 2) == 1;
        
        const req = requests[reqId];
        const tx = req.tx;

        expect(tx.signatures).toHaveLength(2);
        expect(tx.signatures[0].publicKey.toBuffer()).toEqual(appSubsidizer.publicKey().buffer);
        expect(appSubsidizer.kp.verify(tx.serializeMessage(), tx.signatures[0].signature!)).toBeTruthy();
        expect(tx.signatures[1].publicKey.toBuffer()).toEqual(sender.publicKey().buffer);
        expect(sender.kp.verify(tx.serializeMessage(), tx.signatures[1].signature!)).toBeTruthy();

        const memoInstruction = MemoInstruction.decodeMemo(tx.instructions[0]);
        
        const expected = Memo.new(1, TransactionType.Earn, 1, Buffer.alloc(29));
        expect(memoInstruction.data).toEqual(expected.buffer.toString("base64"));
        
        expect(tx.instructions).toHaveLength(earnCount + 1);

        for (let i = 0; i < earnCount; i++) {
            const tokenInstruction = TokenInstruction.decodeTransfer(tx.instructions[i + 1]);    
            
            if (resolved) {
                expect(tokenInstruction.source.toBuffer()).toEqual(resolvedSender.publicKey().buffer);
                expect(tokenInstruction.dest.toBuffer()).toEqual(resolvedDests[batchIndex * 18 + i].buffer);
            } else {
                expect(tokenInstruction.source.toBuffer()).toEqual(sender.publicKey().buffer);
                expect(tokenInstruction.dest.toBuffer()).toEqual(originalDests[batchIndex * 18 + i].buffer);
            }
            
            expect(tokenInstruction.owner.toBuffer()).toEqual(sender.publicKey().buffer);
            expect(tokenInstruction.amount).toEqual(BigInt((batchIndex * 18 + i + 1)));
        }
    }
});
Example #24
Source File: feature-toggle.guard.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('FeatureToggleGuard', () => {
  let configServiceMock: LgFeatureToggleService;
  let guard: FeatureToggleGuard;
  const routerMock = mock(Router);
  const enabledConfig = { parent: true };
  const disabledConfig = { parent: false };
  const enabledConfig2 = { parent: true, child: true };
  const disabledConfig2 = { parent: false, child: false };
  const routeSnapshot: Partial<ActivatedRouteSnapshot> = {
    data: { featureToggle: 'parent' },
    children: [
      {
        data: { featureToggle: 'child' },
      } as any,
    ],
  };

  const checkGuardConfigs = (
    guardType: GuardTypes,
    config,
    marbleValue: boolean,
    onceVerify: boolean = false,
  ) => {
    /* eslint-disable @typescript-eslint/no-unused-expressions, no-unused-expressions */
    onceVerify
      ? when(configServiceMock.toggles$).thenReturn(config)
      : when(configServiceMock.toggles$).thenReturn(of(config));
    /* eslint-enable */

    switch (guardType) {
      case GuardTypes.CAN_ACTIVATE:

        expect(guard.canActivate(routeSnapshot as ActivatedRouteSnapshot)).toBeObservable(
          cold('(a|)', { a: marbleValue }),
        );

        break;

      case GuardTypes.CAN_ACTIVATE_CHILD:

        expect(
          guard.canActivateChild(routeSnapshot as ActivatedRouteSnapshot),
        ).toBeObservable(cold('(a|)', { a: marbleValue }));

        break;

      case GuardTypes.CAN_LOAD:

        expect(guard.canLoad(routeSnapshot as Route)).toBeObservable(
          cold('(a|)', { a: marbleValue }),
        );

        break;
    }

    return verify(
      routerMock.navigate(deepEqual([ '/' ]), deepEqual({ queryParamsHandling: 'merge' })),
    );
  };

  beforeEach(() => {
    configServiceMock = mock(LgFeatureToggleService);

    TestBed.configureTestingModule({
      providers: [
        FeatureToggleGuard,
        {
          provide: LgFeatureToggleService,
          useFactory: () => instance(configServiceMock),
        },
        { provide: Router, useFactory: () => instance(routerMock) },
      ],
    });

    guard = TestBed.inject(FeatureToggleGuard);
  });

  describe('can activate', () => {
    it('should be true when the parent is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE, enabledConfig, true).never();
      reset(routerMock);
    });

    it('should be true when the parent and child is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE, enabledConfig2, true).never();
      reset(routerMock);
    });

    it('should be false when the parent is disabled', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, disabledConfig, false).once();
      reset(routerMock);
    });

    it('should be false when the parent is enabled but not child', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE, disabledConfig2, false).once();
      reset(routerMock);
    });
  });

  describe('can activate child', () => {
    it('should be true when the parent is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, of(enabledConfig), true).never();
      reset(routerMock);
    });

    it('should be true when the parent and child is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, of(enabledConfig2), true).never();
      reset(routerMock);
    });

    it('should be false when the parent is disabled', () => {
      checkGuardConfigs(
        GuardTypes.CAN_ACTIVATE_CHILD,
        of(disabledConfig),
        false,
        true,
      ).once();

      reset(routerMock);
    });

    it('should be false when the parent is enabled but not child', () => {
      checkGuardConfigs(
        GuardTypes.CAN_ACTIVATE_CHILD,
        of(disabledConfig2),
        false,
        true,
      ).once();

      reset(routerMock);
    });
  });

  describe('can load', () => {
    it('should be true when the parent is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_LOAD, of(enabledConfig), true).never();
      reset(routerMock);
    });

    it('should be true when the parent and child is enabled', () => {
      checkGuardConfigs(GuardTypes.CAN_LOAD, of(enabledConfig2), true).never();
      reset(routerMock);
    });

    it('should be false when the parent is disabled', () => {
      checkGuardConfigs(GuardTypes.CAN_LOAD, of(disabledConfig), false, true).once();
      reset(routerMock);
    });

    it('should be false when the parent is enabled but not child', () => {
      checkGuardConfigs(GuardTypes.CAN_LOAD, of(disabledConfig2), false, true).once();
      reset(routerMock);
    });
  });
});
Example #25
Source File: client.spec.ts    From kin-node with MIT License 4 votes vote down vote up
test("submitEarnBatch failures", async() => {
    const internal = mock(InternalClient);

    // ensure top level bad requests are rejected
    const sender = PrivateKey.random();
    const badBatch: EarnBatch = {
        sender: sender,
        earns: [
            {
                destination: PrivateKey.random().publicKey(),
                quarks: new BigNumber(10),
                invoice: {
                    Items: [
                        {
                            title: "test",
                            amount: new BigNumber(10),
                        }
                    ]
                }
            },
        ],
    };

    let client = new Client(Environment.Test, {
        internal: instance(internal),
    });
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("without an app index");
    }

    badBatch.earns.push({
        destination: PrivateKey.random().publicKey(),
        quarks: new BigNumber(10),
    });

    client = new Client(Environment.Test, {
        appIndex: 1,
        internal: instance(internal),
    });
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("all or none");
    }

    // too few earns
    const earns = new Array<Earn>();
    badBatch.earns = earns;
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("at least 1");
    }

    // too many earns
    for (let i = 0; i < 16; i++) {
        const dest = PrivateKey.random();
        earns.push({
            destination: dest.publicKey(),
            quarks: new BigNumber(1 + i),
        });
    }
    try {
        await client.submitEarnBatch(badBatch);
        fail();
    } catch (err) {
        expect((<Error>err).message).toContain("more than 15");
    }

    // reduce to max number of earns of 15
    earns.pop();

    let failWith: TransactionErrors | undefined;
    when(internal.signTransaction(anything(), anything()))
        .thenCall((tx: Transaction) => {
            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(() => {
            if (!failWith) {
                return Promise.resolve(new SubmitTransactionResult());
            }

            return Promise.resolve({
                TxId: Buffer.alloc(32),
                Errors: failWith,
            });
        });

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

    let result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeUndefined();
    expect(result.earnErrors).toBeUndefined();

    failWith = {
        TxError: new InsufficientFee()
    };
    result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeInstanceOf(InsufficientFee);
    expect(result.earnErrors).toBeUndefined();

    failWith = {
        TxError: new InsufficientBalance(),
        PaymentErrors: new Array<Error>(15),
    };
    for (let i = 0; i < 15; i++) {
        if (i%2 == 0) {
            failWith.PaymentErrors![i] = new InsufficientBalance();
        }
    }
    result = await client.submitEarnBatch({
        sender: sender,
        earns: earns,
    });
    expect(result.txId).toEqual(Buffer.alloc(32));
    expect(result.txError).toBeInstanceOf(InsufficientBalance);
    expect(result.earnErrors).toBeDefined();
    expect(result.earnErrors!).toHaveLength(8);
    for (let i = 0; i < 15; i++) {
        if (i%2 == 0) {
            expect(result.earnErrors![i/2].error).toBeInstanceOf(InsufficientBalance);
            expect(result.earnErrors![i/2].earnIndex).toEqual(i);
        }
    }
});
Example #26
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 #27
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 #28
Source File: announce.tests.ts    From sixpg with MIT License 4 votes vote down vote up
describe('modules/announce', () => {
    let guilds: Bots;

    beforeEach(() => {
        guilds = mock<Bots>();
        guilds.get = (): any => new SavedBot();
    });

    describe('member join handler', () =>
    {
        let member: GuildMember;

        beforeEach(() => {
            member = {
                id: '123',
                guild: {
                    name: 'Guild',
                    channels: { cache: {
                        get: (id: string) => {
                            const channel = mock<TextChannel>();
                            channel.send = (message: any): any => {
                                throw new TypeError(message);
                            }
                            return (id === '123') ? channel : null;
                        }
                    }},
                    memberCount: 2
                }
            } as any;
        });

        it('member join, member undefined, returns', () => {
            const result = () => new MemberJoinHandler(guilds).invoke(member);
    
            result().should.eventually.not.throw();
        });
        
        it('member join, event not active, returns', () => {
            const result = () => new MemberJoinHandler(guilds).invoke(member);
    
            result().should.eventually.not.throw();
        });
        
        it('member join, channel not found, returns', () => {
            guilds.get = (): any => {
                const client = new SavedBot();
                guild.announce.events.push({
                    event: EventType.MemberJoin,
                    message: 'test',
                    channelName: '321'
                });
            }

            const result = () => new MemberJoinHandler(guilds).invoke(member);
    
            result().should.eventually.not.throw();
        });
        
        it('member join, event active, message is sent', () => {
            guilds.get = (): any => {
                const client = new SavedBot();
                guild.announce.events.push({
                    event: EventType.MemberJoin,
                    message: 'test',
                    channelName: '123'
                });
            }
            
            const result = () => new MemberJoinHandler(guilds).invoke(member);
    
            result().should.eventually.throw('test');
        });
        
        it('member join, event active, message is sent with applied guild variables', () => {
            guilds.get = (): any => {
                const client = new SavedBot();
                guild.announce.events.push({
                    event: EventType.MemberJoin,
                    message: '[USER] joined!',
                    channelName: '123'
                });
            }

            const result = () => new MemberJoinHandler(guilds).invoke(member);
    
            result().should.eventually.throws(new TypeError('<@!123> joined!'));
        });
    });

    describe('message deleted handler', () => {
        it('')
    });
});
Example #29
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');
    });
  });
});