diff --git a/__tests__/unit/core-api/__support__/index.ts b/__tests__/unit/core-api/__support__/index.ts index be3a059b5b..591282c926 100644 --- a/__tests__/unit/core-api/__support__/index.ts +++ b/__tests__/unit/core-api/__support__/index.ts @@ -1,116 +1,90 @@ -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; - import { Application, Container, Contracts, Providers, Services } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Wallets } from "@packages/core-state"; -import { Identities, Utils } from "@packages/crypto"; -import { One, Two } from "@packages/core-transactions/src/handlers"; -import { TransactionHandlerProvider } from "@packages/core-transactions/src/handlers/handler-provider"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { BridgechainRegistrationTransactionHandler, BusinessRegistrationTransactionHandler, } from "@packages/core-magistrate-transactions/src/handlers"; -import { - addressesIndexer, - ipfsIndexer, locksIndexer, - publicKeysIndexer, - usernamesIndexer, -} from "@packages/core-state/src/wallets/indexers/indexers"; import { bridgechainIndexer, businessIndexer, MagistrateIndex, } from "@packages/core-magistrate-transactions/src/wallet-indexes"; +import { Wallets } from "@packages/core-state"; import { - BlockchainMocks, - BlockRepositoryMocks, NetworkMonitorMocks, - PeerStorageMocks, RoundRepositoryMocks, - StateStoreMocks, TransactionPoolProcessorMocks, TransactionPoolQueryMocks, TransactionRepositoryMocks, -} from "@tests/unit/core-api/mocks"; + addressesIndexer, + ipfsIndexer, + locksIndexer, + publicKeysIndexer, + usernamesIndexer, +} from "@packages/core-state/src/wallets/indexers/indexers"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { One, Two } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerProvider } from "@packages/core-transactions/src/handlers/handler-provider"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Utils } from "@packages/crypto"; export type PaginatedResponse = { - totalCount: number, - results: object[], - meta: object -} + totalCount: number; + results: object[]; + meta: object; +}; export type ItemResponse = { - data: object -} + data: object; +}; export const parseObjectWithBigInt = (item) => { - return JSON.parse(JSON.stringify(item, (key, value) => - typeof value === 'bigint' - ? value.toString() - : value - )); + return JSON.parse(JSON.stringify(item, (key, value) => (typeof value === "bigint" ? value.toString() : value))); }; export const buildSenderWallet = (app: Application, passphrase: string | null = null): Contracts.State.Wallet => { - let walletRepository = app.get(Identifiers.WalletRepository); + const walletRepository = app.get(Identifiers.WalletRepository); - let wallet: Contracts.State.Wallet = walletRepository.createWallet(Identities.Address.fromPassphrase(passphrase ? passphrase : passphrases[0])); + const wallet: Contracts.State.Wallet = walletRepository.createWallet( + Identities.Address.fromPassphrase(passphrase ? passphrase : passphrases[0]), + ); wallet.publicKey = Identities.PublicKey.fromPassphrase(passphrase ? passphrase : passphrases[0]); wallet.balance = Utils.BigNumber.make(7527654310); - return wallet + return wallet; }; export const initApp = (): Application => { - let app = new Application(new Container.Container()); + const app = new Application(new Container.Container()); - app - .bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); - app - .bind(Container.Identifiers.StateStore) - .toConstantValue(StateStoreMocks.stateStore); + app.bind(Container.Identifiers.StateStore).toConstantValue(Mocks.StateStore.instance); - app - .bind(Container.Identifiers.BlockchainService) - .toConstantValue(BlockchainMocks.blockchain); + app.bind(Container.Identifiers.BlockchainService).toConstantValue(Mocks.Blockchain.instance); - app - .bind(Container.Identifiers.BlockRepository) - .toConstantValue(BlockRepositoryMocks.blockRepository); + app.bind(Container.Identifiers.BlockRepository).toConstantValue(Mocks.BlockRepository.instance); - app - .bind(Container.Identifiers.TransactionRepository) - .toConstantValue(TransactionRepositoryMocks.transactionRepository); + app.bind(Container.Identifiers.TransactionRepository).toConstantValue( + Mocks.TransactionRepository.instance, + ); - app - .bind(Container.Identifiers.PeerNetworkMonitor) - .toConstantValue(NetworkMonitorMocks.networkMonitor); + app.bind(Container.Identifiers.PeerNetworkMonitor).toConstantValue(Mocks.NetworkMonitor.instance); - app - .bind(Container.Identifiers.PeerStorage) - .toConstantValue(PeerStorageMocks.peerStorage); + app.bind(Container.Identifiers.PeerStorage).toConstantValue(Mocks.PeerStorage.instance); - app - .bind(Container.Identifiers.RoundRepository) - .toConstantValue(RoundRepositoryMocks.roundRepository); + app.bind(Container.Identifiers.RoundRepository).toConstantValue(Mocks.RoundRepository.instance); - app - .bind(Container.Identifiers.TransactionPoolQuery) - .toConstantValue(TransactionPoolQueryMocks.transactionPoolQuery); + app.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue( + Mocks.TransactionPoolQuery.instance, + ); - app - .bind(Container.Identifiers.TransactionPoolProcessor) - .toConstantValue(TransactionPoolProcessorMocks.transactionPoolProcessor); + app.bind(Container.Identifiers.TransactionPoolProcessor).toConstantValue( + Mocks.TransactionPoolProcessor.instance, + ); - app - .bind(Container.Identifiers.TransactionPoolProcessorFactory) - .toFactory(() => () => { - return TransactionPoolProcessorMocks.transactionPoolProcessor - }); + app.bind(Container.Identifiers.TransactionPoolProcessorFactory).toFactory(() => () => { + return Mocks.TransactionPoolProcessor.instance; + }); - app - .bind(Container.Identifiers.EventDispatcherService) - .toConstantValue({}); + app.bind(Container.Identifiers.EventDispatcherService).toConstantValue({}); app.bind(Identifiers.TransactionHandler).to(One.TransferTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.TransferTransactionHandler); @@ -135,54 +109,56 @@ export const initApp = (): Application => { app.bind(Identifiers.TransactionHandler).to(BusinessRegistrationTransactionHandler); app.bind(Identifiers.TransactionHandler).to(BridgechainRegistrationTransactionHandler); - app - .bind(Identifiers.WalletAttributes) + app.bind(Identifiers.WalletAttributes) .to(Services.Attributes.AttributeSet) .inSingletonScope(); - app - .bind(Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Addresses, indexer: addressesIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.PublicKeys, indexer: publicKeysIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Usernames, indexer: usernamesIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Ipfs, indexer: ipfsIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Locks, indexer: locksIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: MagistrateIndex.Businesses, indexer: businessIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: MagistrateIndex.Bridgechains, indexer: bridgechainIndexer }); - - app - .bind(Identifiers.WalletFactory) - .toFactory((context: Container.interfaces.Context) => (address: string) => + app.bind(Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Addresses, + indexer: addressesIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.PublicKeys, + indexer: publicKeysIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Usernames, + indexer: usernamesIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Ipfs, + indexer: ipfsIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Locks, + indexer: locksIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: MagistrateIndex.Businesses, + indexer: businessIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: MagistrateIndex.Bridgechains, + indexer: bridgechainIndexer, + }); + + app.bind(Identifiers.WalletFactory).toFactory( + (context: Container.interfaces.Context) => (address: string) => new Wallets.Wallet( address, new Services.Attributes.AttributeMap( context.container.get(Identifiers.WalletAttributes), ), ), - ); + ); - app - .bind(Identifiers.WalletRepository) - .to(Wallets.WalletRepository) - .inSingletonScope(); + app.bind(Identifiers.WalletRepository).to(Wallets.WalletRepository).inSingletonScope(); return app; }; diff --git a/__tests__/unit/core-api/controllers/blockchain.test.ts b/__tests__/unit/core-api/controllers/blockchain.test.ts index e7234b7844..96e9b66a88 100644 --- a/__tests__/unit/core-api/controllers/blockchain.test.ts +++ b/__tests__/unit/core-api/controllers/blockchain.test.ts @@ -1,10 +1,12 @@ import "jest-extended"; -import { Application } from "@packages/core-kernel"; -import { initApp, ItemResponse } from "../__support__"; + import { BlockchainController } from "@packages/core-api/src/controllers/blockchain"; -import { StateStoreMocks } from "../mocks"; +import { Application } from "@packages/core-kernel"; +import { Mocks } from "@packages/core-test-framework"; import { Interfaces } from "@packages/crypto"; +import { initApp, ItemResponse } from "../__support__"; + let app: Application; let controller: BlockchainController; @@ -14,31 +16,35 @@ beforeEach(() => { controller = app.resolve(BlockchainController); }); +afterEach(() => { + Mocks.StateStore.setBlock(undefined); +}); + describe("BlockchainController", () => { describe("index", () => { it("should return last block from store", async () => { - let mockBlockData: Partial = { + const mockBlockData: Partial = { id: "1", height: 1, }; - let mockBlock: Partial = { - data: mockBlockData as Interfaces.IBlockData + const mockBlock = { + data: mockBlockData, }; - StateStoreMocks.setMockBlock(mockBlock); + Mocks.StateStore.setBlock(mockBlock as Partial); type BlockItemResponse = ItemResponse & { data: { block: { - id: string, - height: number - }, - supply: string - }, - } - - let response = (await controller.index()); + id: string; + height: number; + }; + supply: string; + }; + }; + + const response = (await controller.index()) as BlockItemResponse; expect(response.data.supply).toBeDefined(); expect(response.data.block).toEqual(mockBlockData); diff --git a/__tests__/unit/core-api/controllers/blocks.test.ts b/__tests__/unit/core-api/controllers/blocks.test.ts index 7114293529..75084b0744 100644 --- a/__tests__/unit/core-api/controllers/blocks.test.ts +++ b/__tests__/unit/core-api/controllers/blocks.test.ts @@ -1,18 +1,19 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application } from "@packages/core-kernel"; -import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { BlocksController } from "@packages/core-api/src/controllers/blocks"; -import { BlockchainMocks, BlockRepositoryMocks, StateStoreMocks, TransactionRepositoryMocks } from "../mocks"; import { Block } from "@packages/core-database/src/models"; -import { Identities, Interfaces, Utils, Transactions } from "@packages/crypto"; -import { BuilderFactory } from "@packages/crypto/src/transactions"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; -import { Wallets } from "@packages/core-state"; +import { Application } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Wallets } from "@packages/core-state"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Interfaces, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; + +import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; let app: Application; let controller: BlocksController; @@ -27,10 +28,13 @@ beforeEach(() => { controller = app.resolve(BlocksController); walletRepository = app.get(Identifiers.WalletRepository); +}); - BlockRepositoryMocks.setMockBlock(null); - BlockRepositoryMocks.setMockBlocks([]); - TransactionRepositoryMocks.setMockTransactions([]); +afterEach(() => { + Mocks.BlockRepository.setBlock(undefined); + Mocks.BlockRepository.setBlocks([]); + Mocks.TransactionRepository.setTransactions([]); + Mocks.StateStore.setBlock(undefined); }); afterEach(() => { @@ -56,12 +60,12 @@ describe("BlocksController", () => { reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), - generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), }; - let delegateWallet = buildSenderWallet(app); + const delegateWallet = buildSenderWallet(app); - let delegateAttributes = { + const delegateAttributes = { username: "delegate", voteBalance: Utils.BigNumber.make("200"), rank: 1, @@ -78,17 +82,17 @@ describe("BlocksController", () => { describe("index", () => { it("should return last block from store", async () => { - BlockRepositoryMocks.setMockBlocks([mockBlock]); + Mocks.BlockRepository.setBlocks([mockBlock]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -97,17 +101,17 @@ describe("BlocksController", () => { }); it("should return last block from store - transformed", async () => { - BlockRepositoryMocks.setMockBlocks([mockBlock]); + Mocks.BlockRepository.setBlocks([mockBlock]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: true - } + transform: true, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -118,17 +122,17 @@ describe("BlocksController", () => { describe("first", () => { it("should return first block from store", async () => { - StateStoreMocks.setMockBlock({data: mockBlock} as Partial); + Mocks.StateStore.setBlock({ data: mockBlock } as Partial); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.first(request, undefined)); + const response = (await controller.first(request, undefined)) as ItemResponse; expect(response.data).toBeDefined(); expect(response.data).toEqual(mockBlock); @@ -137,17 +141,17 @@ describe("BlocksController", () => { describe("last", () => { it("should return last block from store", async () => { - BlockchainMocks.setMockBlock({data: mockBlock} as Partial); + Mocks.Blockchain.setBlock({ data: mockBlock } as Partial); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.last(request, undefined)); + const response = (await controller.last(request, undefined)) as ItemResponse; expect(response.data).toBeDefined(); expect(response.data).toEqual(mockBlock); @@ -156,117 +160,117 @@ describe("BlocksController", () => { describe("show", () => { it("should return found block from store", async () => { - BlockRepositoryMocks.setMockBlock(mockBlock); + Mocks.BlockRepository.setBlock(mockBlock); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; expect(response.data).toBeDefined(); expect(response.data).toEqual(mockBlock); }); it("should return error if block not found", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - await expect( controller.show(request, undefined)).resolves.toThrowError("Block not found"); + await expect(controller.show(request, undefined)).resolves.toThrowError("Block not found"); }); }); describe("transactions", () => { it("should return found transactions", async () => { - BlockRepositoryMocks.setMockBlock(mockBlock); + Mocks.BlockRepository.setBlock(mockBlock); - let transaction = BuilderFactory.transfer() + const transaction = BuilderFactory.transfer() .recipientId(Identities.Address.fromPassphrase(passphrases[1])) .amount("10000000") .sign(passphrases[0]) .nonce("1") .build(); - TransactionRepositoryMocks.setMockTransactions([transaction]); + Mocks.TransactionRepository.setTransactions([transaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.transactions(request, undefined)); + const response = (await controller.transactions(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transaction.data.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transaction.data.id, + }), + ); }); it("should return error if block not found", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - await expect( controller.transactions(request, undefined)).resolves.toThrowError("Block not found"); + await expect(controller.transactions(request, undefined)).resolves.toThrowError("Block not found"); }); it("should return error if block does not have an id", async () => { - let mockBlockWithoutId = Object.assign({}, mockBlock); + const mockBlockWithoutId = Object.assign({}, mockBlock); delete mockBlockWithoutId.id; - BlockchainMocks.setMockBlock({data: mockBlockWithoutId} as Partial); + Mocks.Blockchain.setBlock({ data: mockBlockWithoutId } as Partial); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - await expect( controller.transactions(request, undefined)).resolves.toThrowError("Block not found"); + await expect(controller.transactions(request, undefined)).resolves.toThrowError("Block not found"); }); }); describe("search", () => { it("should return found blocks from store", async () => { - BlockRepositoryMocks.setMockBlocks([mockBlock]); + Mocks.BlockRepository.setBlocks([mockBlock]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: mockBlock.id + id: mockBlock.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); diff --git a/__tests__/unit/core-api/controllers/controller.test.ts b/__tests__/unit/core-api/controllers/controller.test.ts index 17ef6dc354..2eaef3c83e 100644 --- a/__tests__/unit/core-api/controllers/controller.test.ts +++ b/__tests__/unit/core-api/controllers/controller.test.ts @@ -1,23 +1,23 @@ import "jest-extended"; -import { Application } from "@packages/core-kernel"; -import { initApp } from "../__support__"; import { Controller } from "@packages/core-api/src/controllers/controller"; +import { BlockResource } from "@packages/core-api/src/resources"; +import { Application } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Transactions, Utils } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; -import { BlockResource } from "@packages/core-api/src/resources"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Transactions, Utils } from "@packages/crypto"; +import { initApp } from "../__support__"; class TestController extends Controller { - public runRespondWithResource (data: any, transformer: any): any { - return super.respondWithResource(data, transformer) + public runRespondWithResource(data: any, transformer: any): any { + return super.respondWithResource(data, transformer); } - public runToCollection (data: any, transformer: any, transform: boolean): any { - return super.toCollection(data, transformer, transform) + public runToCollection(data: any, transformer: any, transform: boolean): any { + return super.toCollection(data, transformer, transform); } } @@ -53,7 +53,7 @@ describe("Controller", () => { describe("toCollection", () => { it("should return raw data", async () => { - let data = [ + const data = [ { id: "17184958558311101492", version: 2, @@ -62,15 +62,15 @@ describe("Controller", () => { reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), - generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) - } + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + }, ]; expect(controller.runToCollection(data, BlockResource, false)).toStrictEqual(data); }); it("should return transformed data", async () => { - let data = [ + const data = [ { id: "17184958558311101492", version: 2, @@ -79,17 +79,17 @@ describe("Controller", () => { reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), - generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) - } + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + }, ]; - expect(controller.runToCollection(data, BlockResource, true)[0]).toEqual(expect.objectContaining( - { + expect(controller.runToCollection(data, BlockResource, true)[0]).toEqual( + expect.objectContaining({ height: 2, id: "17184958558311101492", - version: 2 - } - )); + version: 2, + }), + ); }); }); }); diff --git a/__tests__/unit/core-api/controllers/delegates.test.ts b/__tests__/unit/core-api/controllers/delegates.test.ts index d57ad2c1fe..1cfb8786ff 100644 --- a/__tests__/unit/core-api/controllers/delegates.test.ts +++ b/__tests__/unit/core-api/controllers/delegates.test.ts @@ -1,18 +1,18 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; - -import { Application, Contracts } from "@packages/core-kernel"; -import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { DelegatesController } from "@packages/core-api/src/controllers/delegates"; -import { BlockRepositoryMocks } from "../mocks"; -import { Wallets } from "@packages/core-state"; -import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Transactions, Utils } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { Block } from "@packages/core-database/src/models"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Wallets } from "@packages/core-state"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Transactions, Utils } from "@packages/crypto"; + +import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; let app: Application; let controller: DelegatesController; @@ -58,7 +58,7 @@ describe("DelegatesController", () => { id: "123", height: 2, timestamp: 2, - } + }, }; delegateWallet.setAttribute("delegate", delegateAttributes); @@ -68,59 +68,59 @@ describe("DelegatesController", () => { describe("index", () => { it("should return list of delegates", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - username: delegateAttributes.username - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + username: delegateAttributes.username, + }), + ); }); }); describe("show", () => { it("should return delegate", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey - } + id: delegateWallet.publicKey, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { - username: delegateAttributes.username - } - )); + expect(response.data).toEqual( + expect.objectContaining({ + username: delegateAttributes.username, + }), + ); }); it("should return error if delegate does not exist", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: Identities.PublicKey.fromPassphrase(passphrases[1]) - } + id: Identities.PublicKey.fromPassphrase(passphrases[1]), + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Delegate not found"); }); it("should return error if delegate does not have username", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey - } + id: delegateWallet.publicKey, + }, }; delegateWallet.forgetAttribute("delegate.username"); @@ -131,110 +131,110 @@ describe("DelegatesController", () => { describe("search", () => { it("should return list of delegates", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey + id: delegateWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - username: delegateAttributes.username - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + username: delegateAttributes.username, + }), + ); }); }); describe("blocks", () => { it("should return list of blocks", async () => { - let mockBlock: Partial = { + const mockBlock: Partial = { id: "17184958558311101492", reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), }; - BlockRepositoryMocks.setMockBlocks([mockBlock]); + Mocks.BlockRepository.setBlocks([mockBlock]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey + id: delegateWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.blocks(request, undefined)); + const response = (await controller.blocks(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: mockBlock.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: mockBlock.id, + }), + ); }); // TODO it("should return list of transformed blocks", async () => { - let mockBlock: Partial = { + const mockBlock: Partial = { id: "17184958558311101492", reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), - timestamp: 2 + timestamp: 2, }; - BlockRepositoryMocks.setMockBlocks([mockBlock]); + Mocks.BlockRepository.setBlocks([mockBlock]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey + id: delegateWallet.publicKey, }, query: { page: 1, limit: 100, - transform: true - } + transform: true, + }, }; - let response = (await controller.blocks(request, undefined)); + const response = (await controller.blocks(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: mockBlock.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: mockBlock.id, + }), + ); }); it("should return error if delegate does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: Identities.PublicKey.fromPassphrase(passphrases[1]) + id: Identities.PublicKey.fromPassphrase(passphrases[1]), }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; await expect(controller.blocks(request, undefined)).resolves.toThrowError("Delegate not found"); @@ -243,46 +243,46 @@ describe("DelegatesController", () => { describe("voters", () => { it("should return list of voting wallets", async () => { - let voteWallet = buildSenderWallet(app, passphrases[1]); + const voteWallet = buildSenderWallet(app, passphrases[1]); voteWallet.setAttribute("vote", delegateWallet.publicKey); walletRepository.index(voteWallet); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: delegateWallet.publicKey + id: delegateWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.voters(request, undefined)); + const response = (await controller.voters(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ address: voteWallet.address, publicKey: voteWallet.publicKey, - } - )); + }), + ); }); it("should return error if delegate does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: Identities.PublicKey.fromPassphrase(passphrases[1]) + id: Identities.PublicKey.fromPassphrase(passphrases[1]), }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; await expect(controller.voters(request, undefined)).resolves.toThrowError("Delegate not found"); diff --git a/__tests__/unit/core-api/controllers/locks.test.ts b/__tests__/unit/core-api/controllers/locks.test.ts index 1f2260cebb..58fa44df06 100644 --- a/__tests__/unit/core-api/controllers/locks.test.ts +++ b/__tests__/unit/core-api/controllers/locks.test.ts @@ -1,18 +1,19 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application, Contracts } from "@packages/core-kernel"; -import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { LocksController } from "@packages/core-api/src/controllers/locks"; -import { BlockchainMocks, StateStoreMocks, TransactionRepositoryMocks } from "../mocks"; -import { Wallets } from "@packages/core-state"; +import { Application, Contracts } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Crypto, Enums, Identities, Interfaces, Transactions, Utils } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Wallets } from "@packages/core-state"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Transactions, Utils } from "@packages/crypto"; import { BuilderFactory } from "@packages/crypto/src/transactions"; + +import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { htlcSecretHashHex } from "../../core-transactions/handlers/__fixtures__/htlc-secrets"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; let app: Application; let controller: LocksController; @@ -24,7 +25,7 @@ const { EpochTimestamp } = Enums.HtlcLockExpirationType; const makeBlockHeightTimestamp = (heightRelativeToLastBlock = 2) => mockLastBlockData.height! + heightRelativeToLastBlock; -const makeNotExpiredTimestamp = type => +const makeNotExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! + 999 : makeBlockHeightTimestamp(9); beforeEach(() => { @@ -36,7 +37,7 @@ beforeEach(() => { controller = app.resolve(LocksController); walletRepository = app.get(Identifiers.WalletRepository); - StateStoreMocks.setMockBlock({ data: mockLastBlockData } as Interfaces.IBlock) + Mocks.StateStore.setBlock({ data: mockLastBlockData } as Interfaces.IBlock); }); afterEach(() => { @@ -89,49 +90,49 @@ describe("LocksController", () => { describe("index", () => { it("should return list of delegates", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ lockId: htlcLockTransaction.id, - } - )); + }), + ); }); }); describe("show", () => { it("should return lock", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: htlcLockTransaction.id, - } + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ lockId: htlcLockTransaction.id, - } - )); + }), + ); }); it("should return error if lock does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "non_existing_lock_id" - } + id: "non_existing_lock_id", + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Lock not found"); @@ -140,59 +141,59 @@ describe("LocksController", () => { describe("search", () => { it("should return list of locks", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: htlcLockTransaction.id + id: htlcLockTransaction.id, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ lockId: htlcLockTransaction.id, - } - )); + }), + ); }); }); describe("unlocked", () => { it("should return list of locks", async () => { // TODO: From fixtures - let mockBlock = { + const mockBlock = { id: "17184958558311101492", reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), }; - BlockchainMocks.setMockBlock({data: mockBlock} as Partial); - TransactionRepositoryMocks.setMockTransactions([htlcLockTransaction]); + Mocks.Blockchain.setBlock({ data: mockBlock } as Partial); + Mocks.TransactionRepository.setTransactions([htlcLockTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { payload: { - ids: [htlcLockTransaction.id] + ids: [htlcLockTransaction.id], }, }; - let response = (await controller.unlocked(request, undefined)); + const response = (await controller.unlocked(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ id: htlcLockTransaction.id, - } - )); + }), + ); }); }); }); diff --git a/__tests__/unit/core-api/controllers/node.test.ts b/__tests__/unit/core-api/controllers/node.test.ts index c482cd85d9..5861612b96 100644 --- a/__tests__/unit/core-api/controllers/node.test.ts +++ b/__tests__/unit/core-api/controllers/node.test.ts @@ -1,15 +1,16 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application, Container, Providers } from "@packages/core-kernel"; -import { initApp, ItemResponse } from "../__support__"; import { NodeController } from "@packages/core-api/src/controllers/node"; -import { BlockchainMocks, NetworkMonitorMocks, TransactionRepositoryMocks } from "../mocks"; +import { Application, Container, Providers } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Interfaces, Managers, Transactions } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Mocks } from "@packages/core-test-framework"; import { Generators } from "@packages/core-test-framework/src"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Interfaces, Managers, Transactions } from "@packages/crypto"; + +import { initApp, ItemResponse } from "../__support__"; let app: Application; let controller: NodeController; @@ -38,74 +39,72 @@ afterEach(() => { }); describe("NodeController", () => { - let mockBlockData: Partial; beforeEach(() => { - mockBlockData= { + mockBlockData = { id: "1", height: 1, }; - let mockBlock: Partial = { - data: mockBlockData as Interfaces.IBlockData + const mockBlock = { + data: mockBlockData, }; - NetworkMonitorMocks.setNetworkHeight(5); - BlockchainMocks.setMockBlock(mockBlock); + Mocks.NetworkMonitor.setNetworkHeight(5); + Mocks.Blockchain.setBlock(mockBlock as Partial); }); describe("status", () => { it("should return node status", async () => { - let response = (await controller.status(undefined, undefined)); + const response = (await controller.status(undefined, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ synced: true, now: 1, - } - )); + }), + ); }); - it("should return node status when last block is undefined", async () => { - BlockchainMocks.setMockBlock(null); - let response = (await controller.status(undefined, undefined)); + Mocks.Blockchain.setBlock(undefined); + const response = (await controller.status(undefined, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ synced: true, now: 0, - blocksCount: 0 - } - )); + blocksCount: 0, + }), + ); }); }); describe("syncing", () => { it("should return syncing status", async () => { - BlockchainMocks.setMockBlock(null); - let response = (await controller.syncing(undefined, undefined)); + Mocks.Blockchain.setBlock(undefined); + const response = (await controller.syncing(undefined, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ syncing: false, height: 0, id: undefined, - } - )); + }), + ); }); it("should return syncing status when last block is undefined", async () => { - let response = (await controller.syncing(undefined, undefined)); + const response = (await controller.syncing(undefined, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ syncing: false, height: mockBlockData.height, id: mockBlockData.id, - } - )); + }), + ); }); }); @@ -113,11 +112,11 @@ describe("NodeController", () => { it("should return node configuration", async () => { app.bind(Identifiers.ApplicationVersion).toConstantValue("3.0.0"); - app - .get(Container.Identifiers.PluginConfiguration) - .set("dynamicFees", { enabled: true }); + app.get(Container.Identifiers.PluginConfiguration).set("dynamicFees", { + enabled: true, + }); - let response = (await controller.configuration(undefined, undefined)); + const response = await controller.configuration(undefined, undefined); expect(response.data.core).toBeDefined(); expect(response.data.nethash).toBeDefined(); @@ -136,11 +135,11 @@ describe("NodeController", () => { it("should return node configuration when dynamicFees are not enabled", async () => { app.bind(Identifiers.ApplicationVersion).toConstantValue("3.0.0"); - app - .get(Container.Identifiers.PluginConfiguration) - .set("dynamicFees", { enabled: false }); + app.get(Container.Identifiers.PluginConfiguration).set("dynamicFees", { + enabled: false, + }); - let response = (await controller.configuration(undefined, undefined)); + const response = await controller.configuration(undefined, undefined); expect(response.data.core).toBeDefined(); expect(response.data.nethash).toBeDefined(); @@ -159,7 +158,7 @@ describe("NodeController", () => { describe("configurationCrypto", () => { it("should return all configurations", async () => { - let response = (await controller.configurationCrypto()); + const response = await controller.configurationCrypto(); expect(response.data.network).toBeDefined(); expect(response.data.exceptions).toBeDefined(); @@ -170,7 +169,7 @@ describe("NodeController", () => { describe("fees", () => { it("should return transactions fees", async () => { - let feeStatistics: TransactionRepositoryMocks.FeeStatistics = { + const feeStatistics: Mocks.TransactionRepository.FeeStatistics = { type: 1, typeGroup: 1, avg: "15", @@ -179,15 +178,15 @@ describe("NodeController", () => { sum: "500", }; - TransactionRepositoryMocks.setFeeStatistics([feeStatistics]); + Mocks.TransactionRepository.setFeeStatistics([feeStatistics]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { days: 5, - } + }, }; - let response = (await controller.fees(request)); + const response = await controller.fees(request); expect(response.data[feeStatistics.type.toString()]).toBeDefined(); }); diff --git a/__tests__/unit/core-api/controllers/peers.test.ts b/__tests__/unit/core-api/controllers/peers.test.ts index 2bb12bc993..71450159e8 100644 --- a/__tests__/unit/core-api/controllers/peers.test.ts +++ b/__tests__/unit/core-api/controllers/peers.test.ts @@ -1,14 +1,15 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application, Contracts } from "@packages/core-kernel"; -import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { PeersController } from "@packages/core-api/src/controllers/peers"; -import { PeerStorageMocks } from "../mocks"; +import { Application, Contracts } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Transactions } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Mocks } from "@packages/core-test-framework"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Transactions } from "@packages/crypto"; + +import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; let app: Application; let controller: PeersController; @@ -21,7 +22,7 @@ beforeEach(() => { controller = app.resolve(PeersController); - PeerStorageMocks.setPeers([]); + Mocks.PeerStorage.setPeers([]); }); afterEach(() => { @@ -46,14 +47,14 @@ describe("PeersController", () => { ip: "127.0.0.1", port: 4000, ports: { - "127.0.0.1": 4000 + "127.0.0.1": 4000, }, state: { height: 1, forgingAllowed: false, currentSlot: 1, - header: {} - } + header: {}, + }, }; anotherPeer = { @@ -62,69 +63,69 @@ describe("PeersController", () => { ip: "127.0.0.2", port: 4000, ports: { - "127.0.0.2": 4000 + "127.0.0.2": 4000, }, state: { height: 2, forgingAllowed: false, currentSlot: 1, - header: {} - } + header: {}, + }, }; }); describe("index", () => { it("should return list of peers", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); }); it("should return error if version in request is invalid", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "invalid_version", page: 1, limit: 100, - transform: false - } + transform: false, + }, }; await expect(controller.index(request, undefined)).resolves.toThrowError("Invalid version range provided"); }); it("should return error when offset is negative", async () => { - PeerStorageMocks.setPeers([peer]); + Mocks.PeerStorage.setPeers([peer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6.0", page: 2, limit: 100, transform: false, - offset: -1 - } + offset: -1, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -132,19 +133,19 @@ describe("PeersController", () => { }); it("should return paginated response when offset is not a number", async () => { - PeerStorageMocks.setPeers([peer]); + Mocks.PeerStorage.setPeers([peer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6.0", page: 2, limit: 100, transform: false, - offset: "invalid" - } + offset: "invalid", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -152,18 +153,18 @@ describe("PeersController", () => { }); it("should return paginated response when limit is not defined", async () => { - PeerStorageMocks.setPeers([peer]); + Mocks.PeerStorage.setPeers([peer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6.0", page: 2, transform: false, - offset: -1 - } + offset: -1, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -171,240 +172,240 @@ describe("PeersController", () => { }); it("should return list of peers ordered by version ascending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "version:asc" - } + orderBy: "version:asc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); }); it("should return list of peers ordered by version descending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "version:desc" - } + orderBy: "version:desc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); }); it("should return list of peers ordered by height ascending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "height:asc" - } + orderBy: "height:asc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); }); it("should return list of peers ordered by height descending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "height:desc" - } + orderBy: "height:desc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); }); it("should return list of peers ordered by latency ascending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "latency:asc" - } + orderBy: "latency:asc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); }); it("should return list of peers ordered by latency descending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "latency:desc" - } + orderBy: "latency:desc", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); }); it("should return list of peers ordered by other descending", async () => { - PeerStorageMocks.setPeers([peer, anotherPeer]); + Mocks.PeerStorage.setPeers([peer, anotherPeer]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { version: "2.6", page: 1, limit: 100, transform: false, - orderBy: "undefined" - } + orderBy: "undefined", + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); - expect(response.results[1]).toEqual(expect.objectContaining( - { - ip: anotherPeer.ip - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); + expect(response.results[1]).toEqual( + expect.objectContaining({ + ip: anotherPeer.ip, + }), + ); }); }); describe("show", () => { it("should return peer", async () => { - PeerStorageMocks.setPeers([peer]); + Mocks.PeerStorage.setPeers([peer]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: peer.ip - } + id: peer.ip, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { - ip: peer.ip - } - )); + expect(response.data).toEqual( + expect.objectContaining({ + ip: peer.ip, + }), + ); }); it("should return error if peer does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: peer.ip - } + id: peer.ip, + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Peer not found"); diff --git a/__tests__/unit/core-api/controllers/rounds.test.ts b/__tests__/unit/core-api/controllers/rounds.test.ts index 384941277c..a2f6c65088 100644 --- a/__tests__/unit/core-api/controllers/rounds.test.ts +++ b/__tests__/unit/core-api/controllers/rounds.test.ts @@ -1,15 +1,16 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application } from "@packages/core-kernel"; -import { initApp, ItemResponse } from "../__support__"; import { RoundsController } from "@packages/core-api/src/controllers/rounds"; -import { RoundRepositoryMocks } from "../mocks"; +import { Application } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Transactions, Utils } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Mocks } from "@packages/core-test-framework"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Transactions, Utils } from "@packages/crypto"; + +import { initApp, ItemResponse } from "../__support__"; let app: Application; let controller: RoundsController; @@ -22,7 +23,7 @@ beforeEach(() => { controller = app.resolve(RoundsController); - RoundRepositoryMocks.setRounds([]); + Mocks.RoundRepository.setRounds([]); }); afterEach(() => { @@ -39,37 +40,37 @@ afterEach(() => { describe("RoundsController", () => { describe("delegates", () => { it("should return list of delegates", async () => { - let round = { + const round = { publicKey: Identities.PublicKey.fromPassphrase(passphrases[1]), round: Utils.BigNumber.make("12"), - balance: Utils.BigNumber.make("555") + balance: Utils.BigNumber.make("555"), }; - RoundRepositoryMocks.setRounds([round]); + Mocks.RoundRepository.setRounds([round]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "12" - } + id: "12", + }, }; - let response = (await controller.delegates(request, undefined)); + const response = (await controller.delegates(request, undefined)) as ItemResponse; - expect(response.data[0]).toEqual(expect.objectContaining( - { - publicKey: round.publicKey - } - )); + expect(response.data[0]).toEqual( + expect.objectContaining({ + publicKey: round.publicKey, + }), + ); }); it("should return error if round does not exist", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "12" - } + id: "12", + }, }; - await expect(controller.delegates(request, undefined)).resolves.toThrowError("Round not found") + await expect(controller.delegates(request, undefined)).resolves.toThrowError("Round not found"); }); }); }); diff --git a/__tests__/unit/core-api/controllers/transactions.test.ts b/__tests__/unit/core-api/controllers/transactions.test.ts index 26763cdf49..78d4748a95 100644 --- a/__tests__/unit/core-api/controllers/transactions.test.ts +++ b/__tests__/unit/core-api/controllers/transactions.test.ts @@ -1,24 +1,20 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; -import { Application } from "@packages/core-kernel"; -import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { TransactionsController } from "@packages/core-api/src/controllers/transactions"; -import { - StateStoreMocks, - TransactionPoolProcessorMocks, - TransactionPoolQueryMocks, - TransactionRepositoryMocks, -} from "../mocks"; +import { Application } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Interfaces, Managers, Transactions } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; -import { BuilderFactory } from "@packages/crypto/src/transactions"; +import { Mocks } from "@packages/core-test-framework"; import { Generators } from "@packages/core-test-framework/src"; -import { configManager } from "@packages/crypto/src/managers"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Interfaces, Managers, Transactions } from "@packages/crypto"; import { TransactionType } from "@packages/crypto/src/enums"; +import { configManager } from "@packages/crypto/src/managers"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; + +import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; let app: Application; let controller: TransactionsController; @@ -35,9 +31,9 @@ beforeEach(() => { controller = app.resolve(TransactionsController); - TransactionRepositoryMocks.setMockTransaction(null); - TransactionRepositoryMocks.setMockTransactions([]); - TransactionPoolQueryMocks.setMockTransactions([]); + Mocks.TransactionRepository.setTransaction(null); + Mocks.TransactionRepository.setTransactions([]); + Mocks.TransactionPoolQuery.setTransactions([]); }); afterEach(() => { @@ -65,86 +61,82 @@ describe("TransactionsController", () => { describe("index", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); }); describe("store", () => { it("should return processor state", async () => { - let processorState = { + const processorState = { accept: [transferTransaction.id], broadcast: [], excess: [], - invalid: [] + invalid: [], }; - TransactionPoolProcessorMocks.setProcessorState(processorState); + Mocks.TransactionPoolProcessor.setProcessorState(processorState); - let request: Hapi.Request = { + const request: Hapi.Request = { payload: { - transactions: [ - transferTransaction - ] - } + transactions: [transferTransaction], + }, }; - let response = (await controller.store(request, undefined)); + const response = (await controller.store(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - processorState - )); + expect(response.data).toEqual(expect.objectContaining(processorState)); }); }); describe("show", () => { it("should return transaction", async () => { - TransactionRepositoryMocks.setMockTransaction(transferTransaction); + Mocks.TransactionRepository.setTransaction(transferTransaction); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: transferTransaction.id + id: transferTransaction.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.data).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if transaction does not exist", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: transferTransaction.id + id: transferTransaction.id, }, query: { - transform: false - } + transform: false, + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Transaction not found"); @@ -153,59 +145,59 @@ describe("TransactionsController", () => { describe("unconfirmed", () => { it("should return transactions", async () => { - TransactionPoolQueryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionPoolQuery.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.unconfirmed(request, undefined)); + const response = (await controller.unconfirmed(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); }); describe("showUnconfirmed", () => { it("should return transactions", async () => { - TransactionPoolQueryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionPoolQuery.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: transferTransaction.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.showUnconfirmed(request, undefined)); + const response = (await controller.showUnconfirmed(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.data).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if transaction does not exist", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: transferTransaction.id, }, query: { - transform: false - } + transform: false, + }, }; await expect(controller.showUnconfirmed(request, undefined)).resolves.toThrowError("Transaction not found"); @@ -214,47 +206,47 @@ describe("TransactionsController", () => { describe("search", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: transferTransaction.id + id: transferTransaction.id, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ id: transferTransaction.id, - } - )); + }), + ); }); it("should return paginated response when defined offset", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: transferTransaction.id + id: transferTransaction.id, }, query: { page: 1, limit: 100, offset: 1, - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); @@ -264,54 +256,53 @@ describe("TransactionsController", () => { describe("types", () => { it("should return registered types", async () => { - let response = (await controller.types(undefined, undefined)); + const response = (await controller.types(undefined, undefined)) as ItemResponse; - let transactionTypeObject = {}; - for(let key of Object.keys(TransactionType)) { + const transactionTypeObject = {}; + for (const key of Object.keys(TransactionType)) { if (isNaN(Number(key))) { - transactionTypeObject[key] = TransactionType[key] + transactionTypeObject[key] = TransactionType[key]; } } - expect(response.data['1']).toEqual(expect.objectContaining( - transactionTypeObject - )); + expect(response.data["1"]).toEqual(expect.objectContaining(transactionTypeObject)); }); }); describe("schemas", () => { it("should return registered schemas", async () => { - let response = (await controller.schemas(undefined, undefined)); + const response = (await controller.schemas(undefined, undefined)) as ItemResponse; const coreTransactionHandlersCount = 11; - expect(Object.keys(response.data['1']).length).toBe(coreTransactionHandlersCount); + expect(Object.keys(response.data["1"]).length).toBe(coreTransactionHandlersCount); }); }); describe("fees", () => { it("should return fees", async () => { - StateStoreMocks.setLastHeight(1); - - let response = (await controller.fees(undefined, undefined)); - - expect(response.data['1']).toEqual(expect.objectContaining({ - transfer: '10000000', - secondSignature: '500000000', - delegateRegistration: '2500000000', - vote: '100000000', - multiSignature: '500000000', - ipfs: '500000000', - multiPayment: '10000000', - delegateResignation: '2500000000', - htlcLock: '10000000', - htlcClaim: '0', - htlcRefund: '0' - } - )); + Mocks.StateStore.setLastHeight(1); + + const response = (await controller.fees(undefined, undefined)) as ItemResponse; + + expect(response.data["1"]).toEqual( + expect.objectContaining({ + transfer: "10000000", + secondSignature: "500000000", + delegateRegistration: "2500000000", + vote: "100000000", + multiSignature: "500000000", + ipfs: "500000000", + multiPayment: "10000000", + delegateResignation: "2500000000", + htlcLock: "10000000", + htlcClaim: "0", + htlcRefund: "0", + }), + ); }); it("should return error ", async () => { - StateStoreMocks.setLastHeight(-1); + Mocks.StateStore.setLastHeight(-1); await expect(controller.fees(undefined, undefined)).resolves.toThrowError(); }); diff --git a/__tests__/unit/core-api/controllers/votes.test.ts b/__tests__/unit/core-api/controllers/votes.test.ts index 7c4d8d3f14..3da50227a1 100644 --- a/__tests__/unit/core-api/controllers/votes.test.ts +++ b/__tests__/unit/core-api/controllers/votes.test.ts @@ -1,18 +1,18 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; - -import { Application } from "@packages/core-kernel"; -import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { VotesController } from "@packages/core-api/src/controllers/votes"; -import { TransactionRepositoryMocks } from "../mocks"; +import { Application } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Interfaces, Transactions } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Interfaces, Transactions } from "@packages/crypto"; import { BuilderFactory } from "@packages/crypto/src/transactions"; +import { initApp, ItemResponse, PaginatedResponse } from "../__support__"; + let app: Application; let controller: VotesController; @@ -46,63 +46,63 @@ describe("VotesController", () => { .sign(passphrases[0]) .build(); - TransactionRepositoryMocks.setMockTransaction(null); + Mocks.TransactionRepository.setTransaction(null); }); describe("index", () => { it("should return list of votes", async () => { - TransactionRepositoryMocks.setMockTransactions([voteTransaction]); + Mocks.TransactionRepository.setTransactions([voteTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: voteTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: voteTransaction.id, + }), + ); }); }); describe("show", () => { it("should return vote", async () => { - TransactionRepositoryMocks.setMockTransaction(voteTransaction); + Mocks.TransactionRepository.setTransaction(voteTransaction); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: voteTransaction.id, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ id: voteTransaction.id, - } - )); + }), + ); }); it("should return error if vote transaction does not exists", async () => { - TransactionRepositoryMocks.setMockTransaction(null); + Mocks.TransactionRepository.setTransaction(null); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_transaction_id" - } + id: "unknown_transaction_id", + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Vote not found"); diff --git a/__tests__/unit/core-api/controllers/wallets.test.ts b/__tests__/unit/core-api/controllers/wallets.test.ts index 941a2cc914..ba8faff95d 100644 --- a/__tests__/unit/core-api/controllers/wallets.test.ts +++ b/__tests__/unit/core-api/controllers/wallets.test.ts @@ -1,18 +1,18 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; - -import { Application, Contracts } from "@packages/core-kernel"; -import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { WalletsController } from "@packages/core-api/src/controllers/wallets"; -import { StateStoreMocks, TransactionRepositoryMocks } from "../mocks"; +import { Application, Contracts } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Crypto, Enums, Identities, Interfaces, Transactions, Utils } from "@packages/crypto"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; import { Wallets } from "@packages/core-state"; -import { BuilderFactory } from "@packages/crypto/src/transactions"; +import { Mocks } from "@packages/core-test-framework"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; + +import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; import { htlcSecretHashHex } from "../../core-transactions/handlers/__fixtures__/htlc-secrets"; let app: Application; @@ -25,7 +25,7 @@ const { EpochTimestamp } = Enums.HtlcLockExpirationType; const makeBlockHeightTimestamp = (heightRelativeToLastBlock = 2) => mockLastBlockData.height! + heightRelativeToLastBlock; -const makeNotExpiredTimestamp = type => +const makeNotExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! + 999 : makeBlockHeightTimestamp(9); beforeEach(() => { @@ -37,8 +37,8 @@ beforeEach(() => { controller = app.resolve(WalletsController); walletRepository = app.get(Identifiers.WalletRepository); - StateStoreMocks.setMockBlock({ data: mockLastBlockData } as Interfaces.IBlock); - TransactionRepositoryMocks.setMockTransactions([]); + Mocks.StateStore.setBlock({ data: mockLastBlockData } as Interfaces.IBlock); + Mocks.TransactionRepository.setTransactions([]); }); afterEach(() => { @@ -71,106 +71,106 @@ describe("WalletsController", () => { describe("index", () => { it("should return list of wallets", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ address: senderWallet.address, publicKey: senderWallet.publicKey, - } - )); + }), + ); }); }); describe("top", () => { it("should return list of top wallets", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.top(request, undefined)); + const response = (await controller.top(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ address: senderWallet.address, publicKey: senderWallet.publicKey, - } - )); + }), + ); }); }); describe("show", () => { it("should return lock", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: senderWallet.publicKey + id: senderWallet.publicKey, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - { + expect(response.data).toEqual( + expect.objectContaining({ address: senderWallet.address, publicKey: senderWallet.publicKey, - } - )); + }), + ); }); }); describe("transactions", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: senderWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.transactions(request, undefined)); + const response = (await controller.transactions(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if wallet does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_wallet_public_key" - } + id: "unknown_wallet_public_key", + }, }; await expect(controller.transactions(request, undefined)).resolves.toThrowError("Wallet not found"); @@ -179,36 +179,36 @@ describe("WalletsController", () => { describe("transactionsSent", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: senderWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.transactionsSent(request, undefined)); + const response = (await controller.transactionsSent(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if wallet does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_wallet_public_key" - } + id: "unknown_wallet_public_key", + }, }; await expect(controller.transactionsSent(request, undefined)).resolves.toThrowError("Wallet not found"); @@ -217,36 +217,36 @@ describe("WalletsController", () => { describe("transactionsReceived", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: senderWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.transactionsReceived(request, undefined)); + const response = (await controller.transactionsReceived(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if wallet does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_wallet_public_key" - } + id: "unknown_wallet_public_key", + }, }; await expect(controller.transactionsReceived(request, undefined)).resolves.toThrowError("Wallet not found"); @@ -255,36 +255,36 @@ describe("WalletsController", () => { describe("votes", () => { it("should return list of transactions", async () => { - TransactionRepositoryMocks.setMockTransactions([transferTransaction]); + Mocks.TransactionRepository.setTransactions([transferTransaction]); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: senderWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.votes(request, undefined)); + const response = (await controller.votes(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - id: transferTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + id: transferTransaction.id, + }), + ); }); it("should return error if wallet does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_wallet_public_key" - } + id: "unknown_wallet_public_key", + }, }; await expect(controller.votes(request, undefined)).resolves.toThrowError("Wallet not found"); @@ -298,7 +298,7 @@ describe("WalletsController", () => { value: makeNotExpiredTimestamp(EpochTimestamp), }; - let htlcLockTransaction = BuilderFactory.htlcLock() + const htlcLockTransaction = BuilderFactory.htlcLock() .htlcLockAsset({ secretHash: htlcSecretHashHex, expiration: expiration, @@ -322,39 +322,39 @@ describe("WalletsController", () => { walletRepository.index(senderWallet); - let request: Hapi.Request = { + const request: Hapi.Request = { params: { id: senderWallet.publicKey, }, query: { page: 1, limit: 100, - transform: false - } + transform: false, + }, }; - let response = (await controller.locks(request, undefined)); + const response = (await controller.locks(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { - lockId: htlcLockTransaction.id - } - )); + expect(response.results[0]).toEqual( + expect.objectContaining({ + lockId: htlcLockTransaction.id, + }), + ); }); it("should return empty rows if cold wallet", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: senderWallet.address - } + id: senderWallet.address, + }, }; delete senderWallet.publicKey; - let response = (await controller.locks(request, undefined)); + const response = (await controller.locks(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBe(0); expect(response.meta).toBeDefined(); @@ -363,10 +363,10 @@ describe("WalletsController", () => { }); it("should return error if wallet does not exists", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "unknown_wallet_public_key" - } + id: "unknown_wallet_public_key", + }, }; await expect(controller.locks(request, undefined)).resolves.toThrowError("Wallet not found"); @@ -375,26 +375,26 @@ describe("WalletsController", () => { describe("search", () => { it("should return found wallets", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: senderWallet.publicKey + id: senderWallet.publicKey, }, query: { - transform: false - } + transform: false, + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBeDefined(); expect(response.meta).toBeDefined(); expect(response.results).toBeDefined(); - expect(response.results[0]).toEqual(expect.objectContaining( - { + expect(response.results[0]).toEqual( + expect.objectContaining({ address: senderWallet.address, publicKey: senderWallet.publicKey, - } - )); + }), + ); }); }); }); diff --git a/__tests__/unit/core-api/mocks/block-repository.ts b/__tests__/unit/core-api/mocks/block-repository.ts deleted file mode 100644 index 3555f4d335..0000000000 --- a/__tests__/unit/core-api/mocks/block-repository.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { BlockRepository, RepositorySearchResult } from "@packages/core-database/src/repositories"; -import { Block } from "@packages/core-database/src/models"; - -let mockBlock: any | null; -let mockBlocks: Partial[]; - -export const setMockBlock = (block: any | null) => { - mockBlock = block; -}; - -export const setMockBlocks = (blocks: Partial[]) => { - mockBlocks = blocks; -}; - -export const blockRepository: Partial = { - searchByQuery: async (query: any, pagination: any): Promise> => { - return { - rows: mockBlocks as Block[], - count: mockBlocks.length, - countIsEstimate: false - } - }, - findByIdOrHeight: async (idOrHeight: any): Promise => { - return mockBlock as Block - }, - search: async (filter: any): Promise> => { - return { - rows: mockBlocks as Block[], - count: mockBlocks.length, - countIsEstimate: false - } - } -}; diff --git a/__tests__/unit/core-api/mocks/blockchain.ts b/__tests__/unit/core-api/mocks/blockchain.ts deleted file mode 100644 index 31f461d27f..0000000000 --- a/__tests__/unit/core-api/mocks/blockchain.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { IBlock } from "@packages/crypto/src/interfaces"; -import { Blockchain } from "@packages/core-blockchain"; - -let mockBlock: Partial | null; -let mockIsSynced: boolean = true; - -export const setMockBlock = (block: Partial | null) => { - mockBlock = block; -}; - -export const setIsSynced = (isSynced: boolean) => { - mockIsSynced = isSynced; -}; - -export const blockchain: Partial = { - getLastBlock: () :IBlock => { - return mockBlock as IBlock; - }, - getLastHeight: (): number => { - return mockBlock?.data ? mockBlock.data.height : 1; - }, - isSynced: (block?: any): boolean => { - return mockIsSynced; - } -}; diff --git a/__tests__/unit/core-api/mocks/index.ts b/__tests__/unit/core-api/mocks/index.ts deleted file mode 100644 index b0f913fa4e..0000000000 --- a/__tests__/unit/core-api/mocks/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as BlockRepositoryMocks from './block-repository' -import * as BlockchainMocks from './blockchain' -import * as NetworkMonitorMocks from './network-monitor' -import * as PeerStorageMocks from './peer-storage' -import * as TransactionPoolQueryMocks from './query' -import * as RoundRepositoryMocks from './round-repository' -import * as ServiceProviderRepository from './service-provider-repository' -import * as StateStoreMocks from './state-store' -import * as TransactionRepositoryMocks from './transaction-repository' -import * as TransactionPoolProcessorMocks from './transaction-pool-processor' - -export { - BlockRepositoryMocks, - BlockchainMocks, - NetworkMonitorMocks, - PeerStorageMocks, - TransactionPoolQueryMocks, - RoundRepositoryMocks, - ServiceProviderRepository, - StateStoreMocks, - TransactionRepositoryMocks, - TransactionPoolProcessorMocks -}; diff --git a/__tests__/unit/core-api/mocks/network-monitor.ts b/__tests__/unit/core-api/mocks/network-monitor.ts deleted file mode 100644 index f227a6fa33..0000000000 --- a/__tests__/unit/core-api/mocks/network-monitor.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { NetworkMonitor } from "@packages/core-p2p/src/network-monitor"; -let mockNetworkHeight: number = 0; - -export const setNetworkHeight = (networkHeight: number) => { - mockNetworkHeight = networkHeight; -}; - -export const networkMonitor: Partial = { - getNetworkHeight: (): number => { - return mockNetworkHeight; - } -}; diff --git a/__tests__/unit/core-api/mocks/peer-storage.ts b/__tests__/unit/core-api/mocks/peer-storage.ts deleted file mode 100644 index 9c5c8f4518..0000000000 --- a/__tests__/unit/core-api/mocks/peer-storage.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { PeerStorage } from "@packages/core-p2p/src/peer-storage"; -import { Contracts } from "@packages/core-kernel"; - -let mockPeers: Partial[] = []; - -export const setPeers = (peers: Partial[]) => { - mockPeers = peers; -}; - -export const peerStorage: Partial = { - getPeers: (): Contracts.P2P.Peer[] => { - return mockPeers as Contracts.P2P.Peer[]; - }, - hasPeer: (id: any): boolean => { - return mockPeers.length > 0 - }, - getPeer: (id: any): Contracts.P2P.Peer => { - return mockPeers[0] as Contracts.P2P.Peer; - } -}; diff --git a/__tests__/unit/core-api/mocks/query.ts b/__tests__/unit/core-api/mocks/query.ts deleted file mode 100644 index 697d6d6d43..0000000000 --- a/__tests__/unit/core-api/mocks/query.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { Transaction } from "@packages/crypto/src/transactions"; -import { Contracts } from "@packages/core-kernel"; -import { Interfaces } from "@packages/crypto"; - -let mockTransactions: Partial[]; - -export const setMockTransactions = (transactions: Partial[]) => { - mockTransactions = transactions; -}; - -class CustomQueryIterable implements Partial { - public transactions: Interfaces.ITransaction[]; - - constructor(items) { - this.transactions = items - } - - public *[Symbol.iterator](): Iterator { - for (const transaction of this.transactions) { - yield transaction; - } - } - - whereId(id: any): any { - return this; - } - - has(): boolean { - return this.transactions.length > 0; - } - - first(): Interfaces.ITransaction { - return this.transactions[0] - } -} - -export const transactionPoolQuery: Partial = { - getFromHighestPriority(): Contracts.TransactionPool.QueryIterable { - return new CustomQueryIterable(mockTransactions) as unknown as Contracts.TransactionPool.QueryIterable - } -}; diff --git a/__tests__/unit/core-api/mocks/round-repository.ts b/__tests__/unit/core-api/mocks/round-repository.ts deleted file mode 100644 index ca1a98a3dc..0000000000 --- a/__tests__/unit/core-api/mocks/round-repository.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { RoundRepository } from "@packages/core-database/src/repositories"; -import { Round } from "@packages/core-database/src/models"; - -let mockRounds: Partial[]; - -export const setRounds = (rounds: Partial[]) => { - mockRounds = rounds -}; - -export const roundRepository: Partial = { - findById: async (id: any): Promise => { - return mockRounds as Round[]; - } -}; diff --git a/__tests__/unit/core-api/mocks/service-provider-repository.ts b/__tests__/unit/core-api/mocks/service-provider-repository.ts deleted file mode 100644 index 07eae17d58..0000000000 --- a/__tests__/unit/core-api/mocks/service-provider-repository.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Providers } from "@packages/core-kernel"; - -let mockServiceProviders: Providers.ServiceProvider[]; - -export const setServiceProviders = (serviceProviders: Providers.ServiceProvider[]) => { - mockServiceProviders = serviceProviders -}; - -export const serviceProviderRepository: Partial = { - allLoadedProviders: (): Providers.ServiceProvider[] => { - return mockServiceProviders - } -}; diff --git a/__tests__/unit/core-api/mocks/state-store.ts b/__tests__/unit/core-api/mocks/state-store.ts deleted file mode 100644 index 120331bc1e..0000000000 --- a/__tests__/unit/core-api/mocks/state-store.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { StateStore } from "@packages/core-state/src/stores/state"; -import { IBlock } from "@packages/crypto/src/interfaces"; - -let mockBlock: Partial | null; -let lastHeight: number; - -export const setMockBlock = (block: Partial | null) => { - mockBlock = block; -}; - -export const setLastHeight = (height: number) => { - lastHeight = height; -}; - -export const stateStore: Partial = { - getLastBlock: () :IBlock => { - return mockBlock as IBlock; - }, - getGenesisBlock: (): IBlock => { - return mockBlock as IBlock; - }, - getLastHeight(): number { - return lastHeight - } -}; diff --git a/__tests__/unit/core-api/mocks/transaction-pool-processor.ts b/__tests__/unit/core-api/mocks/transaction-pool-processor.ts deleted file mode 100644 index 2e5090abff..0000000000 --- a/__tests__/unit/core-api/mocks/transaction-pool-processor.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Contracts } from "@packages/core-kernel"; - - -let accept: string[] = []; -let broadcast: string[] = []; -let invalid: string[] = []; -let excess: string[] = []; -let errors: { [id: string]: Contracts.TransactionPool.ProcessorError } | undefined; - -export const setProcessorState = (state: any): void => { - accept = state.accept ? state.accept : []; - broadcast = state.broadcast ? state.broadcast : []; - broadcast = state.broadcast ? state.broadcast : []; - invalid = state.invalid ? state.invalid : []; - excess = state.excess ? state.excess : []; - errors = state.errors ? state.errors : []; -}; - -export const transactionPoolProcessor: Partial = { - process: async (data: any) : Promise => { - return; - }, - get accept(): string[] { - return accept - }, - get broadcast(): string[] { - return broadcast - }, - get invalid(): string[] { - return invalid - }, - get excess(): string[] { - return excess - }, - get errors(): any { - return errors - } -}; diff --git a/__tests__/unit/core-api/mocks/transaction-repository.ts b/__tests__/unit/core-api/mocks/transaction-repository.ts deleted file mode 100644 index 310d52fbc5..0000000000 --- a/__tests__/unit/core-api/mocks/transaction-repository.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { - RepositorySearchResult, - TransactionRepository, -} from "@packages/core-database/src/repositories"; -import { Transaction } from "@packages/core-database/src/models"; - -export type FeeStatistics = { - type: number; - typeGroup: number; - avg: string; - min: string; - max: string; - sum: string; -}; - -let mockTransaction: Partial | null; -let mockTransactions: Partial[]; -let mockFeeStatistics: FeeStatistics[] = []; - -export const setMockTransaction = (transaction: Partial | null) => { - mockTransaction = transaction; -}; - -export const setMockTransactions = (transactions: Partial[]) => { - mockTransactions = transactions; -}; - -export const setFeeStatistics = (feeStatistics: FeeStatistics[]) => { - mockFeeStatistics = feeStatistics; -}; - -export const transactionRepository: Partial = { - search: async (filter: any): Promise> => { - return { - rows: mockTransactions as Transaction[], - count: mockTransactions.length, - countIsEstimate: false, - } - }, - searchByQuery: async (query: any, pagination: any): Promise> => { - return { - rows: mockTransactions as Transaction[], - count: mockTransactions.length, - countIsEstimate: false, - } - }, - findByHtlcLocks: async (lockIds: any): Promise => { - return mockTransactions as Transaction[] - }, - findByIdAndType: async (type: any, id: any): Promise => { - return mockTransaction ? mockTransaction as Transaction : undefined - }, - findById: async (id: any): Promise => { - return mockTransaction as Transaction; - }, - getFeeStatistics: async (days: any, minFee?: any): Promise => { - return mockFeeStatistics; - } -}; diff --git a/__tests__/unit/core-api/plugins/__support__/index.ts b/__tests__/unit/core-api/plugins/__support__/index.ts index 2315825a40..e9cfeb35e4 100644 --- a/__tests__/unit/core-api/plugins/__support__/index.ts +++ b/__tests__/unit/core-api/plugins/__support__/index.ts @@ -1,24 +1,25 @@ -import { Application, Container, Providers } from "@packages/core-kernel"; import { Server } from "@packages/core-api/src"; import { preparePlugins } from "@packages/core-api/src/plugins"; +import { Application, Container, Providers } from "@packages/core-kernel"; export const initServer = async (app: Application, defaults: any, customRoute: any): Promise => { - let serverConfig = { + const serverConfig = { enabled: true, host: "0.0.0.0", port: 4003, routes: { - cors: true - } + cors: true, + }, }; app.bind(Server).to(Server); - let server = app.get(Server); + const server = app.get(Server); - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); const pluginConfigurationInstance: Providers.PluginConfiguration = pluginConfiguration.from("core-api", defaults); - app.bind(Container.Identifiers.PluginConfiguration).toConstantValue(pluginConfigurationInstance) + app.bind(Container.Identifiers.PluginConfiguration) + .toConstantValue(pluginConfigurationInstance) .when(Container.Selectors.anyAncestorOrTargetTaggedFirst("plugin", "@arkecosystem/core-api")); await server.initialize("Test", serverConfig); diff --git a/__tests__/unit/core-api/plugins/cache.test.ts b/__tests__/unit/core-api/plugins/cache.test.ts index cfea14a2dd..4a431d95ae 100644 --- a/__tests__/unit/core-api/plugins/cache.test.ts +++ b/__tests__/unit/core-api/plugins/cache.test.ts @@ -1,8 +1,9 @@ import "jest-extended"; import Boom from "@hapi/boom"; -import NodeCache from "node-cache"; import { Application } from "@packages/core-kernel"; +import NodeCache from "node-cache"; + import { initApp } from "../__support__"; import { initServer } from "./__support__"; @@ -28,46 +29,38 @@ describe("Cache", () => { enabled: true, stdTTL: 0, // unlimited checkperiod: 0, // no periodic check - } + }, }, }; customResponse = { - data: "ok" + data: "ok", }; customRoute = { - method: 'GET', - path: '/test', + method: "GET", + path: "/test", handler: () => { - return customResponse + return customResponse; }, }; injectOptions = { - method: 'GET', - url: '/test', + method: "GET", + url: "/test", }; }); - it("should not cache if cache is disabled", async () => { - let server = await initServer(app, defaults, customRoute); - - const response = await server.inject(injectOptions); - const payload = JSON.parse(response.payload || {}); - expect(payload.data).toBe("ok"); - }); - it("should not cache if cache is disabled", async () => { defaults.plugins.cache.enabled = false; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); let response = await server.inject(injectOptions); let payload = JSON.parse(response.payload || {}); expect(payload.data).toBe("ok"); customResponse = { - data: "dummy" + data: "dummy", }; response = await server.inject(injectOptions); @@ -76,7 +69,7 @@ describe("Cache", () => { }); it("shod resolve if cache is enabled", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); @@ -84,14 +77,14 @@ describe("Cache", () => { }); it("should cache respone if cache is enabled", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); let response = await server.inject(injectOptions); let payload = JSON.parse(response.payload || {}); expect(payload.data).toBe("ok"); customResponse = { - data: "dummy" + data: "dummy", }; response = await server.inject(injectOptions); @@ -100,7 +93,7 @@ describe("Cache", () => { }); it("should cache boom if cache is enabled", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); customResponse = Boom.badData("Bad data"); @@ -120,14 +113,14 @@ describe("Cache", () => { return undefined; }; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); let response = await server.inject(injectOptions); let payload = JSON.parse(response.payload || {}); expect(payload.data).toBe("ok"); customResponse = { - data: "dummy" + data: "dummy", }; response = await server.inject(injectOptions); diff --git a/__tests__/unit/core-api/plugins/hapi-ajv.test.ts b/__tests__/unit/core-api/plugins/hapi-ajv.test.ts index d9b80cb6ee..0198146e08 100644 --- a/__tests__/unit/core-api/plugins/hapi-ajv.test.ts +++ b/__tests__/unit/core-api/plugins/hapi-ajv.test.ts @@ -1,5 +1,7 @@ import "jest-extended"; + import { Application } from "@packages/core-kernel"; + import { initApp } from "../__support__"; import { initServer } from "./__support__"; @@ -26,12 +28,12 @@ describe("Hapi Ajv", () => { enabled: true, stdTTL: 0, // unlimited checkperiod: 0, // no periodic check - } + }, }, }; customResponse = { - data: "ok" + data: "ok", }; customRouteOptions = { @@ -43,7 +45,7 @@ describe("Hapi Ajv", () => { properties: { test: { minItems: 1, - maxItems: 1 + maxItems: 1, }, }, }, @@ -56,25 +58,25 @@ describe("Hapi Ajv", () => { }; customRoute = { - method: 'POST', - path: '/test', + method: "POST", + path: "/test", handler: () => { - return customResponse + return customResponse; }, - options: customRouteOptions + options: customRouteOptions, }; injectOptions = { - method: 'POST', - url: '/test?test=0', + method: "POST", + url: "/test?test=0", payload: { - test: ["Item1"] - } + test: ["Item1"], + }, }; }); it("should return ok if payload is valid", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); @@ -82,7 +84,7 @@ describe("Hapi Ajv", () => { }); it("should return error if payload is not valid", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); injectOptions.payload.test = ["Item1", "Item2"]; @@ -92,9 +94,9 @@ describe("Hapi Ajv", () => { }); it("should return error if query is not valid", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); - injectOptions.url = '/test'; + injectOptions.url = "/test"; const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); diff --git a/__tests__/unit/core-api/plugins/pagination.test.ts b/__tests__/unit/core-api/plugins/pagination.test.ts index 47ebc91f9e..5124846cc8 100644 --- a/__tests__/unit/core-api/plugins/pagination.test.ts +++ b/__tests__/unit/core-api/plugins/pagination.test.ts @@ -1,6 +1,7 @@ import "jest-extended"; import { Application } from "@packages/core-kernel"; + import { initApp } from "../__support__"; import { initServer } from "./__support__"; @@ -28,43 +29,43 @@ describe("Pagination", () => { customResponse = ["Item1", "Item2", "Item3"]; customRoute = { - method: 'GET', - path: '/api/transactions', + method: "GET", + path: "/api/transactions", handler: () => { - return customResponse - } + return customResponse; + }, }; injectOptions = { - method: 'GET', - url: '/api/transactions', + method: "GET", + url: "/api/transactions", }; }); it("should return paginated payload", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); expect(payload.data).toEqual(customResponse); - expect(payload.meta).toEqual(expect.objectContaining( - { + expect(payload.meta).toEqual( + expect.objectContaining({ count: 3, - pageCount: 1 - } - )); + pageCount: 1, + }), + ); }); it("should not return paginated payload if disabled on route", async () => { customRoute.options = { plugins: { pagination: { - pagination: false - } - } + pagination: false, + }, + }, }; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); @@ -75,71 +76,71 @@ describe("Pagination", () => { }); it("should return paginated payload when params are invalid", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); injectOptions.url = '/api/transactions?page="invalid_values"&limit="invalid_value"'; const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); expect(payload.data).toEqual(customResponse); - expect(payload.meta).toEqual(expect.objectContaining( - { + expect(payload.meta).toEqual( + expect.objectContaining({ count: 3, - pageCount: 1 - } - )); + pageCount: 1, + }), + ); }); it("should return paginated payload with total count", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); customResponse.totalCount = 5; const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); - expect(payload.meta).toEqual(expect.objectContaining( - { + expect(payload.meta).toEqual( + expect.objectContaining({ count: 3, pageCount: 1, - totalCount: 5 - } - )); + totalCount: 5, + }), + ); }); it("should return paginated payload with previous url", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); - injectOptions.url = '/api/transactions?page=2'; + injectOptions.url = "/api/transactions?page=2"; customResponse.totalCount = 5; const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); - expect(payload.meta).toEqual(expect.objectContaining( - { + expect(payload.meta).toEqual( + expect.objectContaining({ count: 3, pageCount: 1, - totalCount: 5 - } - )); + totalCount: 5, + }), + ); expect(payload.meta.previous).toBeDefined(); }); it("should return paginated payload with response object", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); customResponse.response = { - test: "test_value" + test: "test_value", }; const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); - expect(payload.meta).toEqual(expect.objectContaining( - { + expect(payload.meta).toEqual( + expect.objectContaining({ count: 3, - pageCount: 1 - } - )); + pageCount: 1, + }), + ); expect(payload.test).toEqual("test_value"); }); }); diff --git a/__tests__/unit/core-api/plugins/rate-limit.test.ts b/__tests__/unit/core-api/plugins/rate-limit.test.ts index 2356fdaee9..503aa439d5 100644 --- a/__tests__/unit/core-api/plugins/rate-limit.test.ts +++ b/__tests__/unit/core-api/plugins/rate-limit.test.ts @@ -1,7 +1,8 @@ import "jest-extended"; -import { RLWrapperBlackAndWhite } from "rate-limiter-flexible"; import { Application } from "@packages/core-kernel"; +import { RLWrapperBlackAndWhite } from "rate-limiter-flexible"; + import { initApp } from "../__support__"; import { initServer } from "./__support__"; @@ -27,32 +28,31 @@ describe("Rate limit", () => { enabled: true, points: 1, duration: 1, - } + }, }, }; customResponse = { - data: "ok" + data: "ok", }; customRoute = { - method: 'GET', - path: '/test', + method: "GET", + path: "/test", handler: () => { - return customResponse + return customResponse; }, }; injectOptions = { - method: 'GET', - url: '/test', + method: "GET", + url: "/test", }; }); - it("shod resolve if rate limit is disabled", async () => { defaults.plugins.rateLimit.enabled = false; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); @@ -62,7 +62,7 @@ describe("Rate limit", () => { it("shod return error if rate limit is exceeded", async () => { defaults.plugins.rateLimit.whitelist = []; defaults.plugins.rateLimit.blacklist = []; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); let response = await server.inject(injectOptions); let payload = JSON.parse(response.payload || {}); @@ -75,7 +75,7 @@ describe("Rate limit", () => { it("shod resolve if whitelisted", async () => { defaults.plugins.rateLimit.whitelist = ["127.0.0.1"]; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); @@ -84,20 +84,19 @@ describe("Rate limit", () => { it("shod resolve if whitelisted as pattern", async () => { defaults.plugins.rateLimit.whitelist = ["*"]; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); expect(payload.data).toBe("ok"); }); - it("shod return error if blacklisted", async () => { defaults.plugins.rateLimit.whitelist = []; defaults.plugins.rateLimit.blacklist = ["127.0.0.1"]; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); - let response = await server.inject(injectOptions); + const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); expect(payload.statusCode).toBe(429); }); @@ -107,9 +106,9 @@ describe("Rate limit", () => { throw new Error(); }; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); - let response = await server.inject(injectOptions); + const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); expect(payload.statusCode).toBe(500); }); diff --git a/__tests__/unit/core-api/plugins/whitelist.test.ts b/__tests__/unit/core-api/plugins/whitelist.test.ts index 541ff6f86f..743f0654c3 100644 --- a/__tests__/unit/core-api/plugins/whitelist.test.ts +++ b/__tests__/unit/core-api/plugins/whitelist.test.ts @@ -1,6 +1,7 @@ import "jest-extended"; import { Application } from "@packages/core-kernel"; + import { initApp } from "../__support__"; import { initServer } from "./__support__"; @@ -26,28 +27,27 @@ describe("Whitelist", () => { }; customRoute = { - method: 'GET', - path: '/test', - handler: () => 'ok', + method: "GET", + path: "/test", + handler: () => "ok", }; injectOptions = { - method: 'GET', - url: '/test', + method: "GET", + url: "/test", }; }); - it("shod resolve if whitelist options is not provided", async () => { delete defaults.plugins.whitelist; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); expect(response.payload).toBe("ok"); }); it("shod resolve if request ip is whitelisted", async () => { - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); expect(response.payload).toBe("ok"); @@ -55,7 +55,7 @@ describe("Whitelist", () => { it("shod return error if request ip is not whitelisted", async () => { defaults.plugins.whitelist = ["128.0.0.1"]; - let server = await initServer(app, defaults, customRoute); + const server = await initServer(app, defaults, customRoute); const response = await server.inject(injectOptions); const payload = JSON.parse(response.payload || {}); diff --git a/__tests__/unit/core-api/resources/delegates.test.ts b/__tests__/unit/core-api/resources/delegates.test.ts index 0208fdd58e..5a46a5eee8 100644 --- a/__tests__/unit/core-api/resources/delegates.test.ts +++ b/__tests__/unit/core-api/resources/delegates.test.ts @@ -1,4 +1,5 @@ import "jest-extended"; + import { DelegateResource } from "@packages/core-api/src/resources"; let resource: DelegateResource; diff --git a/__tests__/unit/core-api/resources/fee-statistics.test.ts b/__tests__/unit/core-api/resources/fee-statistics.test.ts index 6fdef38879..e5adb8117e 100644 --- a/__tests__/unit/core-api/resources/fee-statistics.test.ts +++ b/__tests__/unit/core-api/resources/fee-statistics.test.ts @@ -1,4 +1,5 @@ import "jest-extended"; + import { FeeStatisticsResource } from "@packages/core-api/src/resources"; // TODO: Use from support or add to node code @@ -27,8 +28,8 @@ describe("DelegateResource", () => { avgFee: "15", minFee: "10", maxFee: "20", - sum: "200" - } + sum: "200", + }; }); describe("raw", () => { @@ -44,8 +45,8 @@ describe("DelegateResource", () => { fees: { minFee: 10, maxFee: 20, - avgFee: 15 - } + avgFee: 15, + }, }); }); }); diff --git a/__tests__/unit/core-api/resources/lock.test.ts b/__tests__/unit/core-api/resources/lock.test.ts index 59d3697333..a4cedd23db 100644 --- a/__tests__/unit/core-api/resources/lock.test.ts +++ b/__tests__/unit/core-api/resources/lock.test.ts @@ -1,8 +1,8 @@ import "jest-extended"; + import { LockResource } from "@packages/core-api/src/resources"; import { Utils } from "@packages/crypto/src"; - let resource: LockResource; beforeEach(() => { @@ -34,7 +34,7 @@ describe("DelegateResource", () => { epoch: 2, human: "2017-03-21T13:00:02.000Z", unix: 1490101202, - } + }, }); }); }); diff --git a/__tests__/unit/core-api/resources/peer.test.ts b/__tests__/unit/core-api/resources/peer.test.ts index 5bf9c5bd97..a44fb8117c 100644 --- a/__tests__/unit/core-api/resources/peer.test.ts +++ b/__tests__/unit/core-api/resources/peer.test.ts @@ -1,4 +1,5 @@ import "jest-extended"; + import { PeerResource } from "@packages/core-api/src/resources"; let resource: PeerResource; @@ -17,7 +18,7 @@ describe("PeerResource", () => { ports: [4003], version: "3.0.0", height: 2, - latency: 200 + latency: 200, }; }); @@ -33,11 +34,11 @@ describe("PeerResource", () => { }); it("should return transformed object when data have state", async () => { - let dataWithState = Object.assign({}, data); + const dataWithState = Object.assign({}, data); // @ts-ignore dataWithState.state = { - height: 2 + height: 2, }; expect(resource.transform(dataWithState)).toEqual(data); diff --git a/__tests__/unit/core-api/resources/ports.test.ts b/__tests__/unit/core-api/resources/ports.test.ts index 99ef2a9a21..73d0b590eb 100644 --- a/__tests__/unit/core-api/resources/ports.test.ts +++ b/__tests__/unit/core-api/resources/ports.test.ts @@ -1,11 +1,13 @@ import "jest-extended"; -import { PortsResource } from "@packages/core-api/src/resources"; -import { Application, Container, Providers } from "@packages/core-kernel"; -import { initApp } from "../__support__"; + import { ServiceProvider as CoreApiServiceProvider } from "@packages/core-api/src"; import { defaults } from "@packages/core-api/src/defaults"; -import { ServiceProviderRepository } from "../mocks"; +import { PortsResource } from "@packages/core-api/src/resources"; +import { Application, Container, Providers } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Mocks } from "@packages/core-test-framework"; + +import { initApp } from "../__support__"; let resource: PortsResource; let app: Application; @@ -14,7 +16,9 @@ beforeEach(() => { app = initApp(); app.unbind(Identifiers.ServiceProviderRepository); - app.bind(Identifiers.ServiceProviderRepository).toConstantValue(ServiceProviderRepository.serviceProviderRepository); + app.bind(Identifiers.ServiceProviderRepository).toConstantValue( + Mocks.ServiceProviderRepository.instance, + ); }); beforeEach(() => { @@ -30,9 +34,11 @@ describe("PortsResource", () => { describe("transform", () => { beforeEach(async () => { - let coreApiServiceProvider = app.resolve(CoreApiServiceProvider); + const coreApiServiceProvider = app.resolve(CoreApiServiceProvider); - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfiguration = app.get( + Container.Identifiers.PluginConfiguration, + ); // @ts-ignore defaults.enabled = true; @@ -44,14 +50,14 @@ describe("PortsResource", () => { await coreApiServiceProvider.register(); coreApiServiceProvider.name = () => { - return "@arkecosystem/core-api" + return "@arkecosystem/core-api"; }; - ServiceProviderRepository.setServiceProviders([coreApiServiceProvider]); + Mocks.ServiceProviderRepository.setServiceProviders([coreApiServiceProvider]); }); it("should return transformed object", async () => { - expect(resource.transform({})).toEqual({ '@arkecosystem/core-api': 4003 }); + expect(resource.transform({})).toEqual({ "@arkecosystem/core-api": 4003 }); }); it("should return transformed object with server port", async () => { @@ -60,7 +66,7 @@ describe("PortsResource", () => { // @ts-ignore defaults.server.port = 4003; - expect(resource.transform({})).toEqual({ '@arkecosystem/core-api': 4003 }); + expect(resource.transform({})).toEqual({ "@arkecosystem/core-api": 4003 }); }); }); }); diff --git a/__tests__/unit/core-api/resources/round.test.ts b/__tests__/unit/core-api/resources/round.test.ts index dba2714c43..f6c279f30e 100644 --- a/__tests__/unit/core-api/resources/round.test.ts +++ b/__tests__/unit/core-api/resources/round.test.ts @@ -1,4 +1,5 @@ import "jest-extended"; + import { RoundResource } from "@packages/core-api/src/resources"; let resource: RoundResource; diff --git a/__tests__/unit/core-api/resources/transaction.test.ts b/__tests__/unit/core-api/resources/transaction.test.ts index 1327302072..e5c771d0fa 100644 --- a/__tests__/unit/core-api/resources/transaction.test.ts +++ b/__tests__/unit/core-api/resources/transaction.test.ts @@ -1,11 +1,13 @@ import "jest-extended"; + import { TransactionResource } from "@packages/core-api/src/resources"; -import { BuilderFactory } from "@packages/crypto/src/transactions"; -import { Identities, Interfaces, Utils } from "@packages/crypto"; -import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { Application } from "@packages/core-kernel"; +import { Mocks } from "@packages/core-test-framework"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Identities, Interfaces, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; + import { initApp, parseObjectWithBigInt } from "../__support__"; -import { BlockchainMocks } from "../mocks"; let app: Application; let resource: TransactionResource; @@ -30,9 +32,9 @@ describe("TransactionResource", () => { describe("raw", () => { it("should return raw object", async () => { - let result = (resource.raw(transferTransaction)); + const result = resource.raw(transferTransaction); - let expectedResult = parseObjectWithBigInt(transferTransaction.data); + const expectedResult = parseObjectWithBigInt(transferTransaction.data); delete expectedResult.typeGroup; expect(result).toEqual(expect.objectContaining(expectedResult)); @@ -41,22 +43,20 @@ describe("TransactionResource", () => { describe("transform", () => { it("should return transformed object", async () => { - let result = (resource.transform(transferTransaction)); + const result = resource.transform(transferTransaction); - let expectedResult = parseObjectWithBigInt(transferTransaction.data); + const expectedResult = parseObjectWithBigInt(transferTransaction.data); expectedResult.confirmations = 0; delete expectedResult.expiration; delete expectedResult.network; delete expectedResult.timestamp; delete expectedResult.recipientId; - expect(result).toEqual(expect.objectContaining( - expectedResult - )); + expect(result).toEqual(expect.objectContaining(expectedResult)); }); it("should return transformed object when contain block", async () => { - let mockBlock: Partial = { + const mockBlock: Partial = { id: "17184958558311101492", version: 2, height: 2, @@ -64,26 +64,24 @@ describe("TransactionResource", () => { reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), - generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), }; - BlockchainMocks.setMockBlock({data: mockBlock} as Partial); + Mocks.Blockchain.setBlock({ data: mockBlock } as Partial); // @ts-ignore transferTransaction.block = mockBlock; - let result = (resource.transform(transferTransaction)); + const result = resource.transform(transferTransaction); - let expectedResult = parseObjectWithBigInt(transferTransaction.data); + const expectedResult = parseObjectWithBigInt(transferTransaction.data); expectedResult.confirmations = 1; delete expectedResult.expiration; delete expectedResult.network; delete expectedResult.timestamp; delete expectedResult.recipientId; - expect(result).toEqual(expect.objectContaining( - expectedResult - )); + expect(result).toEqual(expect.objectContaining(expectedResult)); }); }); }); diff --git a/__tests__/unit/core-api/resources/wallet.test.ts b/__tests__/unit/core-api/resources/wallet.test.ts index e55ff5443d..bc34eb9105 100644 --- a/__tests__/unit/core-api/resources/wallet.test.ts +++ b/__tests__/unit/core-api/resources/wallet.test.ts @@ -1,12 +1,14 @@ import "jest-extended"; + import { WalletResource } from "@packages/core-api/src/resources"; import { Application, Contracts } from "@packages/core-kernel"; -import { buildSenderWallet, initApp, parseObjectWithBigInt } from "../__support__"; -import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Identifiers } from "@packages/core-kernel/src/ioc"; -import { Identities, Transactions, Utils } from "@packages/crypto"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Identities, Transactions, Utils } from "@packages/crypto"; + +import { buildSenderWallet, initApp, parseObjectWithBigInt } from "../__support__"; let app: Application; let resource: WalletResource; @@ -53,14 +55,12 @@ describe("WalletResource", () => { isDelegate: false, isResigned: false, nonce: "0", - publicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) + publicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), }; }); it("should return transformed object", async () => { - expect(resource.transform(senderWallet)).toEqual(expect.objectContaining( - expectedResult - )); + expect(resource.transform(senderWallet)).toEqual(expect.objectContaining(expectedResult)); }); it("should return transformed object when contains additional attributes", async () => { @@ -83,11 +83,9 @@ describe("WalletResource", () => { senderWallet.setAttribute("secondPublicKey", Identities.PublicKey.fromPassphrase(passphrases[2])); expectedResult.secondPublicKey = Identities.PublicKey.fromPassphrase(passphrases[2]); - let result = parseObjectWithBigInt(resource.transform(senderWallet)); + const result = parseObjectWithBigInt(resource.transform(senderWallet)); - expect(result).toEqual(expect.objectContaining( - expectedResult - )); + expect(result).toEqual(expect.objectContaining(expectedResult)); }); }); }); diff --git a/__tests__/unit/core-api/server.test.ts b/__tests__/unit/core-api/server.test.ts index 083a5d1470..0b1df20638 100644 --- a/__tests__/unit/core-api/server.test.ts +++ b/__tests__/unit/core-api/server.test.ts @@ -1,9 +1,10 @@ import "jest-extended"; +import { preparePlugins } from "@packages/core-api/src/plugins"; +import { Server } from "@packages/core-api/src/server"; import { Application, Container, Providers } from "@packages/core-kernel"; + import { initApp } from "./__support__"; -import { Server } from "@packages/core-api/src/server"; -import { preparePlugins } from "@packages/core-api/src/plugins"; let app: Application; @@ -34,14 +35,18 @@ describe("Server", () => { host: "0.0.0.0", port: 4003, routes: { - cors: true - } + cors: true, + }, }; - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); - const pluginConfigurationInstance: Providers.PluginConfiguration = pluginConfiguration.from("core-api", defaults); + const pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfigurationInstance: Providers.PluginConfiguration = pluginConfiguration.from( + "core-api", + defaults, + ); - app.bind(Container.Identifiers.PluginConfiguration).toConstantValue(pluginConfigurationInstance) + app.bind(Container.Identifiers.PluginConfiguration) + .toConstantValue(pluginConfigurationInstance) .when(Container.Selectors.anyAncestorOrTargetTaggedFirst("plugin", "@arkecosystem/core-api")); }); @@ -54,8 +59,8 @@ describe("Server", () => { await expect(server.initialize("Test", serverConfig)).toResolve(); const injectOptions = { - method: 'GET', - url: '/', + method: "GET", + url: "/", }; const response = await server.inject(injectOptions); @@ -69,17 +74,17 @@ describe("Server", () => { it("should add custom route", async () => { await expect(server.initialize("Test", serverConfig)).toResolve(); - let testRoute = { - method: 'GET', - path: '/test', - handler: () => 'ok' + const testRoute = { + method: "GET", + path: "/test", + handler: () => "ok", }; expect(server.route(testRoute)).toResolve(); const injectOptions = { - method: 'GET', - url: '/test', + method: "GET", + url: "/test", }; const response = await server.inject(injectOptions); diff --git a/__tests__/unit/core-api/service-provider.test.ts b/__tests__/unit/core-api/service-provider.test.ts index cb76ec07ae..f2f4382388 100644 --- a/__tests__/unit/core-api/service-provider.test.ts +++ b/__tests__/unit/core-api/service-provider.test.ts @@ -1,9 +1,9 @@ import "jest-extended"; -import path from "path"; import { Identifiers, Server, ServiceProvider as CoreApiServiceProvider } from "@packages/core-api/src"; -import { Application, Container, Providers } from "@packages/core-kernel"; import { defaults } from "@packages/core-api/src/defaults"; +import { Application, Container, Providers } from "@packages/core-kernel"; +import path from "path"; let app: Application; @@ -18,54 +18,29 @@ beforeEach(() => { app.bind(Container.Identifiers.LogService).toConstantValue(logger); - app - .bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); - app - .bind(Container.Identifiers.StateStore) - .toConstantValue({}); + app.bind(Container.Identifiers.StateStore).toConstantValue({}); - app - .bind(Container.Identifiers.BlockchainService) - .toConstantValue({}); + app.bind(Container.Identifiers.BlockchainService).toConstantValue({}); - app - .bind(Container.Identifiers.BlockRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.BlockRepository).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionRepository).toConstantValue({}); - app - .bind(Container.Identifiers.WalletRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.WalletRepository).toConstantValue({}); - app - .bind(Container.Identifiers.PeerNetworkMonitor) - .toConstantValue({}); + app.bind(Container.Identifiers.PeerNetworkMonitor).toConstantValue({}); - app - .bind(Container.Identifiers.PeerStorage) - .toConstantValue({}); + app.bind(Container.Identifiers.PeerStorage).toConstantValue({}); - app - .bind(Container.Identifiers.RoundRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.RoundRepository).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionPoolQuery) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionPoolProcessorFactory) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolProcessorFactory).toConstantValue({}); - app - .bind(Container.Identifiers.EventDispatcherService) - .toConstantValue({}); + app.bind(Container.Identifiers.EventDispatcherService).toConstantValue({}); defaults.server.https.enabled = "enabled"; defaults.server.https.tls.key = path.resolve(__dirname, "./__fixtures__/key.pem"); @@ -73,11 +48,10 @@ beforeEach(() => { }); describe("ServiceProvider", () => { - it("should register", async () => { - let coreApiServiceProvider = app.resolve(CoreApiServiceProvider); + const coreApiServiceProvider = app.resolve(CoreApiServiceProvider); - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); const instance: Providers.PluginConfiguration = pluginConfiguration.from("core-api", defaults); coreApiServiceProvider.setConfig(instance); @@ -88,9 +62,9 @@ describe("ServiceProvider", () => { }); it("should boot", async () => { - let coreApiServiceProvider = app.resolve(CoreApiServiceProvider); + const coreApiServiceProvider = app.resolve(CoreApiServiceProvider); - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); const instance: Providers.PluginConfiguration = pluginConfiguration.from("core-api", defaults); coreApiServiceProvider.setConfig(instance); @@ -103,9 +77,9 @@ describe("ServiceProvider", () => { }); it("should dispose", async () => { - let coreApiServiceProvider = app.resolve(CoreApiServiceProvider); + const coreApiServiceProvider = app.resolve(CoreApiServiceProvider); - let pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); + const pluginConfiguration = app.get(Container.Identifiers.PluginConfiguration); const instance: Providers.PluginConfiguration = pluginConfiguration.from("core-api", defaults); coreApiServiceProvider.setConfig(instance); @@ -120,8 +94,8 @@ describe("ServiceProvider", () => { }); it("should not be required", async () => { - let coreApiServiceProvider = app.resolve(CoreApiServiceProvider); + const coreApiServiceProvider = app.resolve(CoreApiServiceProvider); await expect(coreApiServiceProvider.required()).resolves.toBeFalse(); - }) + }); }); diff --git a/__tests__/unit/core-magistrate-api/__fixtures__/assets.ts b/__tests__/unit/core-magistrate-api/__fixtures__/assets.ts index ab89b5e16a..8bddbc38d7 100644 --- a/__tests__/unit/core-magistrate-api/__fixtures__/assets.ts +++ b/__tests__/unit/core-magistrate-api/__fixtures__/assets.ts @@ -4,7 +4,7 @@ export const businessRegistrationAsset: IBusinessRegistrationAsset = { name: "DummyBusiness", website: "https://www.dummy.example", vat: "EX1234567890", - repository: "https://www.dummy.example/repo" + repository: "https://www.dummy.example/repo", }; export const bridgechainRegistrationAsset = { diff --git a/__tests__/unit/core-magistrate-api/__fixtures__/index.ts b/__tests__/unit/core-magistrate-api/__fixtures__/index.ts index fb20927166..eb34a5e24b 100644 --- a/__tests__/unit/core-magistrate-api/__fixtures__/index.ts +++ b/__tests__/unit/core-magistrate-api/__fixtures__/index.ts @@ -1,3 +1,3 @@ -import * as Assets from './assets' +import * as Assets from "./assets"; -export { Assets } +export { Assets }; diff --git a/__tests__/unit/core-magistrate-api/__support__/index.ts b/__tests__/unit/core-magistrate-api/__support__/index.ts index 171a209197..221420d0b6 100644 --- a/__tests__/unit/core-magistrate-api/__support__/index.ts +++ b/__tests__/unit/core-magistrate-api/__support__/index.ts @@ -13,7 +13,8 @@ import { } from "@packages/core-magistrate-transactions/src/handlers"; import { addressesIndexer, - ipfsIndexer, locksIndexer, + ipfsIndexer, + locksIndexer, publicKeysIndexer, usernamesIndexer, } from "@packages/core-state/src/wallets/indexers/indexers"; @@ -24,69 +25,41 @@ import { } from "@packages/core-magistrate-transactions/src/wallet-indexes"; export type PaginatedResponse = { - totalCount: number, - results: [object], - meta: object -} + totalCount: number; + results: [object]; + meta: object; +}; export type ItemResponse = { - data: object -} + data: object; +}; export const buildSenderWallet = (app: Application): Contracts.State.Wallet => { - let walletRepository = app.get(Identifiers.WalletRepository); + const walletRepository = app.get(Identifiers.WalletRepository); - let wallet: Contracts.State.Wallet = walletRepository.createWallet(Identities.Address.fromPassphrase(passphrases[0])); + const wallet: Contracts.State.Wallet = walletRepository.createWallet( + Identities.Address.fromPassphrase(passphrases[0]), + ); wallet.publicKey = Identities.PublicKey.fromPassphrase(passphrases[0]); wallet.balance = Utils.BigNumber.make(7527654310); - return wallet + return wallet; }; export const initApp = (): Application => { - let app = new Application(new Container.Container()); - - app - .bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); - - app - .bind(Container.Identifiers.StateStore) - .toConstantValue({}); - - app - .bind(Container.Identifiers.BlockchainService) - .toConstantValue({}); - - app - .bind(Container.Identifiers.BlockRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.PeerNetworkMonitor) - .toConstantValue({}); - - app - .bind(Container.Identifiers.PeerStorage) - .toConstantValue({}); - - app - .bind(Container.Identifiers.RoundRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionPoolQuery) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionPoolProcessorFactory) - .toConstantValue({}); + const app = new Application(new Container.Container()); + + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); + app.bind(Container.Identifiers.StateStore).toConstantValue({}); + app.bind(Container.Identifiers.BlockchainService).toConstantValue({}); + app.bind(Container.Identifiers.BlockRepository).toConstantValue({}); + app.bind(Container.Identifiers.TransactionRepository).toConstantValue({}); + app.bind(Container.Identifiers.PeerNetworkMonitor).toConstantValue({}); + app.bind(Container.Identifiers.PeerStorage).toConstantValue({}); + app.bind(Container.Identifiers.RoundRepository).toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolProcessorFactory).toConstantValue({}); app.bind(Identifiers.TransactionHandler).to(One.TransferTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.TransferTransactionHandler); @@ -111,54 +84,56 @@ export const initApp = (): Application => { app.bind(Identifiers.TransactionHandler).to(BusinessRegistrationTransactionHandler); app.bind(Identifiers.TransactionHandler).to(BridgechainRegistrationTransactionHandler); - app - .bind(Identifiers.WalletAttributes) + app.bind(Identifiers.WalletAttributes) .to(Services.Attributes.AttributeSet) .inSingletonScope(); - app - .bind(Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Addresses, indexer: addressesIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.PublicKeys, indexer: publicKeysIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Usernames, indexer: usernamesIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Ipfs, indexer: ipfsIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: Contracts.State.WalletIndexes.Locks, indexer: locksIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: MagistrateIndex.Businesses, indexer: businessIndexer }); - - app - .bind(Container.Identifiers.WalletRepositoryIndexerIndex) - .toConstantValue({ name: MagistrateIndex.Bridgechains, indexer: bridgechainIndexer }); - - app - .bind(Identifiers.WalletFactory) - .toFactory((context: Container.interfaces.Context) => (address: string) => + app.bind(Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Addresses, + indexer: addressesIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.PublicKeys, + indexer: publicKeysIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Usernames, + indexer: usernamesIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Ipfs, + indexer: ipfsIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: Contracts.State.WalletIndexes.Locks, + indexer: locksIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: MagistrateIndex.Businesses, + indexer: businessIndexer, + }); + + app.bind(Container.Identifiers.WalletRepositoryIndexerIndex).toConstantValue({ + name: MagistrateIndex.Bridgechains, + indexer: bridgechainIndexer, + }); + + app.bind(Identifiers.WalletFactory).toFactory( + (context: Container.interfaces.Context) => (address: string) => new Wallets.Wallet( address, new Services.Attributes.AttributeMap( context.container.get(Identifiers.WalletAttributes), ), ), - ); + ); - app - .bind(Identifiers.WalletRepository) - .to(Wallets.WalletRepository) - .inSingletonScope(); + app.bind(Identifiers.WalletRepository).to(Wallets.WalletRepository).inSingletonScope(); // Triggers registration of indexes app.get(Identifiers.TransactionHandlerRegistry); diff --git a/__tests__/unit/core-magistrate-api/controllers/bridgechains.test.ts b/__tests__/unit/core-magistrate-api/controllers/bridgechains.test.ts index ae62298719..b36f771f51 100644 --- a/__tests__/unit/core-magistrate-api/controllers/bridgechains.test.ts +++ b/__tests__/unit/core-magistrate-api/controllers/bridgechains.test.ts @@ -3,15 +3,14 @@ import "jest-extended"; import Hapi from "@hapi/hapi"; import { Application, Contracts } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { BridgechainController } from "@packages/core-magistrate-api/src/controllers/bridgechains"; import { Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; -import { Transactions } from "@packages/crypto"; +import { IBridgechainRegistrationAsset } from "@packages/core-magistrate-crypto/src/interfaces"; import { Wallets } from "@packages/core-state"; -import { BridgechainController } from "@packages/core-magistrate-api/src/controllers/bridgechains"; +import { Transactions } from "@packages/crypto"; + +import { Assets } from "../__fixtures__"; import { buildSenderWallet, initApp, ItemResponse, PaginatedResponse } from "../__support__"; -import { Assets } from '../__fixtures__' -import { - IBridgechainRegistrationAsset, -} from "@packages/core-magistrate-crypto/src/interfaces"; let app: Application; let controller: BridgechainController; @@ -24,7 +23,7 @@ beforeEach(() => { walletRepository = app.get(Identifiers.WalletRepository); - let businessRegistrationAsset = Assets.businessRegistrationAsset; + const businessRegistrationAsset = Assets.businessRegistrationAsset; senderWallet = buildSenderWallet(app); @@ -34,7 +33,7 @@ beforeEach(() => { bridgechainRegistrationAsset = Assets.bridgechainRegistrationAsset; - let businessAttributes = senderWallet.getAttribute("business"); + const businessAttributes = senderWallet.getAttribute("business"); businessAttributes.bridgechains = {}; @@ -61,42 +60,38 @@ afterEach(() => { describe("BridgechainController", () => { describe("index", () => { it("should return registered bridgechain", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { query: { page: 1, limit: 100, - } + }, }; - let response = (await controller.index(request, undefined)); + const response = (await controller.index(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBe(1); - expect(response.results[0]).toEqual(expect.objectContaining( - bridgechainRegistrationAsset - )); + expect(response.results[0]).toEqual(expect.objectContaining(bridgechainRegistrationAsset)); }); }); describe("show", () => { it("should return registered bridgechain", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: bridgechainRegistrationAsset.genesisHash - } + id: bridgechainRegistrationAsset.genesisHash, + }, }; - let response = (await controller.show(request, undefined)); + const response = (await controller.show(request, undefined)) as ItemResponse; - expect(response.data).toEqual(expect.objectContaining( - bridgechainRegistrationAsset - )); + expect(response.data).toEqual(expect.objectContaining(bridgechainRegistrationAsset)); }); it("should return error if registered bridgechain not found", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { params: { - id: "invalid-genesis-hash" - } + id: "invalid-genesis-hash", + }, }; await expect(controller.show(request, undefined)).resolves.toThrowError("Bridgechain not found"); @@ -105,23 +100,21 @@ describe("BridgechainController", () => { describe("search", () => { it("should return registered bridgechain", async () => { - let request: Hapi.Request = { + const request: Hapi.Request = { payload: { - id: bridgechainRegistrationAsset.genesisHash + id: bridgechainRegistrationAsset.genesisHash, }, query: { page: 1, limit: 100, - } + }, }; - let response = (await controller.search(request, undefined)); + const response = (await controller.search(request, undefined)) as PaginatedResponse; expect(response.totalCount).toBe(1); expect(response.results[0]).toBeObject(); - expect(response.results[0]).toEqual(expect.objectContaining( - bridgechainRegistrationAsset - )); + expect(response.results[0]).toEqual(expect.objectContaining(bridgechainRegistrationAsset)); }); }); }); diff --git a/__tests__/unit/core-magistrate-api/controllers/businesses.test.ts b/__tests__/unit/core-magistrate-api/controllers/businesses.test.ts index 09088b24a2..496e5840be 100644 --- a/__tests__/unit/core-magistrate-api/controllers/businesses.test.ts +++ b/__tests__/unit/core-magistrate-api/controllers/businesses.test.ts @@ -126,9 +126,7 @@ describe("BusinessController", () => { }, }; - await expect(controller.show(request, undefined)).resolves.toThrowError( - "Business not found", - ); + await expect(controller.show(request, undefined)).resolves.toThrowError("Business not found"); }); }); @@ -210,7 +208,7 @@ describe("BusinessController", () => { // @ts-ignore controller.toPagination = () => { - throw new Error() + throw new Error(); }; await expect(controller.bridgechains(request, undefined)).resolves.toThrowError(); diff --git a/__tests__/unit/core-magistrate-api/resources/bridgechain.test.ts b/__tests__/unit/core-magistrate-api/resources/bridgechain.test.ts index 29cd3c1d87..ccea0095b7 100644 --- a/__tests__/unit/core-magistrate-api/resources/bridgechain.test.ts +++ b/__tests__/unit/core-magistrate-api/resources/bridgechain.test.ts @@ -1,7 +1,7 @@ import "jest-extended"; import { BridgechainResource } from "@packages/core-magistrate-api/src/resources"; import { IBridgechainRegistrationAsset } from "@packages/core-magistrate-crypto/src/interfaces"; -import { Assets } from '../__fixtures__'; +import { Assets } from "../__fixtures__"; let resource: BridgechainResource; let bridgechainRegistrationAsset: IBridgechainRegistrationAsset; diff --git a/__tests__/unit/core-magistrate-api/resources/businesses.test.ts b/__tests__/unit/core-magistrate-api/resources/businesses.test.ts index c543c69c50..e341298a0e 100644 --- a/__tests__/unit/core-magistrate-api/resources/businesses.test.ts +++ b/__tests__/unit/core-magistrate-api/resources/businesses.test.ts @@ -1,7 +1,7 @@ import "jest-extended"; import { BusinessResource } from "@packages/core-magistrate-api/src/resources"; import { IBusinessRegistrationAsset } from "@packages/core-magistrate-crypto/src/interfaces"; -import { Assets } from '../__fixtures__'; +import { Assets } from "../__fixtures__"; let resource: BusinessResource; let businessRegistrationAsset: IBusinessRegistrationAsset; diff --git a/__tests__/unit/core-magistrate-api/service-provider.test.ts b/__tests__/unit/core-magistrate-api/service-provider.test.ts index cd3cc5ba60..c782fd9c39 100644 --- a/__tests__/unit/core-magistrate-api/service-provider.test.ts +++ b/__tests__/unit/core-magistrate-api/service-provider.test.ts @@ -10,50 +10,27 @@ let app: Application; beforeEach(() => { app = new Application(new Container.Container()); - app - .bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); - - app - .bind(Container.Identifiers.StateStore) - .toConstantValue({}); - - app - .bind(Container.Identifiers.BlockchainService) - .toConstantValue({}); - - app - .bind(Container.Identifiers.BlockRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.WalletRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.PeerNetworkMonitor) - .toConstantValue({}); - - app - .bind(Container.Identifiers.PeerStorage) - .toConstantValue({}); - - app - .bind(Container.Identifiers.RoundRepository) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionPoolQuery) - .toConstantValue({}); - - app - .bind(Container.Identifiers.TransactionPoolProcessorFactory) - .toConstantValue({}); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); + + app.bind(Container.Identifiers.StateStore).toConstantValue({}); + + app.bind(Container.Identifiers.BlockchainService).toConstantValue({}); + + app.bind(Container.Identifiers.BlockRepository).toConstantValue({}); + + app.bind(Container.Identifiers.TransactionRepository).toConstantValue({}); + + app.bind(Container.Identifiers.WalletRepository).toConstantValue({}); + + app.bind(Container.Identifiers.PeerNetworkMonitor).toConstantValue({}); + + app.bind(Container.Identifiers.PeerStorage).toConstantValue({}); + + app.bind(Container.Identifiers.RoundRepository).toConstantValue({}); + + app.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue({}); + + app.bind(Container.Identifiers.TransactionPoolProcessorFactory).toConstantValue({}); }); describe("ServiceProvider", () => { @@ -78,5 +55,5 @@ describe("ServiceProvider", () => { it("should not be required", async () => { await expect(serviceProvider.required()).resolves.toBeFalse(); - }) + }); }); diff --git a/__tests__/unit/core-magistrate-crypto/transactions/business-resgination.test.ts b/__tests__/unit/core-magistrate-crypto/transactions/business-resgination.test.ts index f3b3f5ca8d..2834927bc6 100644 --- a/__tests__/unit/core-magistrate-crypto/transactions/business-resgination.test.ts +++ b/__tests__/unit/core-magistrate-crypto/transactions/business-resgination.test.ts @@ -18,11 +18,7 @@ describe("Business resignation ser/deser", () => { builder = new BusinessResignationBuilder(); }); it("should ser/deserialize giving back original fields", () => { - const businessResignation = builder - .network(23) - .version(2) - .sign("passphrase") - .getStruct(); + const businessResignation = builder.network(23).version(2).sign("passphrase").getStruct(); const serialized = Transactions.TransactionFactory.fromData(businessResignation).serialized.toString("hex"); const deserialized = Transactions.Deserializer.deserialize(serialized); diff --git a/__tests__/unit/core-magistrate-transactions/__support__/app.ts b/__tests__/unit/core-magistrate-transactions/__support__/app.ts index dbe66f9fce..b7a42068d1 100644 --- a/__tests__/unit/core-magistrate-transactions/__support__/app.ts +++ b/__tests__/unit/core-magistrate-transactions/__support__/app.ts @@ -30,9 +30,7 @@ import { TransactionHandlerProvider } from "@packages/core-transactions/src/hand import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Identities, Utils } from "@packages/crypto"; import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; - -import { blockRepository } from "../mocks/block-repository"; -import { transactionRepository } from "../mocks/transaction-repository"; +import { Mocks } from "@packages/core-test-framework"; const logger = { notice: jest.fn(), @@ -95,9 +93,7 @@ export const initApp = (): Application => { ), ); - app.bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); app.get(Container.Identifiers.PluginConfiguration).set("maxTransactionAge", 500); app.get(Container.Identifiers.PluginConfiguration).set( @@ -109,17 +105,11 @@ export const initApp = (): Application => { 300, ); - app.bind(Container.Identifiers.StateStore) - .to(StateStore) - .inTransientScope(); + app.bind(Container.Identifiers.StateStore).to(StateStore).inTransientScope(); - app.bind(Identifiers.TransactionPoolMempool) - .to(Mempool) - .inSingletonScope(); + app.bind(Identifiers.TransactionPoolMempool).to(Mempool).inSingletonScope(); - app.bind(Identifiers.TransactionPoolQuery) - .to(Query) - .inSingletonScope(); + app.bind(Identifiers.TransactionPoolQuery).to(Query).inSingletonScope(); app.bind(Container.Identifiers.TransactionPoolCollator).to(Collator); app.bind(Container.Identifiers.TransactionPoolDynamicFeeMatcher).to(DynamicFeeMatcher); @@ -131,17 +121,13 @@ export const initApp = (): Application => { ); app.bind(Container.Identifiers.TransactionPoolSenderState).to(SenderState); - app.bind(Identifiers.WalletRepository) - .to(Wallets.WalletRepository) - .inSingletonScope(); + app.bind(Identifiers.WalletRepository).to(Wallets.WalletRepository).inSingletonScope(); - app.bind(Identifiers.EventDispatcherService) - .to(NullEventDispatcher) - .inSingletonScope(); + app.bind(Identifiers.EventDispatcherService).to(NullEventDispatcher).inSingletonScope(); - app.bind(Identifiers.BlockRepository).toConstantValue(blockRepository); + app.bind(Identifiers.BlockRepository).toConstantValue(Mocks.BlockRepository.instance); - app.bind(Identifiers.TransactionRepository).toConstantValue(transactionRepository); + app.bind(Identifiers.TransactionRepository).toConstantValue(Mocks.TransactionRepository.instance); app.bind(Identifiers.TransactionHandler).to(One.TransferTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.TransferTransactionHandler); @@ -160,12 +146,8 @@ export const initApp = (): Application => { app.bind(Identifiers.TransactionHandler).to(Two.HtlcClaimTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.HtlcRefundTransactionHandler); - app.bind(Identifiers.TransactionHandlerProvider) - .to(TransactionHandlerProvider) - .inSingletonScope(); - app.bind(Identifiers.TransactionHandlerRegistry) - .to(TransactionHandlerRegistry) - .inSingletonScope(); + app.bind(Identifiers.TransactionHandlerProvider).to(TransactionHandlerProvider).inSingletonScope(); + app.bind(Identifiers.TransactionHandlerRegistry).to(TransactionHandlerRegistry).inSingletonScope(); return app; }; diff --git a/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/assets.ts b/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/assets.ts new file mode 100644 index 0000000000..afd613d2e1 --- /dev/null +++ b/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/assets.ts @@ -0,0 +1,47 @@ +import { + IBridgechainRegistrationAsset, IBridgechainUpdateAsset, + IBusinessRegistrationAsset, IBusinessUpdateAsset, +} from "@packages/core-magistrate-crypto/src/interfaces"; + +export const businessRegistrationAsset: IBusinessRegistrationAsset = { + name: "DummyBusiness", + website: "https://www.dummy.example", + vat: "EX1234567890", + repository: "https://www.dummy.example/repo", +}; + +export const bridgechainRegistrationAsset: IBridgechainRegistrationAsset = { + name: "arkecosystem1", + seedNodes: [ + "74.125.224.71", + "74.125.224.72", + "64.233.173.193", + "2001:4860:4860::8888", + "2001:4860:4860::8844", + ], + genesisHash: "127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935", + bridgechainRepository: "http://www.repository.com/myorg/myrepo", + bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", + ports: { "@arkecosystem/core-api": 12345 }, +}; + +export const businessUpdateAsset: IBusinessUpdateAsset = { + name: "DummyBusinessUpdated", + website: "https://www.dummy.example.updated", + vat: "UEX1234567890", + repository: "https://www.dummy.example/repo/updated", +}; + +export const bridgechainUpdateAsset: IBridgechainUpdateAsset = { + bridgechainId: bridgechainRegistrationAsset.genesisHash, + seedNodes: [ + "74.125.224.71", + "74.125.224.72", + "64.233.173.193", + "2001:4860:4860::8888", + "2001:4860:4860::8844", + ], + bridgechainRepository: "http://www.repository.com/myorg/myrepo", + bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", + ports: { "@arkecosystem/core-api": 12345 }, +}; diff --git a/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/index.ts b/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/index.ts new file mode 100644 index 0000000000..4226e139da --- /dev/null +++ b/__tests__/unit/core-magistrate-transactions/handlers/__fixtures__/index.ts @@ -0,0 +1,3 @@ +import * as Assets from "./assets" + +export { Assets } diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts index 83e022df5e..93f79d77ee 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts @@ -1,39 +1,40 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BridgechainRegistrationBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BridgechainRegistrationBuilder } from "@packages/core-magistrate-crypto/src/builders"; import { IBridgechainRegistrationAsset, IBusinessRegistrationAsset, -} from "@arkecosystem/core-magistrate-crypto/src/interfaces"; +} from "@packages/core-magistrate-crypto/src/interfaces"; import { BridgechainAlreadyRegisteredError, BusinessIsResignedError, GenesisHashAlreadyRegisteredError, PortKeyMustBeValidPackageNameError, WalletIsNotBusinessError, -} from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; +} from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; import { BridgechainRegistrationTransactionHandler, BusinessRegistrationTransactionHandler, -} from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/dist/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +} from "@packages/core-magistrate-transactions/src/handlers"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -51,7 +52,8 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -85,26 +87,8 @@ describe("BusinessRegistration", () => { 2, ); - businessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; - bridgechainRegistrationAsset = { - name: "arkecosystem1", - seedNodes: [ - "74.125.224.71", - "74.125.224.72", - "64.233.173.193", - "2001:4860:4860::8888", - "2001:4860:4860::8844", - ], - genesisHash: "127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935", - bridgechainRepository: "http://www.repository.com/myorg/myrepo", - bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", - ports: { "@arkecosystem/core-api": 12345 }, - }; + businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); + bridgechainRegistrationAsset = _.cloneDeep(Assets.bridgechainRegistrationAsset); bridgechainRegistrationTransaction = new BridgechainRegistrationBuilder() .bridgechainRegistrationAsset(bridgechainRegistrationAsset) @@ -129,12 +113,10 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(bridgechainRegistrationTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(bridgechainRegistrationTransaction), + ]); await expect(handler.bootstrap()).toResolve(); expect( diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts index 437fcfb89e..627b21fb2b 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts @@ -1,40 +1,37 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BridgechainResignationBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; -import { - IBridgechainRegistrationAsset, - IBusinessRegistrationAsset, -} from "@arkecosystem/core-magistrate-crypto/src/interfaces"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BridgechainResignationBuilder } from "@packages/core-magistrate-crypto/src/builders"; import { BridgechainIsNotRegisteredByWalletError, BridgechainIsResignedError, BusinessIsResignedError, WalletIsNotBusinessError, -} from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; +} from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; import { BridgechainRegistrationTransactionHandler, BridgechainResignationTransactionHandler, BusinessRegistrationTransactionHandler, -} from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/dist/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +} from "@packages/core-magistrate-transactions/src/handlers"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool"; +import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -52,7 +49,7 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -75,20 +72,8 @@ beforeEach(() => { describe("BusinessRegistration", () => { let bridgechainResignationTransaction: Interfaces.ITransaction; let handler: TransactionHandler; - const businessRegistrationAsset: IBusinessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; - const bridgechainRegistrationAsset: IBridgechainRegistrationAsset = { - name: "arkecosystem1", - seedNodes: ["74.125.224.71", "74.125.224.72", "64.233.173.193", "2001:4860:4860::8888", "2001:4860:4860::8844"], - genesisHash: "127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935", - bridgechainRepository: "http://www.repository.com/myorg/myrepo", - bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", - ports: { "@arkecosystem/core-api": 12345 }, - }; + const businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); + const bridgechainRegistrationAsset = _.cloneDeep(Assets.bridgechainRegistrationAsset); beforeEach(async () => { handler = transactionHandlerRegistry.getRegisteredHandlerByType( @@ -135,12 +120,10 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(bridgechainResignationTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(bridgechainResignationTransaction), + ]); await expect(handler.bootstrap()).toResolve(); expect( diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts index 7a10c25a1a..9fa9bc59c9 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts @@ -1,44 +1,45 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; import { BridgechainRegistrationBuilder, BridgechainUpdateBuilder, -} from "@arkecosystem/core-magistrate-crypto/src/builders"; +} from "@packages/core-magistrate-crypto/src/builders"; import { IBridgechainRegistrationAsset, IBridgechainUpdateAsset, IBusinessRegistrationAsset, -} from "@arkecosystem/core-magistrate-crypto/src/interfaces"; +} from "@packages/core-magistrate-crypto/src/interfaces"; import { BridgechainIsNotRegisteredByWalletError, BridgechainIsResignedError, BusinessIsNotRegisteredError, BusinessIsResignedError, PortKeyMustBeValidPackageNameError, -} from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; +} from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; import { BridgechainRegistrationTransactionHandler, BridgechainUpdateTransactionHandler, BusinessRegistrationTransactionHandler, -} from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +} from "@packages/core-magistrate-transactions/src/handlers"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction, setMockTransactions } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import _ from "lodash"; +import { Assets } from "./__fixtures__"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -56,7 +57,7 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -93,39 +94,9 @@ describe("BusinessRegistration", () => { 2, ); - businessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; - bridgechainRegistrationAsset = { - name: "arkecosystem1", - seedNodes: [ - "74.125.224.71", - "74.125.224.72", - "64.233.173.193", - "2001:4860:4860::8888", - "2001:4860:4860::8844", - ], - genesisHash: "127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935", - bridgechainRepository: "http://www.repository.com/myorg/myrepo", - bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", - ports: { "@arkecosystem/core-api": 12345 }, - }; - bridgechainUpdateAsset = { - bridgechainId: bridgechainRegistrationAsset.genesisHash, - seedNodes: [ - "74.125.224.71", - "74.125.224.72", - "64.233.173.193", - "2001:4860:4860::8888", - "2001:4860:4860::8844", - ], - bridgechainRepository: "http://www.repository.com/myorg/myrepo", - bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo", - ports: { "@arkecosystem/core-api": 12345 }, - }; + businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); + bridgechainRegistrationAsset = _.cloneDeep(Assets.bridgechainRegistrationAsset); + bridgechainUpdateAsset = _.cloneDeep(Assets.bridgechainUpdateAsset); bridgechainRegistrationTransaction = new BridgechainRegistrationBuilder() .bridgechainRegistrationAsset(bridgechainRegistrationAsset) @@ -168,12 +139,11 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(bridgechainUpdateTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(bridgechainUpdateTransaction, 1), + ]); + await expect(handler.bootstrap()).toResolve(); const bridgechainUpdateAssetClone = Object.assign({}, bridgechainUpdateAsset); @@ -318,7 +288,7 @@ describe("BusinessRegistration", () => { "2001:4860:4860::8844", ], bridgechainRepository: "http://www.repository.com/myorg/myrepo/second", - bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo/sedond", + bridgechainAssetRepository: "http://www.repository.com/myorg/myassetrepo/second", ports: { "@arkecosystem/core-api": 54321 }, }; @@ -351,11 +321,10 @@ describe("BusinessRegistration", () => { ...bridgechainUpdateAssetClone, }); - // @ts-ignore - setMockTransactions([ - bridgechainRegistrationTransaction, - secondBridgechainUpdateTransaction, - bridgechainUpdateTransaction, + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(bridgechainRegistrationTransaction, 1), + Mapper.mapTransactionToModel(secondBridgechainUpdateTransaction, 2), + Mapper.mapTransactionToModel(bridgechainUpdateTransaction, 3), ]); await handler.revert(bridgechainUpdateTransaction, walletRepository); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts index bba020607e..37cadcc50b 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts @@ -1,29 +1,29 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BusinessRegistrationBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; -import { IBusinessRegistrationAsset } from "@arkecosystem/core-magistrate-crypto/src/interfaces"; -import { BusinessAlreadyRegisteredError } from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; -import { BusinessRegistrationTransactionHandler } from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { MagistrateIndex } from "@arkecosystem/core-magistrate-transactions/src/wallet-indexes"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/dist/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BusinessRegistrationBuilder } from "@packages/core-magistrate-crypto/src/builders"; +import { BusinessAlreadyRegisteredError } from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; +import { BusinessRegistrationTransactionHandler } from "@packages/core-magistrate-transactions/src/handlers"; +import { MagistrateIndex } from "@packages/core-magistrate-transactions/src/wallet-indexes"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool"; +import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -41,7 +41,7 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -62,12 +62,7 @@ beforeEach(() => { describe("BusinessRegistration", () => { let businessRegistrationTransaction: Interfaces.ITransaction; let handler: TransactionHandler; - const businessRegistrationAsset: IBusinessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; + const businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); beforeEach(async () => { handler = transactionHandlerRegistry.getRegisteredHandlerByType( @@ -94,12 +89,11 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(businessRegistrationTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(businessRegistrationTransaction), + ]); + await expect(handler.bootstrap()).toResolve(); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessRegistrationAsset); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts index 9e19083baa..3387f61d28 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts @@ -1,35 +1,35 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BusinessResignationBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; -import { IBusinessRegistrationAsset } from "@arkecosystem/core-magistrate-crypto/src/interfaces"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BusinessResignationBuilder } from "@packages/core-magistrate-crypto/src/builders"; import { BusinessIsNotRegisteredError, BusinessIsResignedError, -} from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; +} from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; import { BusinessRegistrationTransactionHandler, BusinessResignationTransactionHandler, -} from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { MagistrateIndex } from "@arkecosystem/core-magistrate-transactions/src/wallet-indexes"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/dist/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +} from "@packages/core-magistrate-transactions/src/handlers"; +import { MagistrateIndex } from "@packages/core-magistrate-transactions/src/wallet-indexes"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool"; +import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -47,7 +47,7 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -69,12 +69,7 @@ beforeEach(() => { describe("BusinessRegistration", () => { let businessResignationTransaction: Interfaces.ITransaction; let handler: TransactionHandler; - const businessRegistrationAsset: IBusinessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; + const businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); beforeEach(async () => { handler = transactionHandlerRegistry.getRegisteredHandlerByType( @@ -85,10 +80,7 @@ describe("BusinessRegistration", () => { 2, ); - businessResignationTransaction = new BusinessResignationBuilder() - .nonce("1") - .sign(passphrases[0]) - .build(); + businessResignationTransaction = new BusinessResignationBuilder().nonce("1").sign(passphrases[0]).build(); senderWallet.setAttribute("business.businessAsset", businessRegistrationAsset); @@ -107,12 +99,10 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(businessResignationTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(businessResignationTransaction), + ]); await expect(handler.bootstrap()).toResolve(); expect(senderWallet.getAttribute("business.resigned")).toBeTrue(); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts index 4c0d3aac8b..debdd4b5a9 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts @@ -1,34 +1,35 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BusinessRegistrationBuilder, BusinessUpdateBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; -import { IBusinessRegistrationAsset, IBusinessUpdateAsset } from "@arkecosystem/core-magistrate-crypto/src/interfaces"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BusinessRegistrationBuilder, BusinessUpdateBuilder } from "@packages/core-magistrate-crypto/src/builders"; +import { IBusinessUpdateAsset } from "@packages/core-magistrate-crypto/src/interfaces"; import { BusinessIsNotRegisteredError, BusinessIsResignedError, -} from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { MagistrateApplicationEvents } from "@arkecosystem/core-magistrate-transactions/src/events"; +} from "@packages/core-magistrate-transactions/src/errors"; +import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; import { BusinessRegistrationTransactionHandler, BusinessUpdateTransactionHandler, -} from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/dist/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +} from "@packages/core-magistrate-transactions/src/handlers"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool"; +import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction, setMockTransactions } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -46,7 +47,7 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); + Mocks.TransactionRepository.setTransactions([]); app = initApp(); @@ -69,19 +70,8 @@ describe("BusinessRegistration", () => { let businessUpdateTransaction: Interfaces.ITransaction; let handler: TransactionHandler; - const businessRegistrationAsset: IBusinessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; - - const businessUpdateAsset: IBusinessUpdateAsset = { - name: "DummyBusinessUpdated", - website: "https://www.dummy.example.updated", - vat: "UEX1234567890", - repository: "https://www.dummy.example/repo/updated", - }; + const businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); + const businessUpdateAsset = _.cloneDeep(Assets.businessUpdateAsset); beforeEach(async () => { handler = transactionHandlerRegistry.getRegisteredHandlerByType( @@ -115,12 +105,10 @@ describe("BusinessRegistration", () => { }); describe("bootstrap", () => { - afterEach(() => { - setMockBlock(null); - }); - it("should resolve", async () => { - setMockTransaction(businessUpdateTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(businessUpdateTransaction), + ]); await expect(handler.bootstrap()).toResolve(); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessUpdateAsset); @@ -200,11 +188,6 @@ describe("BusinessRegistration", () => { }); }); describe("revert", () => { - afterEach(() => { - // @ts-ignore - setMockTransactions([]); - }); - it("should be ok", async () => { const senderBalance = senderWallet.balance; @@ -218,7 +201,10 @@ describe("BusinessRegistration", () => { .sign(passphrases[0]) .build(); - setMockTransactions([businessRegistrationTransaction]); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(businessRegistrationTransaction), + ]); + await handler.revert(businessUpdateTransaction, walletRepository); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessRegistrationAsset); @@ -260,12 +246,12 @@ describe("BusinessRegistration", () => { ...secondBusinessUpdateAsset, }); - // @ts-ignore - setMockTransactions([ - businessRegistrationTransaction, - secondBusinessUpdateTransaction, - businessUpdateTransaction, + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(businessRegistrationTransaction), + Mapper.mapTransactionToModel(secondBusinessUpdateTransaction), + Mapper.mapTransactionToModel(businessUpdateTransaction), ]); + await handler.revert(secondBusinessUpdateTransaction, walletRepository); expect(senderWallet.getAttribute("business.businessAsset")).toEqual({ diff --git a/__tests__/unit/core-magistrate-transactions/handlers/general.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/general.test.ts index 786e80f7ef..4e08a02c9a 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/general.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/general.test.ts @@ -1,24 +1,24 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Enums, Transactions as MagistrateTransactions } from "@arkecosystem/core-magistrate-crypto"; -import { BusinessRegistrationBuilder } from "@arkecosystem/core-magistrate-crypto/src/builders"; -import { IBusinessRegistrationAsset } from "@arkecosystem/core-magistrate-crypto/src/interfaces"; -import { StaticFeeMismatchError } from "@arkecosystem/core-magistrate-transactions/src/errors"; -import { BusinessRegistrationTransactionHandler } from "@arkecosystem/core-magistrate-transactions/src/handlers"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { configManager } from "@arkecosystem/crypto/src/managers"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Enums, Transactions as MagistrateTransactions } from "@packages/core-magistrate-crypto"; +import { BusinessRegistrationBuilder } from "@packages/core-magistrate-crypto/src/builders"; +import { StaticFeeMismatchError } from "@packages/core-magistrate-transactions/src/errors"; +import { BusinessRegistrationTransactionHandler } from "@packages/core-magistrate-transactions/src/handlers"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { configManager } from "@packages/crypto/src/managers"; import { buildSenderWallet, initApp } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Assets } from "./__fixtures__"; +import _ from "lodash"; let app: Application; let senderWallet: Contracts.State.Wallet; @@ -36,8 +36,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); app.bind(Identifiers.TransactionHandler).to(BusinessRegistrationTransactionHandler); @@ -69,12 +67,7 @@ describe("BusinessRegistration", () => { const builder = new BusinessRegistrationBuilder(); - const businessRegistrationAsset: IBusinessRegistrationAsset = { - name: "DummyBusiness", - website: "https://www.dummy.example", - vat: "EX1234567890", - repository: "https://www.dummy.example/repo", - }; + const businessRegistrationAsset = _.cloneDeep(Assets.businessRegistrationAsset); businessRegistrationTransaction = builder .businessRegistrationAsset(businessRegistrationAsset) diff --git a/__tests__/unit/core-magistrate-transactions/mocks/block-repository.ts b/__tests__/unit/core-magistrate-transactions/mocks/block-repository.ts deleted file mode 100644 index d484a9de95..0000000000 --- a/__tests__/unit/core-magistrate-transactions/mocks/block-repository.ts +++ /dev/null @@ -1,14 +0,0 @@ -let mockBlock: any | null; - -export const setMockBlock = (block: any | null) => { - mockBlock = block; -}; - -export const blockRepository = { - getDelegatesForgedBlocks: async () => { - return mockBlock ? [mockBlock] : []; - }, - getLastForgedBlocks: async () => { - return mockBlock ? [mockBlock] : []; - }, -}; diff --git a/__tests__/unit/core-magistrate-transactions/mocks/transaction-repository.ts b/__tests__/unit/core-magistrate-transactions/mocks/transaction-repository.ts deleted file mode 100644 index 6b48eb1d39..0000000000 --- a/__tests__/unit/core-magistrate-transactions/mocks/transaction-repository.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { SearchFilter } from "@packages/core-database/src/repositories/search"; -import { ITransaction } from "@packages/crypto/src/interfaces"; - -let mockTransaction: ITransaction | null; -let mockTransactions: [ITransaction]; - -export const setMockTransaction = (transaction: ITransaction | null) => { - mockTransaction = transaction; -}; - -export const setMockTransactions = (transactions: [ITransaction]) => { - mockTransactions = transactions; -}; - -export const transactionRepository = { - findByIds: async () => { - return mockTransaction ? [mockTransaction.data] : []; - }, - findByType: async () => { - return mockTransaction ? [mockTransaction.data] : []; - }, - findReceivedTransactions() { - return mockTransaction ? [mockTransaction.data] : []; - }, - getOpenHtlcLocks() { - return mockTransaction ? [mockTransaction.data] : []; - }, - getClaimedHtlcLockBalances() { - return mockTransaction - ? [{ amount: mockTransaction.data.amount, recipientId: mockTransaction.data.recipientId }] - : []; - }, - getRefundedHtlcLockBalances() { - return mockTransaction - ? [{ amount: mockTransaction.data.amount, senderPublicKey: mockTransaction.data.senderPublicKey }] - : []; - }, - search(filter: SearchFilter): any { - const type = filter.criteria.find(x => x.field === "type"); - return { - // @ts-ignore - rows: mockTransactions.filter(x => x.data.type === type.value).map(x => x.data), - }; - }, -}; diff --git a/__tests__/unit/core-magistrate-transactions/service-provider.test.ts b/__tests__/unit/core-magistrate-transactions/service-provider.test.ts index 398e8f1f10..61f662631d 100644 --- a/__tests__/unit/core-magistrate-transactions/service-provider.test.ts +++ b/__tests__/unit/core-magistrate-transactions/service-provider.test.ts @@ -1,7 +1,7 @@ import "jest-extended"; -import { Application, Container } from "@arkecosystem/core-kernel"; -import { ServiceProvider } from "@arkecosystem/core-magistrate-transactions/src"; +import { Application, Container } from "@packages/core-kernel"; +import { ServiceProvider } from "@packages/core-magistrate-transactions/src"; let app: Application; diff --git a/__tests__/unit/core-test-framework/app/generators/core.test.ts b/__tests__/unit/core-test-framework/app/generators/core.test.ts index cbb0a58bcf..ed01e46c1f 100644 --- a/__tests__/unit/core-test-framework/app/generators/core.test.ts +++ b/__tests__/unit/core-test-framework/app/generators/core.test.ts @@ -6,7 +6,6 @@ import { CoreGenerator } from "@packages/core-test-framework/src/app/generators/ import { CoreConfigPaths } from "@packages/core-test-framework/src"; import { sandboxOptions } from "./__fixtures__/assets"; - afterEach(() => { jest.resetAllMocks(); }); @@ -43,6 +42,8 @@ describe("CoreGenerator", () => { let generator: CoreGenerator = new CoreGenerator(); - expect(() => { generator.generate() }).toThrowError(); + expect(() => { + generator.generate(); + }).toThrowError(); }); }); diff --git a/__tests__/unit/core-test-framework/app/generators/crypto.test.ts b/__tests__/unit/core-test-framework/app/generators/crypto.test.ts index 595dacf200..1f30ce5f97 100644 --- a/__tests__/unit/core-test-framework/app/generators/crypto.test.ts +++ b/__tests__/unit/core-test-framework/app/generators/crypto.test.ts @@ -78,6 +78,8 @@ describe("CryptoGenerator", () => { let generator: CryptoGenerator = new CryptoGenerator(); - expect(() => { generator.generate() }).toThrowError(); + expect(() => { + generator.generate(); + }).toThrowError(); }); }); diff --git a/__tests__/unit/core-test-framework/app/sandbox.test.ts b/__tests__/unit/core-test-framework/app/sandbox.test.ts index 7afe082200..4887579243 100644 --- a/__tests__/unit/core-test-framework/app/sandbox.test.ts +++ b/__tests__/unit/core-test-framework/app/sandbox.test.ts @@ -87,21 +87,20 @@ describe("Sandbox", () => { sandbox.restore(); - expect(() => { sandbox.app.get("test") }).toThrowError(); + expect(() => { + sandbox.app.get("test"); + }).toThrowError(); }); it("should register service provider", async () => { let sandbox = new Sandbox(); - sandbox - .app - .bind(Container.Identifiers.EventDispatcherService) - .toConstantValue({}); + sandbox.app.bind(Container.Identifiers.EventDispatcherService).toConstantValue({}); let serviceProviderOptions = { name: "@arkecosystem/core-state", path: resolve(__dirname, "../../../../packages/core-state"), - klass: CoreStateServiceProvider + klass: CoreStateServiceProvider, }; expect(sandbox.registerServiceProvider(serviceProviderOptions)).toBe(sandbox); diff --git a/__tests__/unit/core-test-framework/cli/console.test.ts b/__tests__/unit/core-test-framework/cli/console.test.ts index 5e79ad0914..a34c51e26e 100644 --- a/__tests__/unit/core-test-framework/cli/console.test.ts +++ b/__tests__/unit/core-test-framework/cli/console.test.ts @@ -31,11 +31,9 @@ export class Command extends Commands.Command { * @memberof Command */ public configure(): void { - this.definition - .setFlag("test", "The test message.", Joi.string().default("test")); + this.definition.setFlag("test", "The test message.", Joi.string().default("test")); - this.definition - .setArgument("test_arg", "The test argument.", Joi.string().default("test")); + this.definition.setArgument("test_arg", "The test argument.", Joi.string().default("test")); } /** diff --git a/__tests__/unit/core-test-framework/factories/factories/block.test.ts b/__tests__/unit/core-test-framework/factories/factories/block.test.ts index 0f674795fc..e1adf1d99b 100644 --- a/__tests__/unit/core-test-framework/factories/factories/block.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/block.test.ts @@ -5,7 +5,6 @@ import { Blocks, Interfaces } from "@packages/crypto"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Generators } from "@packages/core-test-framework/src"; - let factory: FactoryBuilder; beforeEach(() => { @@ -44,8 +43,8 @@ describe("BlockFactory", () => { const options = { config: { - genesisBlock: genesisBlock.data - } + genesisBlock: genesisBlock.data, + }, }; const entity: Blocks.Block = factory.get("Block").withOptions(options).make(); diff --git a/__tests__/unit/core-test-framework/factories/factories/identity.test.ts b/__tests__/unit/core-test-framework/factories/factories/identity.test.ts index f727109abb..9facebc0d8 100644 --- a/__tests__/unit/core-test-framework/factories/factories/identity.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/identity.test.ts @@ -37,10 +37,7 @@ describe("IdentityFactory", () => { }); it("should make an identity with a second passphrase", () => { - const entity: Identity = factory - .get("Identity") - .withStates("secondPassphrase") - .make(); + const entity: Identity = factory.get("Identity").withStates("secondPassphrase").make(); expect(entity).toContainAllKeys([ "keys", diff --git a/__tests__/unit/core-test-framework/factories/factories/round.test.ts b/__tests__/unit/core-test-framework/factories/factories/round.test.ts index 09cd8e26f9..9854941223 100644 --- a/__tests__/unit/core-test-framework/factories/factories/round.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/round.test.ts @@ -26,6 +26,6 @@ describe("RoundFactory", () => { expect(delegate.balance).toBeInstanceOf(Utils.BigNumber); expect(delegate.nonce).toBeInstanceOf(Utils.BigNumber); expect(delegate.isDelegate()).toBeTrue(); - }) + }); }); }); diff --git a/__tests__/unit/core-test-framework/factories/factories/transaction.test.ts b/__tests__/unit/core-test-framework/factories/factories/transaction.test.ts index bf273981bb..0432152581 100644 --- a/__tests__/unit/core-test-framework/factories/factories/transaction.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/transaction.test.ts @@ -30,10 +30,14 @@ describe("TransactionFactory", () => { timestamp: 1, senderPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), expiration: 2, - vendorField: "Dummy Field" + vendorField: "Dummy Field", }; - const transaction: Interfaces.ITransaction = factory.get("Transfer").withOptions(options).withStates("vendorField").make(); + const transaction: Interfaces.ITransaction = factory + .get("Transfer") + .withOptions(options) + .withStates("vendorField") + .make(); expect(transaction.data.signature).toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -53,10 +57,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Transfer") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Transfer").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -77,10 +78,7 @@ describe("TransactionFactory", () => { }); it("should sign it with multiple passphrases", () => { - const transaction: Interfaces.ITransaction = factory - .get("Transfer") - .withStates("sign", "multiSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Transfer").withStates("sign", "multiSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -100,10 +98,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("SecondSignature") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("SecondSignature").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -134,10 +129,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("DelegateRegistration") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("DelegateRegistration").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -168,10 +160,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("DelegateResignation") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("DelegateResignation").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -202,10 +191,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Vote") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Vote").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -214,10 +200,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a second passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Vote") - .withStates("sign", "secondSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Vote").withStates("sign", "secondSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).not.toBeUndefined(); @@ -226,10 +209,7 @@ describe("TransactionFactory", () => { }); it("should sign it with multiple passphrases", () => { - const transaction: Interfaces.ITransaction = factory - .get("Vote") - .withStates("sign", "multiSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Vote").withStates("sign", "multiSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -247,10 +227,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Unvote") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Unvote").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -259,10 +236,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a second passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Unvote") - .withStates("sign", "secondSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Unvote").withStates("sign", "secondSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).not.toBeUndefined(); @@ -271,10 +245,7 @@ describe("TransactionFactory", () => { }); it("should sign it with multiple passphrases", () => { - const transaction: Interfaces.ITransaction = factory - .get("Unvote") - .withStates("sign", "multiSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Unvote").withStates("sign", "multiSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -314,10 +285,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Ipfs") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Ipfs").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -326,10 +294,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a second passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("Ipfs") - .withStates("sign", "secondSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Ipfs").withStates("sign", "secondSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).not.toBeUndefined(); @@ -338,10 +303,7 @@ describe("TransactionFactory", () => { }); it("should sign it with multiple passphrases", () => { - const transaction: Interfaces.ITransaction = factory - .get("Ipfs") - .withStates("sign", "multiSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("Ipfs").withStates("sign", "multiSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -359,10 +321,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("HtlcLock") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("HtlcLock").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -383,10 +342,7 @@ describe("TransactionFactory", () => { }); it("should sign it with multiple passphrases", () => { - const transaction: Interfaces.ITransaction = factory - .get("HtlcLock") - .withStates("sign", "multiSign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("HtlcLock").withStates("sign", "multiSign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -404,10 +360,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("HtlcClaim") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("HtlcClaim").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -449,10 +402,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("HtlcRefund") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("HtlcRefund").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -494,10 +444,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("MultiPayment") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("MultiPayment").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -539,10 +486,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("BusinessRegistration") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("BusinessRegistration").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -584,10 +528,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("BusinessResignation") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("BusinessResignation").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -629,10 +570,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("BusinessUpdate") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("BusinessUpdate").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); @@ -764,10 +702,7 @@ describe("TransactionFactory", () => { }); it("should sign it with a single passphrase", () => { - const transaction: Interfaces.ITransaction = factory - .get("BridgechainUpdate") - .withStates("sign") - .make(); + const transaction: Interfaces.ITransaction = factory.get("BridgechainUpdate").withStates("sign").make(); expect(transaction.data.signature).not.toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); diff --git a/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts b/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts index 8ab00ce10a..e152fca084 100644 --- a/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts @@ -21,10 +21,7 @@ describe("WalletFactory", () => { }); it("should make a wallet with a second public key", () => { - const entity: Wallets.Wallet = factory - .get("Wallet") - .withStates("secondPublicKey") - .make(); + const entity: Wallets.Wallet = factory.get("Wallet").withStates("secondPublicKey").make(); expect(entity).toBeInstanceOf(Wallets.Wallet); expect(entity.address).toBeString(); diff --git a/__tests__/unit/core-test-framework/factories/factory-builder.test.ts b/__tests__/unit/core-test-framework/factories/factory-builder.test.ts index 594b994ea4..a486c2e389 100644 --- a/__tests__/unit/core-test-framework/factories/factory-builder.test.ts +++ b/__tests__/unit/core-test-framework/factories/factory-builder.test.ts @@ -32,12 +32,11 @@ describe("FactoryBuilder", () => { return entity; }); - expect( - factory - .get("Transaction") - .withStates("verified", "expired") - .make(), - ).toEqual({ valid: true, verified: true, expired: true }); + expect(factory.get("Transaction").withStates("verified", "expired").make()).toEqual({ + valid: true, + verified: true, + expired: true, + }); }); it("should create a new entity and merge the given attributes", () => { @@ -45,12 +44,7 @@ describe("FactoryBuilder", () => { valid: true, })); - expect( - factory - .get("Transaction") - .withAttributes({ another: "value" }) - .make(), - ).toEqual({ + expect(factory.get("Transaction").withAttributes({ another: "value" }).make()).toEqual({ valid: true, another: "value", }); @@ -80,12 +74,7 @@ describe("FactoryBuilder", () => { factory.get("Transaction").afterMakingState("invalid", ({ entity }) => (entity.hooked = true)); - expect( - factory - .get("Transaction") - .withStates("invalid") - .make(), - ).toEqual({ + expect(factory.get("Transaction").withStates("invalid").make()).toEqual({ valid: false, hooked: true, }); @@ -96,12 +85,7 @@ describe("FactoryBuilder", () => { valid: options.valid, })); - expect( - factory - .get("Transaction") - .withOptions({ valid: "no" }) - .make(), - ).toEqual({ + expect(factory.get("Transaction").withOptions({ valid: "no" }).make()).toEqual({ valid: "no", }); }); diff --git a/__tests__/unit/core-test-framework/factories/helpers.test.ts b/__tests__/unit/core-test-framework/factories/helpers.test.ts index c03d84ebe6..68656a7404 100644 --- a/__tests__/unit/core-test-framework/factories/helpers.test.ts +++ b/__tests__/unit/core-test-framework/factories/helpers.test.ts @@ -27,5 +27,5 @@ describe("Helpers", () => { expect(factory("BridgechainResignation")).toBeDefined(); expect(factory("BridgechainUpdate")).toBeDefined(); expect(factory("Wallet")).toBeDefined(); - }) + }); }); diff --git a/__tests__/unit/core-test-framework/internal/delegates.test.ts b/__tests__/unit/core-test-framework/internal/delegates.test.ts index 068b89ce5c..3f21e58106 100644 --- a/__tests__/unit/core-test-framework/internal/delegates.test.ts +++ b/__tests__/unit/core-test-framework/internal/delegates.test.ts @@ -1,6 +1,6 @@ import "jest-extended"; -import { delegates } from "@packages/core-test-framework/src/internal/delegates" +import { delegates } from "@packages/core-test-framework/src/internal/delegates"; describe("Delegates", () => { it("should create delegates from passphrases", async () => { diff --git a/__tests__/unit/core-test-framework/internal/signer.test.ts b/__tests__/unit/core-test-framework/internal/signer.test.ts index 1330294f87..ad96abd8cb 100644 --- a/__tests__/unit/core-test-framework/internal/signer.test.ts +++ b/__tests__/unit/core-test-framework/internal/signer.test.ts @@ -1,6 +1,6 @@ import "jest-extended"; -import { Signer } from "@packages/core-test-framework/src/internal/signer" +import { Signer } from "@packages/core-test-framework/src/internal/signer"; import { Generators } from "@packages/core-test-framework/src"; import { Identities, Interfaces } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; @@ -21,7 +21,7 @@ describe("Signer", () => { amount: "100", passphrase: passphrases[0], secondPassphrase: passphrases[1], - vendorField: "dummy" + vendorField: "dummy", }; let entity: Interfaces.ITransactionData = signer.makeTransfer(options); @@ -79,7 +79,9 @@ describe("Signer", () => { it("should make multi signature registration", async () => { let options = { min: 2, - participants: `${Identities.PublicKey.fromPassphrase(passphrases[0])},${Identities.PublicKey.fromPassphrase(passphrases[1])},${Identities.PublicKey.fromPassphrase(passphrases[2])}`, + participants: `${Identities.PublicKey.fromPassphrase(passphrases[0])},${Identities.PublicKey.fromPassphrase( + passphrases[1], + )},${Identities.PublicKey.fromPassphrase(passphrases[2])}`, passphrases: `${passphrases[0]},${passphrases[1]},${passphrases[2]}`, passphrase: passphrases[0], secondPassphrase: passphrases[1], @@ -115,12 +117,12 @@ describe("Signer", () => { payments: [ { recipientId: Identities.Address.fromPassphrase(passphrases[0]), - amount: "2" + amount: "2", }, { recipientId: Identities.Address.fromPassphrase(passphrases[1]), - amount: "3" - } + amount: "3", + }, ], passphrase: passphrases[0], secondPassphrase: passphrases[1], @@ -141,7 +143,7 @@ describe("Signer", () => { expiration: { type: HtlcLockExpirationType.EpochTimestamp, value: 5, - } + }, }, amount: "100", recipient: Identities.Address.fromPassphrase(passphrases[0]), @@ -180,7 +182,7 @@ describe("Signer", () => { let options = { htlcRefundFee: "5", refund: { - lockTransactionId: "12345" + lockTransactionId: "12345", }, passphrase: passphrases[0], secondPassphrase: passphrases[1], diff --git a/__tests__/unit/core-test-framework/matchers/api/block.test.ts b/__tests__/unit/core-test-framework/matchers/api/block.test.ts index 672f6a2de5..97ce5a748c 100644 --- a/__tests__/unit/core-test-framework/matchers/api/block.test.ts +++ b/__tests__/unit/core-test-framework/matchers/api/block.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/api/block" +import "@packages/core-test-framework/src/matchers/api/block"; import { Utils } from "@packages/crypto"; let block: any; @@ -9,27 +9,27 @@ beforeEach(() => { version: 0, timestamp: 8, height: 2, - previousBlockHex: 'b5ffa48d4b7e6937', - previousBlock: '13114381566690093367', + previousBlockHex: "b5ffa48d4b7e6937", + previousBlock: "13114381566690093367", transactions: [], numberOfTransactions: 0, totalAmount: Utils.BigNumber.make("0"), totalFee: Utils.BigNumber.make("0"), reward: Utils.BigNumber.make("0"), payloadLength: 0, - payloadHash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', - generatorPublicKey: '03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37', - blockSignature: '30450221009b3a032a50e79eca6f8d5851191e8edd2b36e6acf5f800632ddec5b968e6e09502200ee2cd4065386d77c3af255d416254a5946eeccf865d5413636a7b844b0bf581', - idHex: 'ca3fdcbcf44698b1', - id: '14573609623304444081', + payloadHash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + generatorPublicKey: "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37", + blockSignature: + "30450221009b3a032a50e79eca6f8d5851191e8edd2b36e6acf5f800632ddec5b968e6e09502200ee2cd4065386d77c3af255d416254a5946eeccf865d5413636a7b844b0bf581", + idHex: "ca3fdcbcf44698b1", + id: "14573609623304444081", createdAt: undefined, - updatedAt: undefined - } + updatedAt: undefined, + }; }); describe("Block", () => { describe("toBeValidBlock", () => { - // TODO: Check why we need createdAt and updatedAt fields it("should be valid block", async () => { expect(block).toBeValidBlock(); @@ -56,5 +56,5 @@ describe("Block", () => { it("should pass if block is valid", async () => { expect([block]).toBeValidArrayOfBlocks(); }); - }) + }); }); diff --git a/__tests__/unit/core-test-framework/matchers/api/peer.test.ts b/__tests__/unit/core-test-framework/matchers/api/peer.test.ts index ff77d0dbd1..e7117fc95d 100644 --- a/__tests__/unit/core-test-framework/matchers/api/peer.test.ts +++ b/__tests__/unit/core-test-framework/matchers/api/peer.test.ts @@ -1,17 +1,16 @@ -import "@packages/core-test-framework/src/matchers/api/peer" +import "@packages/core-test-framework/src/matchers/api/peer"; let peer: any; beforeEach(() => { peer = { ip: "127.0.0.1", - port: 4004 - } + port: 4004, + }; }); describe("Peer", () => { describe("toBeValidPeer", () => { - it("should be valid peer", async () => { expect(peer).toBeValidPeer(); }); @@ -35,5 +34,5 @@ describe("Peer", () => { it("should pass if peer is valid", async () => { expect([peer]).toBeValidArrayOfPeers(); }); - }) + }); }); diff --git a/__tests__/unit/core-test-framework/matchers/api/response.test.ts b/__tests__/unit/core-test-framework/matchers/api/response.test.ts index 2e6322a0ea..8309ee016f 100644 --- a/__tests__/unit/core-test-framework/matchers/api/response.test.ts +++ b/__tests__/unit/core-test-framework/matchers/api/response.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/api/response" +import "@packages/core-test-framework/src/matchers/api/response"; let response: any; @@ -7,23 +7,22 @@ beforeEach(() => { data: { test: "test", meta: { - "pageCount": 5, - "totalCount": 25, - "next": undefined, - "previous": undefined, - "self": undefined, - "first": undefined, - "last": undefined, - } + pageCount: 5, + totalCount: 25, + next: undefined, + previous: undefined, + self: undefined, + first: undefined, + last: undefined, + }, }, status: 200, - headers: {} - } + headers: {}, + }; }); describe("Response", () => { describe("toBeSuccessfulResponse", () => { - it("should be successful response", async () => { expect(response).toBeSuccessfulResponse(); }); diff --git a/__tests__/unit/core-test-framework/matchers/api/transaction.test.ts b/__tests__/unit/core-test-framework/matchers/api/transaction.test.ts index 8c7a1d7a49..75f00a8c6d 100644 --- a/__tests__/unit/core-test-framework/matchers/api/transaction.test.ts +++ b/__tests__/unit/core-test-framework/matchers/api/transaction.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/api/transaction" +import "@packages/core-test-framework/src/matchers/api/transaction"; let transaction: any; @@ -14,21 +14,21 @@ beforeEach(() => { senderId: "AagVinotZRfT5Xw57baQQBLvALdhAGeBfw", senderPublicKey: "03a550364f50f0710a7e4d27bf6542f37765b846923b84fab07a7c2f161106e73c", recipient: "AFrPtEmzu6wdVpa2CnRDEKGQQMWgq8nE9V", - signature: "3045022100f1a6076cf97823ce28f9c3de07806150e2c5280101bfdee841949f328f1b1b010220408c6c47caba417c55cbfea15d80da6da591176bab42eca9b20f49594e5924a8", + signature: + "3045022100f1a6076cf97823ce28f9c3de07806150e2c5280101bfdee841949f328f1b1b010220408c6c47caba417c55cbfea15d80da6da591176bab42eca9b20f49594e5924a8", confirmations: 25, timestamp: { epoch: 94756144, unix: 1584857344, - human: "2020-03-22T06:09:04.000Z" + human: "2020-03-22T06:09:04.000Z", }, asset: {}, - nonce: "54" - } + nonce: "54", + }; }); describe("Transaction", () => { describe("toBeApiTransaction", () => { - it("should be valid transaction", async () => { expect(transaction).toBeApiTransaction(); }); diff --git a/__tests__/unit/core-test-framework/matchers/blockchain/__fixtures__/assets.ts b/__tests__/unit/core-test-framework/matchers/blockchain/__fixtures__/assets.ts index 1593119fde..6c1c9976bb 100644 --- a/__tests__/unit/core-test-framework/matchers/blockchain/__fixtures__/assets.ts +++ b/__tests__/unit/core-test-framework/matchers/blockchain/__fixtures__/assets.ts @@ -15,16 +15,16 @@ export const machineConfig = { firstNestedState: { onEntry: ["runFirstNestedState"], on: { - LEAVE: "secondNestedState" - } + LEAVE: "secondNestedState", + }, }, secondNestedState: { onEntry: ["runSecondNestedState"], on: { - LEAVE: "stopped" - } - } - } - } - } + LEAVE: "stopped", + }, + }, + }, + }, + }, }; diff --git a/__tests__/unit/core-test-framework/matchers/blockchain/dispatch.test.ts b/__tests__/unit/core-test-framework/matchers/blockchain/dispatch.test.ts index eaa229cca8..e8c2dc20ae 100644 --- a/__tests__/unit/core-test-framework/matchers/blockchain/dispatch.test.ts +++ b/__tests__/unit/core-test-framework/matchers/blockchain/dispatch.test.ts @@ -1,17 +1,15 @@ -import "@packages/core-test-framework/src/matchers/blockchain/dispatch" +import "@packages/core-test-framework/src/matchers/blockchain/dispatch"; class Dispatcher { - dispatch(event: string): void { - } + dispatch(event: string): void {} - async transitionMethod (): Promise { + async transitionMethod(): Promise { this.dispatch("TEST"); } } describe("Dispatch", () => { describe("toDispatch", () => { - it("should be successful on valid event", async () => { let dispatcher = new Dispatcher(); diff --git a/__tests__/unit/core-test-framework/matchers/blockchain/execute-on-entry.test.ts b/__tests__/unit/core-test-framework/matchers/blockchain/execute-on-entry.test.ts index 7a50cb0135..751489b94d 100644 --- a/__tests__/unit/core-test-framework/matchers/blockchain/execute-on-entry.test.ts +++ b/__tests__/unit/core-test-framework/matchers/blockchain/execute-on-entry.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/blockchain/execute-on-entry" +import "@packages/core-test-framework/src/matchers/blockchain/execute-on-entry"; import { Machine } from "xstate"; import { machineConfig } from "./__fixtures__/assets"; diff --git a/__tests__/unit/core-test-framework/matchers/blockchain/transition.test.ts b/__tests__/unit/core-test-framework/matchers/blockchain/transition.test.ts index 67e07528d9..9aeaf22ae1 100644 --- a/__tests__/unit/core-test-framework/matchers/blockchain/transition.test.ts +++ b/__tests__/unit/core-test-framework/matchers/blockchain/transition.test.ts @@ -1,8 +1,7 @@ -import "@packages/core-test-framework/src/matchers/blockchain/transition" +import "@packages/core-test-framework/src/matchers/blockchain/transition"; import { Machine } from "xstate"; import { machineConfig } from "./__fixtures__/assets"; - let testMachine: any; beforeEach(() => { diff --git a/__tests__/unit/core-test-framework/matchers/fields/address.test.ts b/__tests__/unit/core-test-framework/matchers/fields/address.test.ts index 2b193ff016..d1f5e065f0 100644 --- a/__tests__/unit/core-test-framework/matchers/fields/address.test.ts +++ b/__tests__/unit/core-test-framework/matchers/fields/address.test.ts @@ -1,8 +1,7 @@ -import "@packages/core-test-framework/src/matchers/fields/address" +import "@packages/core-test-framework/src/matchers/fields/address"; import { Identities } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; - let address: string; beforeEach(() => { @@ -11,7 +10,6 @@ beforeEach(() => { describe("Address", () => { describe("toBeAddress", () => { - it("should be valid address", async () => { expect(address).toBeAddress(); }); diff --git a/__tests__/unit/core-test-framework/matchers/fields/public-key.test.ts b/__tests__/unit/core-test-framework/matchers/fields/public-key.test.ts index 049b791793..4eacf81e78 100644 --- a/__tests__/unit/core-test-framework/matchers/fields/public-key.test.ts +++ b/__tests__/unit/core-test-framework/matchers/fields/public-key.test.ts @@ -1,8 +1,7 @@ -import "@packages/core-test-framework/src/matchers/fields/public-key" +import "@packages/core-test-framework/src/matchers/fields/public-key"; import { Identities } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; - let publicKey: string; beforeEach(() => { @@ -11,7 +10,6 @@ beforeEach(() => { describe("PublicKey", () => { describe("toBePublicKey", () => { - it("should be valid public key", async () => { expect(publicKey).toBePublicKey(); }); diff --git a/__tests__/unit/core-test-framework/matchers/functional/accepted.test.ts b/__tests__/unit/core-test-framework/matchers/functional/accepted.test.ts index 549027eec5..297914281d 100644 --- a/__tests__/unit/core-test-framework/matchers/functional/accepted.test.ts +++ b/__tests__/unit/core-test-framework/matchers/functional/accepted.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/functional/accepted" +import "@packages/core-test-framework/src/matchers/functional/accepted"; import { Interfaces } from "@packages/crypto"; import got from "got"; @@ -14,8 +14,8 @@ beforeEach(() => { }, { id: "8fa3422ec3bf69cf4931b867dfc97185df891c4d45d0c2993014332daa69c596", - } - ] + }, + ]; }); describe("Accepted", () => { @@ -29,9 +29,9 @@ describe("Accepted", () => { data: { accept: [transactions[0].id], broadcast: [transactions[0].id], - } - }) - } + }, + }), + }; }); await expect(transactions[0]).toBeAccepted(); @@ -56,8 +56,8 @@ describe("Accepted", () => { return { body: JSON.stringify({ errors: undefined, - }) - } + }), + }; }); await expect(transactions).toBeAllAccepted(); @@ -82,8 +82,8 @@ describe("Accepted", () => { return { body: JSON.stringify({ errors: undefined, - }) - } + }), + }; }); await expect(transactions).toBeEachAccepted(); @@ -95,9 +95,9 @@ describe("Accepted", () => { let spyOnPost = jest.spyOn(got, "post").mockImplementation((url: any) => { return { body: JSON.stringify({ - errors: "Dummy error" - }) - } + errors: "Dummy error", + }), + }; }); await expect(transactions).not.toBeEachAccepted(); diff --git a/__tests__/unit/core-test-framework/matchers/functional/forged.test.ts b/__tests__/unit/core-test-framework/matchers/functional/forged.test.ts index 50f4fde308..9904bda280 100644 --- a/__tests__/unit/core-test-framework/matchers/functional/forged.test.ts +++ b/__tests__/unit/core-test-framework/matchers/functional/forged.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/functional/forged" +import "@packages/core-test-framework/src/matchers/functional/forged"; import { Interfaces } from "@packages/crypto"; import got from "got"; @@ -7,7 +7,7 @@ let block: Partial; beforeEach(() => { block = { id: "67219440c617ddaa7b7d102df462773c5b765ca1a1ba0827340f34ff32f495ef", - } + }; }); describe("Forged", () => { @@ -18,10 +18,10 @@ describe("Forged", () => { return { body: JSON.stringify({ data: { - id: block.id - } - }) - } + id: block.id, + }, + }), + }; }); await expect(block.id).toBeForged(); diff --git a/__tests__/unit/core-test-framework/matchers/functional/rejected.test.ts b/__tests__/unit/core-test-framework/matchers/functional/rejected.test.ts index 33d78fd5dc..ac579d6b04 100644 --- a/__tests__/unit/core-test-framework/matchers/functional/rejected.test.ts +++ b/__tests__/unit/core-test-framework/matchers/functional/rejected.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/functional/rejected" +import "@packages/core-test-framework/src/matchers/functional/rejected"; import { Interfaces } from "@packages/crypto"; import got from "got"; @@ -14,8 +14,8 @@ beforeEach(() => { }, { id: "8fa3422ec3bf69cf4931b867dfc97185df891c4d45d0c2993014332daa69c596", - } - ] + }, + ]; }); describe("Rejected", () => { @@ -27,10 +27,10 @@ describe("Rejected", () => { body: JSON.stringify({ errors: "Dummy error", data: { - invalid: [transactions[0].id] - } - }) - } + invalid: [transactions[0].id], + }, + }), + }; }); await expect(transactions[0]).toBeRejected(); @@ -52,17 +52,16 @@ describe("Rejected", () => { it("should pass", async () => { // @ts-ignore let spyOnPost = jest.spyOn(got, "post").mockImplementation(async (url: any, data: any) => { - let parsedData = JSON.parse(data.body); return { body: JSON.stringify({ errors: "Dummy error", data: { - invalid: parsedData.transactions.map(x => x.id) - } - }) - } + invalid: parsedData.transactions.map((x) => x.id), + }, + }), + }; }); await expect(transactions).toBeEachRejected(); @@ -72,16 +71,15 @@ describe("Rejected", () => { it("should pass due response without error", async () => { // @ts-ignore let spyOnPost = jest.spyOn(got, "post").mockImplementation(async (url: any, data: any) => { - let parsedData = JSON.parse(data.body); return { body: JSON.stringify({ data: { - invalid: parsedData.transactions.map(x => x.id) - } - }) - } + invalid: parsedData.transactions.map((x) => x.id), + }, + }), + }; }); await expect(transactions).not.toBeEachRejected(); diff --git a/__tests__/unit/core-test-framework/matchers/models/delegate.test.ts b/__tests__/unit/core-test-framework/matchers/models/delegate.test.ts index a4b2f9feb5..ccd7380bbf 100644 --- a/__tests__/unit/core-test-framework/matchers/models/delegate.test.ts +++ b/__tests__/unit/core-test-framework/matchers/models/delegate.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/models/delegate" +import "@packages/core-test-framework/src/matchers/models/delegate"; import { Identities } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; @@ -9,12 +9,11 @@ beforeEach(() => { address: Identities.Address.fromPassphrase(passphrases[0]), publicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), username: "dummy", - } + }; }); describe("Delegate", () => { describe("toBeDelegate", () => { - it("should be delegate", async () => { expect(delegate).toBeDelegate(); }); diff --git a/__tests__/unit/core-test-framework/matchers/models/transaction.test.ts b/__tests__/unit/core-test-framework/matchers/models/transaction.test.ts index e354f67576..4d5ff5430b 100644 --- a/__tests__/unit/core-test-framework/matchers/models/transaction.test.ts +++ b/__tests__/unit/core-test-framework/matchers/models/transaction.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/models/transaction" +import "@packages/core-test-framework/src/matchers/models/transaction"; let transaction: any; @@ -10,18 +10,18 @@ beforeEach(() => { // typeGroup: 1, // TODO: Why is not checked in matcher amount: "379990000000", fee: "10000000", - signature: "3045022100f1a6076cf97823ce28f9c3de07806150e2c5280101bfdee841949f328f1b1b010220408c6c47caba417c55cbfea15d80da6da591176bab42eca9b20f49594e5924a8", + signature: + "3045022100f1a6076cf97823ce28f9c3de07806150e2c5280101bfdee841949f328f1b1b010220408c6c47caba417c55cbfea15d80da6da591176bab42eca9b20f49594e5924a8", timestamp: { epoch: 94756144, unix: 1584857344, - human: "2020-03-22T06:09:04.000Z" - } - } + human: "2020-03-22T06:09:04.000Z", + }, + }; }); describe("Transaction", () => { describe("toBeTransaction", () => { - it("should be transaction", async () => { expect(transaction).toBeTransaction(); }); diff --git a/__tests__/unit/core-test-framework/matchers/models/wallet.test.ts b/__tests__/unit/core-test-framework/matchers/models/wallet.test.ts index 703576d416..e0a6f7495f 100644 --- a/__tests__/unit/core-test-framework/matchers/models/wallet.test.ts +++ b/__tests__/unit/core-test-framework/matchers/models/wallet.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/models/wallet" +import "@packages/core-test-framework/src/matchers/models/wallet"; import { Identities } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; @@ -8,12 +8,11 @@ beforeEach(() => { wallet = { address: Identities.Address.fromPassphrase(passphrases[0]), publicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), - } + }; }); describe("Wallet", () => { describe("toBeWallet", () => { - it("should be wallet", async () => { expect(wallet).toBeWallet(); }); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-registration.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-registration.test.ts index 679551d06a..c1b6a71f72 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-registration.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-registration.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/delegate-registration" +import "@packages/core-test-framework/src/matchers/transactions/types/delegate-registration"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Delegate Registration", () => { describe("toBeDelegateRegistrationType", () => { - it("should be delegate registrations type", async () => { const transaction: Interfaces.ITransaction = factory.get("DelegateRegistration").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-resignation.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-resignation.test.ts index bafc52e78e..fea8c4d25e 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-resignation.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/delegate-resignation.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/delegate-resignation" +import "@packages/core-test-framework/src/matchers/transactions/types/delegate-resignation"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Delegate Resignation", () => { describe("toBeDelegateResignationType", () => { - it("should be delegate resignation type", async () => { const transaction: Interfaces.ITransaction = factory.get("DelegateResignation").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/ipfs.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/ipfs.test.ts index 4ef236d3d1..17aae42aa6 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/ipfs.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/ipfs.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/ipfs" +import "@packages/core-test-framework/src/matchers/transactions/types/ipfs"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("IPFS", () => { describe("toBeIpfsType", () => { - it("should be ipfs type", async () => { const transaction: Interfaces.ITransaction = factory.get("Ipfs").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/multi-payment.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/multi-payment.test.ts index 568e1c05bb..1001e9a2b0 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/multi-payment.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/multi-payment.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/multi-payment" +import "@packages/core-test-framework/src/matchers/transactions/types/multi-payment"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Multi Payment", () => { describe("toBeMultiPaymentType", () => { - it("should be multi payment type", async () => { const transaction: Interfaces.ITransaction = factory.get("MultiPayment").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/multi-signature.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/multi-signature.test.ts index f112b184a5..c34a8a8ffd 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/multi-signature.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/multi-signature.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/multi-signature" +import "@packages/core-test-framework/src/matchers/transactions/types/multi-signature"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Multi Signature", () => { describe("toBeMultiSignatureType", () => { - it("should be multi signature type", async () => { const transaction: Interfaces.ITransaction = factory.get("MultiSignature").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/second-signature.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/second-signature.test.ts index d9de1f0b52..65c7e9c009 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/second-signature.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/second-signature.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/second-signature" +import "@packages/core-test-framework/src/matchers/transactions/types/second-signature"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Second Signature", () => { describe("toBeSecondSignatureType", () => { - it("should be second signature type", async () => { const transaction: Interfaces.ITransaction = factory.get("SecondSignature").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/transfer.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/transfer.test.ts index 8032a61749..f8c53dddaa 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/transfer.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/transfer.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/transfer" +import "@packages/core-test-framework/src/matchers/transactions/types/transfer"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Transfer", () => { describe("toBeTransferType", () => { - it("should be transfer type", async () => { const transaction: Interfaces.ITransaction = factory.get("Transfer").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/types/vote.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/types/vote.test.ts index 04a45235ef..ebb70aa99d 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/types/vote.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/types/vote.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/types/vote" +import "@packages/core-test-framework/src/matchers/transactions/types/vote"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -12,7 +12,6 @@ beforeEach(() => { describe("Vote", () => { describe("toBeVoteType", () => { - it("should be vote type", async () => { const transaction: Interfaces.ITransaction = factory.get("Vote").make(); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/valid-second-signature.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/valid-second-signature.test.ts index ee8f79b805..3611ca7c45 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/valid-second-signature.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/valid-second-signature.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/valid-second-signature" +import "@packages/core-test-framework/src/matchers/transactions/valid-second-signature"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Identities, Interfaces } from "@packages/crypto"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; @@ -9,17 +9,21 @@ beforeEach(() => { factory = new FactoryBuilder(); Factories.registerTransactionFactory(factory); - }); describe("Valid Second Signature", () => { describe("toHaveValidSecondSignature", () => { it("should be valid transaction - with second sign", async () => { - const transaction: Interfaces.ITransaction = factory.get("Transfer").withStates("sign", "secondSign").make(); + const transaction: Interfaces.ITransaction = factory + .get("Transfer") + .withStates("sign", "secondSign") + .make(); expect(transaction.data.signature).toBeDefined(); expect(transaction.data.secondSignature).toBeDefined(); - expect(transaction.data).toHaveValidSecondSignature({publicKey: Identities.PublicKey.fromPassphrase(passphrases[1])}); + expect(transaction.data).toHaveValidSecondSignature({ + publicKey: Identities.PublicKey.fromPassphrase(passphrases[1]), + }); }); it("should not be valid transaction - without sign", async () => { @@ -27,7 +31,9 @@ describe("Valid Second Signature", () => { expect(transaction.data.signature).toBeUndefined(); expect(transaction.data.secondSignature).toBeUndefined(); - expect(transaction.data).not.toHaveValidSecondSignature({publicKey: Identities.PublicKey.fromPassphrase(passphrases[1])}); + expect(transaction.data).not.toHaveValidSecondSignature({ + publicKey: Identities.PublicKey.fromPassphrase(passphrases[1]), + }); }); }); }); diff --git a/__tests__/unit/core-test-framework/matchers/transactions/valid.test.ts b/__tests__/unit/core-test-framework/matchers/transactions/valid.test.ts index 104150ff19..f4892f5981 100644 --- a/__tests__/unit/core-test-framework/matchers/transactions/valid.test.ts +++ b/__tests__/unit/core-test-framework/matchers/transactions/valid.test.ts @@ -1,4 +1,4 @@ -import "@packages/core-test-framework/src/matchers/transactions/valid" +import "@packages/core-test-framework/src/matchers/transactions/valid"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import { Interfaces } from "@packages/crypto"; @@ -8,12 +8,10 @@ beforeEach(() => { factory = new FactoryBuilder(); Factories.registerTransactionFactory(factory); - }); describe("Valid", () => { describe("toBeValidTransaction", () => { - it("should be valid transaction - with sign", async () => { const transaction: Interfaces.ITransaction = factory.get("Transfer").withStates("sign").make(); diff --git a/__tests__/unit/core-test-framework/mocks/block-repository.test.ts b/__tests__/unit/core-test-framework/mocks/block-repository.test.ts new file mode 100644 index 0000000000..8c3aeaa178 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/block-repository.test.ts @@ -0,0 +1,125 @@ +import "jest-extended"; + +import { BlockRepository } from "@packages/core-test-framework/src/mocks"; +import { Models } from "@packages/core-database"; +import { Identities } from "@packages/crypto"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; + +let block: Partial = { + id: "717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9", + version: 2, + timestamp: 123132, +}; + +let delegateForgedBlock: BlockRepository.DelegateForgedBlock = { + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + totalRewards: "2", + totalFees: "2", + totalProduced: 1, +}; + +let lastForgedBlock: BlockRepository.LastForgedBlock = { + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + id: "717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9", + height: "1", + timestamp: 1, +}; + +const clear = () => { + BlockRepository.setBlock(undefined); + BlockRepository.setBlocks([]); + BlockRepository.setDelegateForgedBlocks([]); + BlockRepository.setLastForgedBlocks([]); +}; + +describe("BlockRepository", () => { + describe("default values", () => { + it("findByIdOrHeight should return undefined", async () => { + await expect(BlockRepository.instance.findByIdOrHeight(1)).resolves.toBeUndefined(); + }); + + it("search should return empty paginated result", async () => { + await expect(BlockRepository.instance.search({ criteria: [] })).resolves.toEqual({ + rows: [], + count: 0, + countIsEstimate: false, + }); + }); + + it("searchByQuery should return empty paginated result", async () => { + await expect(BlockRepository.instance.searchByQuery({}, { offset: 0, limit: 100 })).resolves.toEqual({ + rows: [], + count: 0, + countIsEstimate: false, + }); + }); + + it("getDelegatesForgedBlocks should return empty array", async () => { + await expect(BlockRepository.instance.getDelegatesForgedBlocks()).resolves.toEqual([]); + }); + + it("getLastForgedBlocks should return empty array", async () => { + await expect(BlockRepository.instance.getLastForgedBlocks()).resolves.toEqual([]); + }); + }); + + describe("setBlock", () => { + beforeEach(() => { + clear(); + + BlockRepository.setBlock(block); + }); + + it("findByIdOrHeight should return mocked block", async () => { + await expect(BlockRepository.instance.findByIdOrHeight(1)).resolves.toEqual(block); + }); + }); + + describe("setBlocks", () => { + beforeEach(() => { + clear(); + + BlockRepository.setBlocks([block]); + }); + + it("search should return paginated result with mocked block", async () => { + await expect(BlockRepository.instance.search({ criteria: [] })).resolves.toEqual({ + rows: [block], + count: 1, + countIsEstimate: false, + }); + }); + + it("search should return paginated result with mocked block", async () => { + await expect(BlockRepository.instance.searchByQuery({}, { offset: 0, limit: 100 })).resolves.toEqual({ + rows: [block], + count: 1, + countIsEstimate: false, + }); + }); + }); + + describe("setDelegateForgedBlocks", () => { + beforeEach(() => { + clear(); + + BlockRepository.setDelegateForgedBlocks([delegateForgedBlock]); + }); + + it("getDelegatesForgedBlocks should return mocked block", async () => { + await expect(BlockRepository.instance.getDelegatesForgedBlocks()).resolves.toEqual([delegateForgedBlock]); + }); + }); + + describe("setLastForgedBlocks", () => { + beforeEach(() => { + clear(); + + BlockRepository.setLastForgedBlocks([lastForgedBlock]); + }); + + it("getLastForgedBlocks should return mocked block", async () => { + await expect(BlockRepository.instance.getLastForgedBlocks()).resolves.toEqual([lastForgedBlock]); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/blockchain.test.ts b/__tests__/unit/core-test-framework/mocks/blockchain.test.ts new file mode 100644 index 0000000000..c09b49c042 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/blockchain.test.ts @@ -0,0 +1,74 @@ +import "jest-extended"; + +import { Blockchain } from "@packages/core-test-framework/src/mocks"; +import { Interfaces } from "@packages/crypto"; + +let blockData: Partial = { + id: "717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9", + version: 2, + timestamp: 123132, + height: 5, +}; + +let block = { + data: blockData, +} as Interfaces.IBlock; + +const clear = () => { + Blockchain.setBlock(undefined); + Blockchain.setIsSynced(true); +}; + +describe("Blockchain", () => { + describe("default values", () => { + it("getLastBlock should return undefined", async () => { + expect(Blockchain.instance.getLastBlock()).toBeUndefined(); + }); + + it("getLastHeight should return undefined", async () => { + expect(Blockchain.instance.getLastHeight()).toBe(1); + }); + + it("isSynced should return undefined", async () => { + expect(Blockchain.instance.isSynced()).toBe(true); + }); + }); + + describe("setMockBlock", () => { + beforeEach(() => { + clear(); + + Blockchain.setBlock(block); + }); + + it("getLastBlock should return mocked block", async () => { + expect(Blockchain.instance.getLastBlock()).toEqual(block); + }); + + it("getLastHeight should return mocked block height", async () => { + expect(Blockchain.instance.getLastHeight()).toEqual(5); + }); + }); + + describe("setIsSynced", () => { + beforeEach(() => { + clear(); + + Blockchain.setIsSynced(false); + }); + + it("isSynced should return false", async () => { + expect(Blockchain.instance.isSynced()).toEqual(false); + }); + }); + + describe("other", () => { + beforeEach(() => { + clear(); + }); + + it("isSynced should return false", async () => { + expect(Blockchain.instance.removeBlocks(3)).toResolve(); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/network-monitor.test.ts b/__tests__/unit/core-test-framework/mocks/network-monitor.test.ts new file mode 100644 index 0000000000..c653318d52 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/network-monitor.test.ts @@ -0,0 +1,27 @@ +import "jest-extended"; + +import { NetworkMonitor } from "@packages/core-test-framework/src/mocks"; + +const clear = () => { + NetworkMonitor.setNetworkHeight(0); +}; + +describe("NetworkMonitor", () => { + describe("default values", () => { + it("getNetworkHeight should return 0", async () => { + expect(NetworkMonitor.instance.getNetworkHeight()).toBe(0); + }); + }); + + describe("setNetworkHeight", () => { + beforeEach(() => { + clear(); + + NetworkMonitor.setNetworkHeight(1); + }); + + it("getNetworkHeight should return 0", async () => { + expect(NetworkMonitor.instance.getNetworkHeight()).toEqual(1); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/peer-storage.test.ts b/__tests__/unit/core-test-framework/mocks/peer-storage.test.ts new file mode 100644 index 0000000000..967786e311 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/peer-storage.test.ts @@ -0,0 +1,60 @@ +import "jest-extended"; + +import { PeerStorage } from "@packages/core-test-framework/src/mocks"; +import { Contracts } from "@packages/core-kernel"; + +let peer: Partial = { + version: "2.6.0", + latency: 200, + ip: "127.0.0.1", + port: 4000, + ports: { + "127.0.0.1": 4000, + }, + state: { + height: 1, + forgingAllowed: false, + currentSlot: 1, + header: {}, + }, +}; + +const clear = () => { + PeerStorage.setPeers([]); +}; + +describe("PeerStorage", () => { + describe("default values", () => { + it("getPeers should return empty array", async () => { + expect(PeerStorage.instance.getPeers()).toEqual([]); + }); + + it("hasPeer should return false", async () => { + expect(PeerStorage.instance.hasPeer("127.0.0.1")).toBeFalse(); + }); + + it("getPeer should return undefined", async () => { + expect(PeerStorage.instance.getPeer("127.0.0.1")).toBeUndefined(); + }); + }); + + describe("setPeers", () => { + beforeEach(() => { + clear(); + + PeerStorage.setPeers([peer]); + }); + + it("getPeers should return mocked peer", async () => { + expect(PeerStorage.instance.getPeers()).toEqual([peer]); + }); + + it("getPeers should return true", async () => { + expect(PeerStorage.instance.hasPeer("127.0.0.1")).toBeTrue(); + }); + + it("getPeers should return first peer", async () => { + expect(PeerStorage.instance.getPeer("127.0.0.1")).toEqual(peer); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/query.test.ts b/__tests__/unit/core-test-framework/mocks/query.test.ts new file mode 100644 index 0000000000..a63f75266b --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/query.test.ts @@ -0,0 +1,58 @@ +import "jest-extended"; + +import { TransactionPoolQuery } from "@packages/core-test-framework/src/mocks"; +import { Interfaces } from "@packages/crypto"; + +let tranasction: Partial = { + id: "f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177", + type: 2, + typeGroup: 1, +}; + +const clear = () => { + TransactionPoolQuery.setTransactions([]); +}; + +describe("PeerStorage", () => { + describe("default values", () => { + it("getFromHighestPriority should return", async () => { + expect(TransactionPoolQuery.instance.getFromHighestPriority()).toEqual({ transactions: [] }); + }); + }); + + describe("setTransactions", () => { + beforeEach(() => { + clear(); + + TransactionPoolQuery.setTransactions([tranasction]); + }); + + it("getPeers should return mocked peer", async () => { + expect(TransactionPoolQuery.instance.getFromHighestPriority()).toEqual({ transactions: [tranasction] }); + }); + }); + + describe("CustomQueryIterable", () => { + let customQueryIterable: TransactionPoolQuery.CustomQueryIterable; + + beforeEach(() => { + customQueryIterable = new TransactionPoolQuery.CustomQueryIterable([tranasction]); + }); + + it("whereId should return all transactions", async () => { + expect(customQueryIterable.whereId(1)).toEqual({ transactions: [tranasction] }); + }); + + it("has should return true if transactions exist", async () => { + expect(customQueryIterable.has()).toBeTrue(); + }); + + it("first should return first transaction", async () => { + expect(customQueryIterable.first()).toEqual(tranasction); + }); + + it("should iterate", async () => { + expect(Array.from(customQueryIterable.whereId(1))).toEqual([tranasction]); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/round-repository.test.ts b/__tests__/unit/core-test-framework/mocks/round-repository.test.ts new file mode 100644 index 0000000000..14cc0fdf22 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/round-repository.test.ts @@ -0,0 +1,36 @@ +import "jest-extended"; + +import { RoundRepository } from "@packages/core-test-framework/src/mocks"; +import { Identities, Utils } from "@packages/crypto"; +import { Models } from "@packages/core-database"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; + +const round: Models.Round = { + publicKey: Identities.PublicKey.fromPassphrase(passphrases[1]), + round: Utils.BigNumber.make("12"), + balance: Utils.BigNumber.make("555"), +}; + +const clear = () => { + RoundRepository.setRounds([]); +}; + +describe("RoundRepository", () => { + describe("default values", () => { + it("findById should return empty array", async () => { + await expect(RoundRepository.instance.findById("1")).resolves.toEqual([]); + }); + }); + + describe("setRounds", () => { + beforeEach(() => { + clear(); + + RoundRepository.setRounds([round]); + }); + + it("findById should return mocked rounds", async () => { + await expect(RoundRepository.instance.findById("1")).resolves.toEqual([round]); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/service-provider-repository.test.ts b/__tests__/unit/core-test-framework/mocks/service-provider-repository.test.ts new file mode 100644 index 0000000000..6262026ced --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/service-provider-repository.test.ts @@ -0,0 +1,34 @@ +import "jest-extended"; + +import { ServiceProviderRepository } from "@packages/core-test-framework/src/mocks"; +import { ServiceProvider } from "@packages/core-webhooks"; +import { Sandbox } from "@packages/core-test-framework/src"; + +const clear = () => { + ServiceProviderRepository.setServiceProviders([]); +}; + +describe("ServiceProviderRepository", () => { + describe("default values", () => { + it("allLoadedProviders should return empty array", async () => { + expect(ServiceProviderRepository.instance.allLoadedProviders()).toEqual([]); + }); + }); + + describe("setRounds", () => { + let serviceProvider: ServiceProvider; + + beforeEach(() => { + clear(); + + let sandbox = new Sandbox(); + serviceProvider = sandbox.app.resolve(ServiceProvider); + + ServiceProviderRepository.setServiceProviders([serviceProvider]); + }); + + it("allLoadedProviders should return mocked service providers", async () => { + expect(ServiceProviderRepository.instance.allLoadedProviders()).toEqual([serviceProvider]); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/state-store.test.ts b/__tests__/unit/core-test-framework/mocks/state-store.test.ts new file mode 100644 index 0000000000..48a454ac68 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/state-store.test.ts @@ -0,0 +1,64 @@ +import "jest-extended"; + +import { StateStore } from "@packages/core-test-framework/src/mocks"; +import { Interfaces } from "@packages/crypto"; + +let blockData: Partial = { + id: "717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9", + version: 2, + timestamp: 123132, + height: 5, +}; + +let block = { + data: blockData, +} as Partial; + +const clear = () => { + StateStore.setBlock(undefined); + StateStore.setLastHeight(0); +}; + +describe("StateStore", () => { + describe("default values", () => { + it("getLastBlock should be undefined", async () => { + expect(StateStore.instance.getLastBlock()).toBeUndefined(); + }); + + it("getGenesisBlock should be undefined", async () => { + expect(StateStore.instance.getGenesisBlock()).toBeUndefined(); + }); + + it("getLastHeight should be 0", async () => { + expect(StateStore.instance.getLastHeight()).toBe(0); + }); + }); + + describe("setBlock", () => { + beforeEach(() => { + clear(); + + StateStore.setBlock(block); + }); + + it("getLastBlock should return mocked block", async () => { + expect(StateStore.instance.getLastBlock()).toEqual(block); + }); + + it("getGenesisBlock should return mocked block", async () => { + expect(StateStore.instance.getGenesisBlock()).toEqual(block); + }); + }); + + describe("setLastHeight", () => { + beforeEach(() => { + clear(); + + StateStore.setLastHeight(5); + }); + + it("getLastHeight should return mocked height", async () => { + expect(StateStore.instance.getLastHeight()).toEqual(5); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/transaction-pool-processor.test.ts b/__tests__/unit/core-test-framework/mocks/transaction-pool-processor.test.ts new file mode 100644 index 0000000000..710ee01403 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/transaction-pool-processor.test.ts @@ -0,0 +1,82 @@ +import "jest-extended"; + +import { TransactionPoolProcessor } from "@packages/core-test-framework/src/mocks"; + +let processorState = { + accept: ["f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177"], + broadcast: ["f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177"], + invalid: ["9f912ac02c06f6afc7ad80eca355ae5a31d175207885359a06da5a618dcdaa58"], + excess: ["e875dc95e9e404ba7ba93dd92f6c9190bc87d244fce8db3046d64705ce4680f9"], + errors: { + "0c79fe9faf214de92847baa322a9e991a49f6f6f0bc774927098c7feae627d77": { + type: "dummy error type", + message: "dummy error message", + }, + }, +}; + +const clear = () => { + TransactionPoolProcessor.setProcessorState({}); +}; + +describe("TransactionPoolProcessor", () => { + describe("default values", () => { + it("accept should be empty array", async () => { + expect(TransactionPoolProcessor.instance.accept).toEqual([]); + }); + + it("broadcast should be empty array", async () => { + expect(TransactionPoolProcessor.instance.broadcast).toEqual([]); + }); + + it("invalid should be empty array", async () => { + expect(TransactionPoolProcessor.instance.invalid).toEqual([]); + }); + + it("excess should be empty array", async () => { + expect(TransactionPoolProcessor.instance.excess).toEqual([]); + }); + + it("errors should be empty array", async () => { + expect(TransactionPoolProcessor.instance.errors).toBeUndefined(); + }); + }); + + describe("setProcessorState", () => { + beforeEach(() => { + clear(); + + TransactionPoolProcessor.setProcessorState(processorState); + }); + + it("accept should be mocked value", async () => { + expect(TransactionPoolProcessor.instance.accept).toEqual(processorState.accept); + }); + + it("broadcast should be mocked value", async () => { + expect(TransactionPoolProcessor.instance.broadcast).toEqual(processorState.broadcast); + }); + + it("invalid should be mocked value", async () => { + expect(TransactionPoolProcessor.instance.invalid).toEqual(processorState.invalid); + }); + + it("excess should be mocked value", async () => { + expect(TransactionPoolProcessor.instance.excess).toEqual(processorState.excess); + }); + + it("errors should be mocked value", async () => { + expect(TransactionPoolProcessor.instance.errors).toEqual(processorState.errors); + }); + }); + + describe("other", () => { + beforeEach(() => { + clear(); + }); + + it("process method should resolve", async () => { + await expect(TransactionPoolProcessor.instance.process([])).toResolve(); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/transaction-repository.test.ts b/__tests__/unit/core-test-framework/mocks/transaction-repository.test.ts new file mode 100644 index 0000000000..2788b0b2d1 --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/transaction-repository.test.ts @@ -0,0 +1,211 @@ +import "jest-extended"; + +import { TransactionRepository } from "@packages/core-test-framework/src/mocks"; +import { Models } from "@packages/core-database"; +import { SearchOperator } from "@packages/core-database/src/repositories/search"; + +let transaction: Partial = { + id: "0c79fe9faf214de92847baa322a9e991a49f6f6f0bc774927098c7feae627d77", + blockId: "6749a4b976e792817d32e1cf06d6b303badd2a5aff3086cc682349b9029290d5", + version: 2, + type: 2, + typeGroup: 1, + amount: BigInt("0"), + fee: BigInt("2500000000"), + senderPublicKey: "0272a9fb36e7a7d212aedfab53b2cdd48c8b620583d1927e03104122e6792482db", + recipientId: "DRwgqrfuuaPCy3AE8Sz1AjdrncKfHjePn5", +}; + +const feeStatistics: TransactionRepository.FeeStatistics = { + type: 1, + typeGroup: 1, + avg: "15", + min: "10", + max: "20", + sum: "500", +}; + +const clear = () => { + TransactionRepository.setTransaction(undefined); + TransactionRepository.setTransactions([]); + TransactionRepository.setFeeStatistics([]); +}; + +describe("TransactionRepository", () => { + describe("default values", () => { + it("findById should return empty search result", async () => { + await expect(TransactionRepository.instance.findById("dummy_id")).resolves.toBeUndefined(); + }); + + it("findByIdAndType should return empty search result", async () => { + await expect(TransactionRepository.instance.findByIdAndType(1, "dummy_id")).resolves.toBeUndefined(); + }); + + it("search should return empty search result", async () => { + await expect(TransactionRepository.instance.search({ criteria: [] })).resolves.toEqual({ + rows: [], + count: 0, + countIsEstimate: false, + }); + }); + + it("searchByQuery should return empty search result", async () => { + await expect(TransactionRepository.instance.searchByQuery({}, { limit: 100, offset: 0 })).resolves.toEqual({ + rows: [], + count: 0, + countIsEstimate: false, + }); + }); + + it("findByIds should return empty search result", async () => { + await expect(TransactionRepository.instance.findByIds(["dummy_id"])).resolves.toEqual([]); + }); + + it("findByType should return empty search result", async () => { + await expect(TransactionRepository.instance.findByType(1, 1)).resolves.toEqual([]); + }); + + it("findReceivedTransactions should return empty search result", async () => { + await expect(TransactionRepository.instance.findReceivedTransactions()).resolves.toEqual([]); + }); + + it("findByHtlcLocks should return empty search result", async () => { + await expect(TransactionRepository.instance.findByHtlcLocks(["dummy_id"])).resolves.toEqual([]); + }); + + it("getOpenHtlcLocks should return empty search result", async () => { + await expect(TransactionRepository.instance.getOpenHtlcLocks()).resolves.toEqual([]); + }); + + it("getClaimedHtlcLockBalances should return empty search result", async () => { + await expect(TransactionRepository.instance.getClaimedHtlcLockBalances()).resolves.toEqual([]); + }); + + it("getRefundedHtlcLockBalances should return empty search result", async () => { + await expect(TransactionRepository.instance.getRefundedHtlcLockBalances()).resolves.toEqual([]); + }); + + it("getFeeStatistics should return empty search result", async () => { + await expect(TransactionRepository.instance.getFeeStatistics(1)).resolves.toEqual([]); + }); + }); + + describe("setTransaction", () => { + beforeEach(() => { + clear(); + + TransactionRepository.setTransaction(transaction); + }); + + it("findByIdAndType should return mocked transaction", async () => { + await expect(TransactionRepository.instance.findByIdAndType(1, "dummy_id")).resolves.toEqual(transaction); + }); + + it("findById should return mocked transaction", async () => { + await expect(TransactionRepository.instance.findById("dummy_id")).resolves.toEqual(transaction); + }); + }); + + describe("setMockTransactions", () => { + beforeEach(() => { + clear(); + + TransactionRepository.setTransactions([transaction]); + }); + + it("search should return search result with transaction", async () => { + await expect(TransactionRepository.instance.search({ criteria: [] })).resolves.toEqual({ + rows: [transaction], + count: 1, + countIsEstimate: false, + }); + }); + + it("search should return search result with filtered transaction", async () => { + await expect( + TransactionRepository.instance.search({ + criteria: [{ field: "type", value: 2, operator: SearchOperator.Equal }], + }), + ).resolves.toEqual({ + rows: [transaction], + count: 1, + countIsEstimate: false, + }); + }); + + it("search should return empty search result with filtered transaction", async () => { + await expect( + TransactionRepository.instance.search({ + criteria: [{ field: "type", value: 3, operator: SearchOperator.Equal }], + }), + ).resolves.toEqual({ + rows: [], + count: 0, + countIsEstimate: false, + }); + }); + + it("searchByQuery should return empty search result", async () => { + await expect(TransactionRepository.instance.searchByQuery({}, { limit: 100, offset: 0 })).resolves.toEqual({ + rows: [transaction], + count: 1, + countIsEstimate: false, + }); + }); + + it("findByIds should return empty search result", async () => { + await expect(TransactionRepository.instance.findByIds(["dummy_id"])).resolves.toEqual([transaction]); + }); + + it("findByType should return empty search result", async () => { + await expect(TransactionRepository.instance.findByIds(["dummy_id"])).resolves.toEqual([transaction]); + }); + + it("findReceivedTransactions should return empty search result", async () => { + await expect(TransactionRepository.instance.findReceivedTransactions()).resolves.toEqual([ + { + recipientId: transaction.recipientId, + amount: transaction.amount!.toString(), + }, + ]); + }); + + it("findByHtlcLocks should return mocked transactions", async () => { + await expect(TransactionRepository.instance.findByHtlcLocks(["dummy_id"])).resolves.toEqual([transaction]); + }); + + it("getOpenHtlcLocks should return empty search result", async () => { + await expect(TransactionRepository.instance.getOpenHtlcLocks()).resolves.toEqual([transaction]); + }); + + it("getClaimedHtlcLockBalances should return empty search result", async () => { + await expect(TransactionRepository.instance.getClaimedHtlcLockBalances()).resolves.toEqual([ + { + recipientId: transaction.recipientId, + amount: transaction.amount!.toString(), + }, + ]); + }); + + it("getRefundedHtlcLockBalances should return empty search result", async () => { + await expect(TransactionRepository.instance.getRefundedHtlcLockBalances()).resolves.toEqual([ + { + senderPublicKey: transaction.senderPublicKey, + amount: transaction.amount!.toString(), + }, + ]); + }); + }); + + describe("setFeeStatistics", () => { + beforeEach(() => { + clear(); + + TransactionRepository.setFeeStatistics([feeStatistics]); + }); + + it("findByIdAndType should return mocked transaction", async () => { + await expect(TransactionRepository.instance.getFeeStatistics(1)).resolves.toEqual([feeStatistics]); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/mocks/wallet-repository.test.ts b/__tests__/unit/core-test-framework/mocks/wallet-repository.test.ts new file mode 100644 index 0000000000..ba91f4999b --- /dev/null +++ b/__tests__/unit/core-test-framework/mocks/wallet-repository.test.ts @@ -0,0 +1,28 @@ +import "jest-extended"; + +import { WalletRepository } from "@packages/core-test-framework/src/mocks"; +import { Utils } from "@packages/crypto"; + +const clear = () => { + WalletRepository.setNonce(Utils.BigNumber.make(1)); +}; + +describe("WalletRepository", () => { + describe("default values", () => { + it("getNonce should be 1", async () => { + expect(WalletRepository.instance.getNonce("dummy public key")).toEqual(Utils.BigNumber.make(1)); + }); + }); + + describe("setNonce", () => { + beforeEach(() => { + clear(); + + WalletRepository.setNonce(Utils.BigNumber.make(5)); + }); + + it("getNonce should return mocked value", async () => { + expect(WalletRepository.instance.getNonce("dummy public key")).toEqual(Utils.BigNumber.make(5)); + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/utils/__fixtures__/assets.ts b/__tests__/unit/core-test-framework/utils/__fixtures__/assets.ts index bcea0edb9f..b234bb59e6 100644 --- a/__tests__/unit/core-test-framework/utils/__fixtures__/assets.ts +++ b/__tests__/unit/core-test-framework/utils/__fixtures__/assets.ts @@ -9,7 +9,7 @@ export const paginationResponseMeta = { previous: null, self: "/transactions?transform=true&page=1&limit=100", first: "/transactions?transform=true&page=1&limit=100", - last: "/transactions?transform=true&page=39697&limit=100" + last: "/transactions?transform=true&page=39697&limit=100", }; export const transactionResponse = { @@ -23,19 +23,20 @@ export const transactionResponse = { sender: "DPTbJqyvrPgBmhs6UFqBwFdyx6jvorxHNL", senderPublicKey: "027ab77a71c903893c6264f0997455534c8a9dfd4608b3bc59d3fb6366f5475b0b", recipient: "DPTbJqyvrPgBmhs6UFqBwFdyx6jvorxHNL", - signature: "32cd7d0bc8d1ddd13ff485aa7e07c8b5f5608920be7b995fa1ed9a58ce76671bc70cc3560cb236eddb04f2b8039d70e508c6f0d0df5ddbb9f3a7c57d40ce117f", + signature: + "32cd7d0bc8d1ddd13ff485aa7e07c8b5f5608920be7b995fa1ed9a58ce76671bc70cc3560cb236eddb04f2b8039d70e508c6f0d0df5ddbb9f3a7c57d40ce117f", asset: { delegate: { - username: "test123456" - } + username: "test123456", + }, }, confirmations: 119869, timestamp: { epoch: 93911584, unix: 1584012784, - human: "2020-03-12T11:33:04.000Z" + human: "2020-03-12T11:33:04.000Z", }, - nonce: "1" + nonce: "1", }; export const blockResponse = { @@ -47,25 +48,26 @@ export const blockResponse = { reward: "200000000", fee: "0", total: "200000000", - amount: "0" + amount: "0", }, payload: { hash: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - length: 0 + length: 0, }, generator: { username: "pitbull", address: "APRt1h4Mrimbjuqm8deiYpuX1wpaM7dfNb", - publicKey: "03dff448e2fe490aff1665da1e217f39ac8b6715e5ecfdfec20bc150da70ef5153" + publicKey: "03dff448e2fe490aff1665da1e217f39ac8b6715e5ecfdfec20bc150da70ef5153", }, - signature: "304402203974f10df9c73626c861f1d5164d4b7f10e6a0337d0208474bb389a38cc173b00220552c0a65d090e0ddf258538fb5638fbd1c7a2bdea12e6da9b6d45d82266f44c5", + signature: + "304402203974f10df9c73626c861f1d5164d4b7f10e6a0337d0208474bb389a38cc173b00220552c0a65d090e0ddf258538fb5638fbd1c7a2bdea12e6da9b6d45d82266f44c5", confirmations: 0, transactions: 0, timestamp: { epoch: 94874968, unix: 1584976168, - human: "2020-03-23T15:09:28.000Z" - } + human: "2020-03-23T15:09:28.000Z", + }, }; export const delegateResponse = { @@ -83,18 +85,18 @@ export const delegateResponse = { timestamp: { epoch: 94874824, unix: 1584976024, - human: "2020-03-23T15:07:04.000Z" - } - } + human: "2020-03-23T15:07:04.000Z", + }, + }, }, production: { - approval: 2.09 + approval: 2.09, }, forged: { fees: "1173040419815", rewards: "41992600000000", - total: "43165640419815" - } + total: "43165640419815", + }, }; export const walletResponse = { @@ -103,11 +105,11 @@ export const walletResponse = { nonce: "122533", balance: "704589827182762", attributes: { - vote: "03a28aeb6b15e792f1753caae663a52f15ab642ae7cdee6fcdbc5416ffc0f4f702" + vote: "03a28aeb6b15e792f1753caae663a52f15ab642ae7cdee6fcdbc5416ffc0f4f702", }, isDelegate: false, isResigned: false, - vote: "03a28aeb6b15e792f1753caae663a52f15ab642ae7cdee6fcdbc5416ffc0f4f702" + vote: "03a28aeb6b15e792f1753caae663a52f15ab642ae7cdee6fcdbc5416ffc0f4f702", }; export const lockResponse = { @@ -119,11 +121,11 @@ export const lockResponse = { timestamp: { epoch: 93993832, unix: 1584095032, - human: "2020-03-13T10:23:52.000Z" + human: "2020-03-13T10:23:52.000Z", }, expirationType: 1, expirationValue: 1504193605, - isExpired: false + isExpired: false, }; export const htlcLockAsset = { @@ -131,7 +133,7 @@ export const htlcLockAsset = { expiration: { type: HtlcLockExpirationType.EpochTimestamp, value: 5, - } + }, }; export const htlcClaimAsset = { @@ -140,21 +142,21 @@ export const htlcClaimAsset = { }; export const htlcRefundAsset = { - lockTransactionId: "12345" + lockTransactionId: "12345", }; export const businessRegistrationAsset = { name: "DummyBusiness", website: "https://www.dummy.example", vat: "EX1234567890", - repository: "https://www.dummy.example/repo" + repository: "https://www.dummy.example/repo", }; export const businessUpdateAsset = { name: "DummyBusiness", website: "https://www.dummy.example", vat: "EX1234567890", - repository: "https://www.dummy.example/repo" + repository: "https://www.dummy.example/repo", }; export const bridgechainRegistrationAsset = { @@ -182,5 +184,5 @@ export const passphrasePairsAsset = [ { passphrase: passphrases[3], secondPassphrase: passphrases[4], - } + }, ]; diff --git a/__tests__/unit/core-test-framework/utils/api.test.ts b/__tests__/unit/core-test-framework/utils/api.test.ts index aaacb63bb7..49d34c7e30 100644 --- a/__tests__/unit/core-test-framework/utils/api.test.ts +++ b/__tests__/unit/core-test-framework/utils/api.test.ts @@ -12,7 +12,6 @@ import { walletResponse, } from "./__fixtures__/assets"; - let sandbox: Sandbox; let api: ApiHelpers; @@ -21,7 +20,7 @@ let mockResponse: any = '{test:"test"}'; let mockServer = { async inject(options: any) { return mockResponse; - } + }, }; beforeEach(async () => { @@ -36,7 +35,6 @@ afterEach(() => { jest.resetAllMocks(); }); - describe("ApiHelpers", () => { describe("request", () => { it("should return response", async () => { @@ -58,7 +56,7 @@ describe("ApiHelpers", () => { describe("expectJson", () => { it("should pass", async () => { let response = { - data: {} + data: {}, }; api.expectJson(response); @@ -68,7 +66,7 @@ describe("ApiHelpers", () => { describe("expectStatus", () => { it("should pass", async () => { let response = { - status: 200 + status: 200, }; api.expectStatus(response, 200); @@ -79,8 +77,8 @@ describe("ApiHelpers", () => { it("should pass", async () => { let response = { data: { - data: {} - } + data: {}, + }, }; api.expectResource(response); @@ -91,8 +89,8 @@ describe("ApiHelpers", () => { it("should pass", async () => { let response = { data: { - data: [] - } + data: [], + }, }; api.expectCollection(response); @@ -103,8 +101,8 @@ describe("ApiHelpers", () => { it("should pass", async () => { let response = { data: { - meta: paginationResponseMeta - } + meta: paginationResponseMeta, + }, }; api.expectPaginator(response); @@ -115,7 +113,7 @@ describe("ApiHelpers", () => { it("should pass", async () => { let response = { data: {}, - status: 200 + status: 200, }; api.expectSuccessful(response); @@ -130,7 +128,7 @@ describe("ApiHelpers", () => { error: "Dummy error", message: "Dummy error message", }, - status: 404 + status: 404, }; api.expectError(response); @@ -164,7 +162,6 @@ describe("ApiHelpers", () => { describe("expectWallet", () => { it("should pass", async () => { - // TODO: Check why is vote required api.expectWallet(walletResponse); diff --git a/__tests__/unit/core-test-framework/utils/generic.test.ts b/__tests__/unit/core-test-framework/utils/generic.test.ts index edaeecca87..097f36ae9c 100644 --- a/__tests__/unit/core-test-framework/utils/generic.test.ts +++ b/__tests__/unit/core-test-framework/utils/generic.test.ts @@ -4,7 +4,7 @@ import { performance } from "perf_hooks"; import { Generators, Sandbox } from "@packages/core-test-framework"; import { Identities, Interfaces, Managers, Utils } from "@packages/crypto"; import { Container } from "@packages/core-kernel"; -import { BlockchainMocks, StateStoreMocks, WalletRepositoryMocks } from "./mocks"; +import { Mocks } from "@packages/core-test-framework"; import { Block } from "@packages/core-database/src/models"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { @@ -20,34 +20,34 @@ let sandbox: Sandbox; let config = Generators.generateCryptoConfigRaw(); - beforeEach(async () => { - for(let item of config.milestones) { + for (let item of config.milestones) { item.blocktime = 2; } Managers.configManager.setConfig(config); sandbox = new Sandbox(); - sandbox.app.bind(Container.Identifiers.StateStore).toConstantValue(StateStoreMocks.stateStore); + sandbox.app.bind(Container.Identifiers.StateStore).toConstantValue(Mocks.StateStore.instance); - sandbox.app.bind(Container.Identifiers.BlockchainService).toConstantValue(BlockchainMocks.blockchain); + sandbox.app.bind(Container.Identifiers.BlockchainService).toConstantValue(Mocks.Blockchain.instance); - sandbox.app.bind(Container.Identifiers.WalletRepository).toConstantValue(WalletRepositoryMocks.walletRepository) + sandbox.app + .bind(Container.Identifiers.WalletRepository) + .toConstantValue(Mocks.WalletRepository.instance) .when(Container.Selectors.anyAncestorOrTargetTaggedFirst("state", "blockchain")); }); afterEach(() => { jest.resetAllMocks(); - StateStoreMocks.setLastHeight(0); + Mocks.StateStore.setLastHeight(0); - BlockchainMocks.setMockBlock(null); + Mocks.Blockchain.setBlock(undefined); - WalletRepositoryMocks.setMockNonce(Utils.BigNumber.make(1)); + Mocks.WalletRepository.setNonce(Utils.BigNumber.make(1)); }); - describe("Generic", () => { describe("snoozeForBlock", () => { it("should snooze", async () => { @@ -58,8 +58,8 @@ describe("Generic", () => { let end = performance.now(); // Test with 2 sec blocktime - expect(end-start).toBeGreaterThan(1900); - expect(end-start).toBeLessThan(4100); + expect(end - start).toBeGreaterThan(1900); + expect(end - start).toBeLessThan(4100); }); }); @@ -77,7 +77,7 @@ describe("Generic", () => { describe("getLastHeight", () => { it("should return last height", async () => { - StateStoreMocks.setLastHeight(5); + Mocks.StateStore.setLastHeight(5); expect(getLastHeight(sandbox.app)).toBe(5); }); @@ -85,9 +85,11 @@ describe("Generic", () => { describe("getSenderNonce", () => { it("should return sender nonce", async () => { - WalletRepositoryMocks.setMockNonce(Utils.BigNumber.make(5)); + Mocks.WalletRepository.setNonce(Utils.BigNumber.make(5)); - expect(getSenderNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual(Utils.BigNumber.make(5)); + expect(getSenderNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual( + Utils.BigNumber.make(5), + ); }); }); @@ -101,12 +103,12 @@ describe("Generic", () => { reward: Utils.BigNumber.make("100"), totalFee: Utils.BigNumber.make("200"), totalAmount: Utils.BigNumber.make("300"), - generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]) + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), }; - BlockchainMocks.setMockBlock({data: mockBlock} as Partial); + Mocks.Blockchain.setBlock({ data: mockBlock } as Partial); - let spyOnRemoveBlocks = jest.spyOn(BlockchainMocks.blockchain, "removeBlocks"); + let spyOnRemoveBlocks = jest.spyOn(Mocks.Blockchain.instance, "removeBlocks"); await expect(resetBlockchain(sandbox.app)).toResolve(); expect(spyOnRemoveBlocks).toHaveBeenCalled(); @@ -115,19 +117,25 @@ describe("Generic", () => { describe("getWalletNonce", () => { it("should return wallet nonce", async () => { - WalletRepositoryMocks.setMockNonce(Utils.BigNumber.make(5)); + Mocks.WalletRepository.setNonce(Utils.BigNumber.make(5)); - expect(getWalletNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual(Utils.BigNumber.make(5)); + expect(getWalletNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual( + Utils.BigNumber.make(5), + ); }); it("should return zero on error", async () => { - WalletRepositoryMocks.setMockNonce(Utils.BigNumber.make(5)); + Mocks.WalletRepository.setNonce(Utils.BigNumber.make(5)); - let spyOnGetNonce = jest.spyOn(WalletRepositoryMocks.walletRepository, "getNonce").mockImplementation((publicKey: string) => { - throw new Error(); - }); + let spyOnGetNonce = jest + .spyOn(Mocks.WalletRepository.instance, "getNonce") + .mockImplementation((publicKey: string) => { + throw new Error(); + }); - expect(getWalletNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual(Utils.BigNumber.make(0)); + expect(getWalletNonce(sandbox.app, Identities.PublicKey.fromPassphrase(passphrases[0]))).toEqual( + Utils.BigNumber.make(0), + ); expect(spyOnGetNonce).toHaveBeenCalled(); }); }); diff --git a/__tests__/unit/core-test-framework/utils/mapper.test.ts b/__tests__/unit/core-test-framework/utils/mapper.test.ts new file mode 100644 index 0000000000..cf5ee80fa7 --- /dev/null +++ b/__tests__/unit/core-test-framework/utils/mapper.test.ts @@ -0,0 +1,89 @@ +import "jest-extended"; + +import { mapTransactionToModel } from "@packages/core-test-framework/src/utils/mapper"; +import { Interfaces, Utils } from "@arkecosystem/crypto"; +import { Models } from "@arkecosystem/core-database"; + +let transaction: Interfaces.ITransaction; +let transactionModel: Models.Transaction; + +beforeEach(() => { + transaction = { + id: "f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177", + type: 2, + typeGroup: 1, + verified: true, + isVerified: true, + key: "123", + staticFee: Utils.BigNumber.make(5), + timestamp: 2000123, + data: { + id: "f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177", + version: 2, + network: 23, + type: 2, + typeGroup: 1, + timestamp: 2000123, + nonce: Utils.BigNumber.make(5), + senderPublicKey: "025805c82bb3ff7068e1b20da4ad2f89638e404950b0af7a0d2e23512b3701a21a", + fee: Utils.BigNumber.make(5), + amount: Utils.BigNumber.make(5), + recipientId: "D7RVC5iZqs3f8ETtHRL3REeVzsxrrBexcT", + signature: "efd9acefcc843123f7f518ebc34cd8a81ba536b9604d42eaf3bc84fa9df4e2f51e4596ca2671e5726e99bff83a85f98122512ec9ed5f9a3de97045d23f6c94f3", + blockId: "717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9", + sequence: 1, + asset: {} + }, + serialized: Buffer.from(""), + serialize: jest.fn(), + deserialize: jest.fn(), + verify: jest.fn(), + verifySchema: jest.fn(), + toJson: jest.fn(), + hasVendorField: jest.fn(), + }; + + transactionModel = { + id: 'f0880e972206698bf48e43325ec03045a3b2ab215b8f716a51742a909b718177', + version: 2, + blockId: '717093ac984e1a82a2de1fb334e92bda648547955417bc830d7825c515b5f2f9', + sequence: 0, + timestamp: 2000123, + nonce: Utils.BigNumber.make(5), + senderPublicKey: '025805c82bb3ff7068e1b20da4ad2f89638e404950b0af7a0d2e23512b3701a21a', + recipientId: 'D7RVC5iZqs3f8ETtHRL3REeVzsxrrBexcT', + type: 2, + typeGroup: 1, + vendorField: undefined, + amount: BigInt(Utils.BigNumber.make(5)), + fee: BigInt(Utils.BigNumber.make(5)), + serialized: Buffer.from(""), + asset: {} + }; +}); + +describe("Mapper", () => { + describe("mapTransactionToModel", () => { + it("should convert crypto transaction to database model", async () => { + expect(mapTransactionToModel(transaction)).toEqual(transactionModel) + }); + + it("should convert crypto transaction to database model without optional parameters", async () => { + delete transaction.data.version; + delete transaction.data.blockId; + delete transaction.data.nonce; + delete transaction.data.senderPublicKey; + delete transaction.data.recipientId; + delete transaction.data.typeGroup; + + transactionModel.version = 1; + transactionModel.blockId = ""; + transactionModel.nonce = Utils.BigNumber.make(1); + transactionModel.senderPublicKey = ""; + transactionModel.recipientId = ""; + transactionModel.typeGroup = 1; + + expect(mapTransactionToModel(transaction)).toEqual(transactionModel) + }); + }); +}); diff --git a/__tests__/unit/core-test-framework/utils/mocks/blockchain.ts b/__tests__/unit/core-test-framework/utils/mocks/blockchain.ts deleted file mode 100644 index 7b43c3a3c1..0000000000 --- a/__tests__/unit/core-test-framework/utils/mocks/blockchain.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { IBlock } from "@packages/crypto/src/interfaces"; -import { Blockchain } from "@packages/core-blockchain"; - -let mockBlock: Partial | null; -let mockIsSynced: boolean = true; - -export const setMockBlock = (block: Partial | null) => { - mockBlock = block; -}; - -export const setIsSynced = (isSynced: boolean) => { - mockIsSynced = isSynced; -}; - -export const blockchain: Partial = { - getLastBlock: () :IBlock => { - return mockBlock as IBlock; - }, - getLastHeight: (): number => { - return mockBlock?.data ? mockBlock.data.height : 1; - }, - isSynced: (block?: any): boolean => { - return mockIsSynced; - }, - removeBlocks: async (nblocks: number): Promise => { } -}; diff --git a/__tests__/unit/core-test-framework/utils/mocks/index.ts b/__tests__/unit/core-test-framework/utils/mocks/index.ts deleted file mode 100644 index 22657c10e5..0000000000 --- a/__tests__/unit/core-test-framework/utils/mocks/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as BlockchainMocks from './blockchain' -import * as StateStoreMocks from './state-store' -import * as WalletRepositoryMocks from './wallet-respository' - -export { - BlockchainMocks, - StateStoreMocks, - WalletRepositoryMocks -}; diff --git a/__tests__/unit/core-test-framework/utils/mocks/state-store.ts b/__tests__/unit/core-test-framework/utils/mocks/state-store.ts deleted file mode 100644 index 120331bc1e..0000000000 --- a/__tests__/unit/core-test-framework/utils/mocks/state-store.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { StateStore } from "@packages/core-state/src/stores/state"; -import { IBlock } from "@packages/crypto/src/interfaces"; - -let mockBlock: Partial | null; -let lastHeight: number; - -export const setMockBlock = (block: Partial | null) => { - mockBlock = block; -}; - -export const setLastHeight = (height: number) => { - lastHeight = height; -}; - -export const stateStore: Partial = { - getLastBlock: () :IBlock => { - return mockBlock as IBlock; - }, - getGenesisBlock: (): IBlock => { - return mockBlock as IBlock; - }, - getLastHeight(): number { - return lastHeight - } -}; diff --git a/__tests__/unit/core-test-framework/utils/mocks/wallet-respository.ts b/__tests__/unit/core-test-framework/utils/mocks/wallet-respository.ts deleted file mode 100644 index 57869a47e2..0000000000 --- a/__tests__/unit/core-test-framework/utils/mocks/wallet-respository.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { WalletRepository } from "@packages/core-state/src/wallets"; -import { Utils } from "@packages/crypto"; - -let mockNonce: Utils.BigNumber = Utils.BigNumber.make(1); - -export const setMockNonce = (nonce: Utils.BigNumber) => { - mockNonce = nonce; -}; - -export const walletRepository: Partial = { - getNonce: (publicKey: string): Utils.BigNumber => { - return mockNonce; - } -}; diff --git a/__tests__/unit/core-test-framework/utils/rest-client.test.ts b/__tests__/unit/core-test-framework/utils/rest-client.test.ts index 5ccc60016f..73b9c14890 100644 --- a/__tests__/unit/core-test-framework/utils/rest-client.test.ts +++ b/__tests__/unit/core-test-framework/utils/rest-client.test.ts @@ -9,12 +9,12 @@ let spyOnPost: jest.SpyInstance; beforeEach(() => { // @ts-ignore spyOnGet = jest.spyOn(Utils.http, "get").mockImplementation((url: string, opts?: any) => { - return {} + return {}; }); // @ts-ignore spyOnPost = jest.spyOn(Utils.http, "post").mockImplementation((url: string, opts?: any) => { - return {} + return {}; }); }); @@ -22,14 +22,13 @@ afterEach(() => { jest.resetAllMocks(); }); - describe("RestClient", () => { describe("get", () => { it("should resolve", async () => { let opts = { body: { - test: "test" - } + test: "test", + }, }; await expect(RestClient.get("blockchain", opts)).resolves.toEqual({}); @@ -40,7 +39,7 @@ describe("RestClient", () => { describe("post", () => { it("should resolve", async () => { let opts = { - test: "test" + test: "test", }; await expect(RestClient.post("blockchain", opts)).resolves.toEqual({}); diff --git a/__tests__/unit/core-test-framework/utils/transaction-factory.test.ts b/__tests__/unit/core-test-framework/utils/transaction-factory.test.ts index 8d47687284..86d35bdcc4 100644 --- a/__tests__/unit/core-test-framework/utils/transaction-factory.test.ts +++ b/__tests__/unit/core-test-framework/utils/transaction-factory.test.ts @@ -31,7 +31,6 @@ afterEach(() => { jest.resetAllMocks(); }); - describe("TransactionFactory", () => { describe("transfer", () => { it("should return transaction factory", async () => { @@ -129,7 +128,11 @@ describe("TransactionFactory", () => { describe("htlcLock", () => { it("should return transaction factory", async () => { - let entity = transactionFactory.htlcLock(htlcLockAsset, Identities.Address.fromPassphrase(passphrases[0]), 5); + let entity = transactionFactory.htlcLock( + htlcLockAsset, + Identities.Address.fromPassphrase(passphrases[0]), + 5, + ); expect(entity).toBeInstanceOf(TransactionFactory); }); @@ -203,7 +206,9 @@ describe("TransactionFactory", () => { describe("bridgechainResignation", () => { it("should return transaction factory", async () => { - let entity = transactionFactory.bridgechainResignation("127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935"); + let entity = transactionFactory.bridgechainResignation( + "127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935", + ); expect(entity).toBeInstanceOf(TransactionFactory); }); @@ -259,7 +264,9 @@ describe("TransactionFactory", () => { describe("withSenderPublicKey", () => { it("should return transaction factory", async () => { - let entity = transactionFactory.transfer().withSenderPublicKey(Identities.PublicKey.fromPassphrase(passphrases[0])); + let entity = transactionFactory + .transfer() + .withSenderPublicKey(Identities.PublicKey.fromPassphrase(passphrases[0])); expect(entity).toBeInstanceOf(TransactionFactory); }); @@ -347,7 +354,7 @@ describe("TransactionFactory", () => { expect(transaction.amount).toBeDefined(); expect(transaction.recipientId).toBeDefined(); expect(transaction.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - with default parameters", async () => { @@ -367,7 +374,7 @@ describe("TransactionFactory", () => { expect(transaction.amount).toBeDefined(); expect(transaction.recipientId).toBeDefined(); expect(transaction.vendorField).toBeDefined(); - }) + }); }); }); @@ -406,7 +413,7 @@ describe("TransactionFactory", () => { expect(item.data.amount).toBeDefined(); expect(item.data.recipientId).toBeDefined(); expect(item.data.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - with default parameters", async () => { @@ -426,7 +433,7 @@ describe("TransactionFactory", () => { expect(item.data.amount).toBeDefined(); expect(item.data.recipientId).toBeDefined(); expect(item.data.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - with passphrase pairs", async () => { @@ -446,12 +453,12 @@ describe("TransactionFactory", () => { expect(item.data.amount).toBeDefined(); expect(item.data.recipientId).toBeDefined(); expect(item.data.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - without network config", async () => { - - let entity = transactionFactory.transfer() + let entity = transactionFactory + .transfer() .withVersion(2) .withNetworkConfig(Generators.generateCryptoConfigRaw()) .build(); @@ -470,11 +477,12 @@ describe("TransactionFactory", () => { expect(item.data.amount).toBeDefined(); expect(item.data.recipientId).toBeDefined(); expect(item.data.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - with parameters", async () => { - let entity = transactionFactory.transfer() + let entity = transactionFactory + .transfer() .withVersion(2) .withFee(5) .withTimestamp(5) @@ -495,13 +503,11 @@ describe("TransactionFactory", () => { expect(item.data.amount).toBeDefined(); expect(item.data.recipientId).toBeDefined(); expect(item.data.vendorField).toBeDefined(); - }) + }); }); it("should return transactions - delegate registration", async () => { - let entity = transactionFactory.delegateRegistration() - .withVersion(2) - .build(); + let entity = transactionFactory.delegateRegistration().withVersion(2).build(); expect(entity).toBeArray(); expect(entity.length).toBeGreaterThan(0); @@ -515,7 +521,7 @@ describe("TransactionFactory", () => { expect(item.data.senderPublicKey).toBeDefined(); expect(item.data.nonce).toBeDefined(); expect(item.data.amount).toBeDefined(); - }) + }); }); it("should return transactions - multi signature", async () => { @@ -538,7 +544,7 @@ describe("TransactionFactory", () => { expect(item.data.nonce).toBeDefined(); expect(item.data.amount).toBeDefined(); expect(item.data.signatures).toBeArray(); - }) + }); }); it("should return transactions - with aip11 and verision", async () => { @@ -560,7 +566,7 @@ describe("TransactionFactory", () => { expect(item.data.senderPublicKey).toBeDefined(); expect(item.data.nonce).toBeUndefined(); expect(item.data.amount).toBeDefined(); - }) + }); }); }); }); diff --git a/__tests__/unit/core-transactions/handlers/__support__/app.ts b/__tests__/unit/core-transactions/handlers/__support__/app.ts index 2bb5e35661..57caa6961f 100644 --- a/__tests__/unit/core-transactions/handlers/__support__/app.ts +++ b/__tests__/unit/core-transactions/handlers/__support__/app.ts @@ -9,8 +9,7 @@ import { locksIndexer, publicKeysIndexer, usernamesIndexer, -} from "@packages/core-state/src/wallets/indexers/indexers" -; +} from "@packages/core-state/src/wallets/indexers/indexers"; import { FactoryBuilder } from "@packages/core-test-framework/src/factories"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { getWalletAttributeSet } from "@packages/core-test-framework/src/internal/wallet-attributes"; @@ -26,9 +25,7 @@ import { TransactionHandlerProvider } from "@packages/core-transactions/src/hand import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Identities, Utils } from "@packages/crypto"; import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; - -import { blockRepository } from "../mocks/block-repository"; -import { transactionRepository } from "../mocks/transaction-repository"; +import { Mocks } from "@packages/core-test-framework"; const logger = { notice: jest.fn(), @@ -81,9 +78,7 @@ export const initApp = (): Application => { ), ); - app.bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); app.get(Container.Identifiers.PluginConfiguration).set("maxTransactionAge", 500); app.get(Container.Identifiers.PluginConfiguration).set( @@ -95,17 +90,11 @@ export const initApp = (): Application => { 300, ); - app.bind(Container.Identifiers.StateStore) - .to(StateStore) - .inTransientScope(); + app.bind(Container.Identifiers.StateStore).to(StateStore).inTransientScope(); - app.bind(Identifiers.TransactionPoolMempool) - .to(Mempool) - .inSingletonScope(); + app.bind(Identifiers.TransactionPoolMempool).to(Mempool).inSingletonScope(); - app.bind(Identifiers.TransactionPoolQuery) - .to(Query) - .inSingletonScope(); + app.bind(Identifiers.TransactionPoolQuery).to(Query).inSingletonScope(); app.bind(Container.Identifiers.TransactionPoolCollator).to(Collator); app.bind(Container.Identifiers.TransactionPoolDynamicFeeMatcher).to(DynamicFeeMatcher); @@ -117,17 +106,13 @@ export const initApp = (): Application => { ); app.bind(Container.Identifiers.TransactionPoolSenderState).to(SenderState); - app.bind(Identifiers.WalletRepository) - .to(Wallets.WalletRepository) - .inSingletonScope(); + app.bind(Identifiers.WalletRepository).to(Wallets.WalletRepository).inSingletonScope(); - app.bind(Identifiers.EventDispatcherService) - .to(NullEventDispatcher) - .inSingletonScope(); + app.bind(Identifiers.EventDispatcherService).to(NullEventDispatcher).inSingletonScope(); - app.bind(Identifiers.BlockRepository).toConstantValue(blockRepository); + app.bind(Identifiers.BlockRepository).toConstantValue(Mocks.BlockRepository.instance); - app.bind(Identifiers.TransactionRepository).toConstantValue(transactionRepository); + app.bind(Identifiers.TransactionRepository).toConstantValue(Mocks.TransactionRepository.instance); app.bind(Identifiers.TransactionHandler).to(One.TransferTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.TransferTransactionHandler); @@ -146,12 +131,8 @@ export const initApp = (): Application => { app.bind(Identifiers.TransactionHandler).to(Two.HtlcClaimTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.HtlcRefundTransactionHandler); - app.bind(Identifiers.TransactionHandlerProvider) - .to(TransactionHandlerProvider) - .inSingletonScope(); - app.bind(Identifiers.TransactionHandlerRegistry) - .to(TransactionHandlerRegistry) - .inSingletonScope(); + app.bind(Identifiers.TransactionHandlerProvider).to(TransactionHandlerProvider).inSingletonScope(); + app.bind(Identifiers.TransactionHandlerRegistry).to(TransactionHandlerRegistry).inSingletonScope(); return app; }; diff --git a/__tests__/unit/core-transactions/handlers/handler-registry.test.ts b/__tests__/unit/core-transactions/handlers/handler-registry.test.ts index 88fb73030b..73101731cb 100644 --- a/__tests__/unit/core-transactions/handlers/handler-registry.test.ts +++ b/__tests__/unit/core-transactions/handlers/handler-registry.test.ts @@ -1,22 +1,22 @@ import "jest-extended"; -import { Contracts, Services } from "@arkecosystem/core-kernel"; -import { Application } from "@arkecosystem/core-kernel/src/application"; -import { Container, Identifiers } from "@arkecosystem/core-kernel/src/ioc"; +import { Contracts, Services } from "@packages/core-kernel"; +import { Application } from "@packages/core-kernel/src/application"; +import { Container, Identifiers } from "@packages/core-kernel/src/ioc"; import { DeactivatedTransactionHandlerError, InvalidTransactionTypeError, -} from "@arkecosystem/core-transactions/src/errors"; +} from "@packages/core-transactions/src/errors"; import { One, TransactionHandler, TransactionHandlerConstructor, Two, -} from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerProvider } from "@arkecosystem/core-transactions/src/handlers/handler-provider"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { TransactionSchema } from "@arkecosystem/crypto/src/transactions/types/schemas"; +} from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerProvider } from "@packages/core-transactions/src/handlers/handler-provider"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { TransactionSchema } from "@packages/crypto/src/transactions/types/schemas"; import ByteBuffer from "bytebuffer"; let app: Application; @@ -158,12 +158,8 @@ beforeEach(() => { app.bind(Identifiers.TransactionHandler).to(Two.HtlcClaimTransactionHandler); app.bind(Identifiers.TransactionHandler).to(Two.HtlcRefundTransactionHandler); - app.bind(Identifiers.TransactionHandlerProvider) - .to(TransactionHandlerProvider) - .inSingletonScope(); - app.bind(Identifiers.TransactionHandlerRegistry) - .to(TransactionHandlerRegistry) - .inSingletonScope(); + app.bind(Identifiers.TransactionHandlerProvider).to(TransactionHandlerProvider).inSingletonScope(); + app.bind(Identifiers.TransactionHandlerRegistry).to(TransactionHandlerRegistry).inSingletonScope(); Managers.configManager.getMilestone().aip11 = false; }); diff --git a/__tests__/unit/core-transactions/handlers/mocks/block-repository.ts b/__tests__/unit/core-transactions/handlers/mocks/block-repository.ts deleted file mode 100644 index d484a9de95..0000000000 --- a/__tests__/unit/core-transactions/handlers/mocks/block-repository.ts +++ /dev/null @@ -1,14 +0,0 @@ -let mockBlock: any | null; - -export const setMockBlock = (block: any | null) => { - mockBlock = block; -}; - -export const blockRepository = { - getDelegatesForgedBlocks: async () => { - return mockBlock ? [mockBlock] : []; - }, - getLastForgedBlocks: async () => { - return mockBlock ? [mockBlock] : []; - }, -}; diff --git a/__tests__/unit/core-transactions/handlers/mocks/transaction-repository.ts b/__tests__/unit/core-transactions/handlers/mocks/transaction-repository.ts deleted file mode 100644 index e45800ac09..0000000000 --- a/__tests__/unit/core-transactions/handlers/mocks/transaction-repository.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ITransaction } from "@packages/crypto/src/interfaces"; - -let mockTransaction: ITransaction | null; - -export const setMockTransaction = (transaction: ITransaction | null) => { - mockTransaction = transaction; -}; - -export const transactionRepository = { - findByIds: async () => { - return mockTransaction ? [mockTransaction.data] : []; - }, - findByType: async () => { - return mockTransaction ? [mockTransaction.data] : []; - }, - findReceivedTransactions() { - return mockTransaction ? [mockTransaction.data] : []; - }, - getOpenHtlcLocks() { - return mockTransaction ? [mockTransaction.data] : []; - }, - getClaimedHtlcLockBalances() { - return mockTransaction - ? [{ amount: mockTransaction.data.amount, recipientId: mockTransaction.data.recipientId }] - : []; - }, - getRefundedHtlcLockBalances() { - return mockTransaction - ? [{ amount: mockTransaction.data.amount, senderPublicKey: mockTransaction.data.senderPublicKey }] - : []; - }, -}; diff --git a/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts index f929915a41..602d2067a2 100644 --- a/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts @@ -1,22 +1,22 @@ import "jest-extended"; -import { Application, Contracts, Services } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { getWalletAttributeSet } from "@arkecosystem/core-test-framework/src/internal/wallet-attributes"; +import { Application, Contracts, Services } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { getWalletAttributeSet } from "@packages/core-test-framework/src/internal/wallet-attributes"; import { LegacyMultiSignatureError, MultiSignatureAlreadyRegisteredError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { IMultiSignatureAsset } from "@arkecosystem/crypto/src/interfaces"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -26,7 +26,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -49,8 +49,6 @@ beforeEach(() => { configManager.getMilestone().aip11 = false; Managers.configManager.getMilestone().aip11 = false; - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -70,6 +68,11 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + + describe("MultiSignatureRegistrationTransaction", () => { let multiSignatureTransaction: Interfaces.ITransaction; let recipientWallet: Wallets.Wallet; @@ -121,13 +124,17 @@ describe("MultiSignatureRegistrationTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(multiSignatureTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(multiSignatureTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); it("should throw when wallet has multi signature", async () => { senderWallet.setAttribute("multiSignature", multiSignatureAsset); - setMockTransaction(multiSignatureTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(multiSignatureTransaction), + ]); await expect(handler.bootstrap()).rejects.toThrow(MultiSignatureAlreadyRegisteredError); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts index 1a61a54c1c..e3931c6d1d 100644 --- a/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts @@ -1,25 +1,25 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { DelegateEvent } from "@arkecosystem/core-kernel/src/enums"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts } from "@packages/core-kernel"; +import { DelegateEvent } from "@packages/core-kernel/src/enums"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { InsufficientBalanceError, NotSupportedForMultiSignatureWalletError, WalletIsAlreadyDelegateError, WalletUsernameAlreadyRegisteredError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { IMultiSignatureAsset } from "@arkecosystem/crypto/src/interfaces"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -29,8 +29,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockBlock } from "../mocks/block-repository"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -50,8 +49,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -104,38 +101,51 @@ describe("DelegateRegistrationTransaction", () => { describe("bootstrap", () => { afterEach(() => { - setMockBlock(null); + Mocks.TransactionRepository.setTransactions([]); + Mocks.BlockRepository.setDelegateForgedBlocks([]); + Mocks.BlockRepository.setLastForgedBlocks([]); }); it("should resolve", async () => { - setMockTransaction(delegateRegistrationTransaction); + Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(delegateRegistrationTransaction)]); await expect(handler.bootstrap()).toResolve(); }); it("should resolve with bocks", async () => { - setMockTransaction(delegateRegistrationTransaction); - setMockBlock({ + Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(delegateRegistrationTransaction)]); + + Mocks.BlockRepository.setDelegateForgedBlocks([{ generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), totalRewards: "2", totalFees: "2", - totalProduced: "1", - id: "1", + totalProduced: 1, + }]); + + Mocks.BlockRepository.setLastForgedBlocks([{ + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + id: "123", height: "1", - timestamp: "1", - }); + timestamp: 1 + }]); + await expect(handler.bootstrap()).toResolve(); }); it("should resolve with bocks and genesis wallet", async () => { - setMockBlock({ + Mocks.BlockRepository.setDelegateForgedBlocks([{ generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), totalRewards: "2", totalFees: "2", - totalProduced: "1", - id: "1", + totalProduced: 1, + }]); + + Mocks.BlockRepository.setLastForgedBlocks([{ + generatorPublicKey: Identities.PublicKey.fromPassphrase(passphrases[0]), + id: "123", height: "1", - timestamp: "1", - }); + timestamp: 1 + }]); + await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts b/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts index 12577fab63..2127eef0d7 100644 --- a/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts @@ -1,25 +1,25 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { DelegateEvent } from "@arkecosystem/core-kernel/src/enums"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts } from "@packages/core-kernel"; +import { DelegateEvent } from "@packages/core-kernel/src/enums"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { InsufficientBalanceError, NotEnoughDelegatesError, VotedForResignedDelegateError, WalletAlreadyResignedError, WalletNotADelegateError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -29,7 +29,8 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; + let app: Application; let senderWallet: Wallets.Wallet; @@ -50,8 +51,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -139,7 +138,7 @@ describe("DelegateResignationTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(delegateResignationTransaction); + Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(delegateResignationTransaction)]); await expect(handler.bootstrap()).toResolve(); }); @@ -148,7 +147,7 @@ describe("DelegateResignationTransaction", () => { walletRepository.index(allDelegates[0]); - setMockTransaction(delegateResignationTransaction); + Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(delegateResignationTransaction)]); await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/general.test.ts b/__tests__/unit/core-transactions/handlers/two/general.test.ts index 73050d13fc..6ff78f87de 100644 --- a/__tests__/unit/core-transactions/handlers/two/general.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/general.test.ts @@ -1,12 +1,12 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { InsufficientBalanceError, InvalidMultiSignatureError, @@ -16,12 +16,12 @@ import { UnexpectedMultiSignatureError, UnexpectedNonceError, UnexpectedSecondSignatureError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { IMultiSignatureAsset } from "@arkecosystem/crypto/src/interfaces"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -31,7 +31,6 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; let app: Application; let senderWallet: Wallets.Wallet; @@ -52,8 +51,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -336,9 +333,7 @@ describe("General Tests", () => { await handler.apply(instance, walletRepository); expect(senderWallet.balance).toEqual( - Utils.BigNumber.make(senderBalance) - .minus(instance.data.amount) - .minus(instance.data.fee), + Utils.BigNumber.make(senderBalance).minus(instance.data.amount).minus(instance.data.fee), ); expect(recipientWallet.balance).toEqual(Utils.BigNumber.make(recipientBalance).plus(instance.data.amount)); @@ -403,9 +398,7 @@ describe("General Tests", () => { await handler.revert(instance, walletRepository); expect(senderWallet.balance).toEqual( - Utils.BigNumber.make(senderBalance) - .plus(instance.data.amount) - .plus(instance.data.fee), + Utils.BigNumber.make(senderBalance).plus(instance.data.amount).plus(instance.data.fee), ); expect(senderWallet.nonce.isZero()).toBeTrue(); diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts index d1e0f34dc5..cd4aa6e66e 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts @@ -1,22 +1,22 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { HtlcLockExpiredError, HtlcLockTransactionNotFoundError, HtlcSecretHashMismatchError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { htlcSecretHashHex, htlcSecretHex } from "../__fixtures__/htlc-secrets"; @@ -27,7 +27,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -43,9 +43,9 @@ const mockLastBlockData: Partial = { timestamp: Crypto.Sl const makeBlockHeightTimestamp = (heightRelativeToLastBlock = 2) => mockLastBlockData.height! + heightRelativeToLastBlock; -const makeExpiredTimestamp = type => +const makeExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! - 9 : makeBlockHeightTimestamp(-2); -const makeNotExpiredTimestamp = type => +const makeNotExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! + 999 : makeBlockHeightTimestamp(9); const mockGetLastBlock = jest.fn(); @@ -57,8 +57,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -78,8 +76,12 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("Htlc claim", () => { - describe.each([EpochTimestamp, BlockHeight])("Htlc claim - expiration type %i", expirationType => { + describe.each([EpochTimestamp, BlockHeight])("Htlc claim - expiration type %i", (expirationType) => { let htlcLockTransaction: Interfaces.ITransaction; let htlcClaimTransaction: Interfaces.ITransaction; let secondSignHtlcClaimTransaction: Interfaces.ITransaction; @@ -190,7 +192,9 @@ describe("Htlc claim", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); @@ -463,7 +467,10 @@ describe("Htlc claim", () => { handler.throwIfCannotBeApplied(htlcClaimTransaction, claimWallet, walletRepository), ).toResolve(); - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); + const balanceBefore = claimWallet.balance; await handler.apply(htlcClaimTransaction, walletRepository); @@ -484,7 +491,7 @@ describe("Htlc claim", () => { expect(foundLockWallet).toBeDefined(); // @ts-ignore expect(lockWallet.getAttribute("htlc.locks")[htlcLockTransaction.id]).toEqual({ - amount: htlcLockTransaction.data.amount, + amount: BigInt(htlcLockTransaction.data.amount), recipientId: htlcLockTransaction.data.recipientId, ...htlcLockTransaction.data.asset!.lock, }); @@ -500,7 +507,10 @@ describe("Htlc claim", () => { handler.throwIfCannotBeApplied(htlcClaimTransaction, claimWallet, walletRepository), ).toResolve(); - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); + const balanceBefore = claimWallet.balance; await handler.apply(htlcClaimTransaction, walletRepository); diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts index 08c145258a..6598eff20f 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts @@ -1,17 +1,17 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { HtlcLockExpiredError, InsufficientBalanceError } from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { HtlcLockExpiredError, InsufficientBalanceError } from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { htlcSecretHashHex } from "../__fixtures__/htlc-secrets"; @@ -22,7 +22,9 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; + +import { Mocks, Mapper } from "@packages/core-test-framework"; + let app: Application; let senderWallet: Wallets.Wallet; @@ -38,7 +40,7 @@ const mockLastBlockData: Partial = { timestamp: Crypto.Sl const makeBlockHeightTimestamp = (heightRelativeToLastBlock = 2) => mockLastBlockData.height! + heightRelativeToLastBlock; -const makeNotExpiredTimestamp = type => +const makeNotExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! + 999 : makeBlockHeightTimestamp(9); const mockGetLastBlock = jest.fn(); @@ -50,8 +52,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -71,8 +71,12 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("Htlc lock", () => { - describe.each([EpochTimestamp, BlockHeight])("Htlc lock - expiration type %i", expirationType => { + describe.each([EpochTimestamp, BlockHeight])("Htlc lock - expiration type %i", (expirationType) => { let htlcLockTransaction: Interfaces.ITransaction; let secondSignatureHtlcLockTransaction: Interfaces.ITransaction; let multiSignatureHtlcLockTransaction: Interfaces.ITransaction; @@ -140,14 +144,22 @@ describe("Htlc lock", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); it("should resolve with open transaction", async () => { + + let mockHtlcLockTransacton = Mapper.mapTransactionToModel(htlcLockTransaction); // @ts-ignore - htlcLockTransaction.data.open = true; - setMockTransaction(htlcLockTransaction); + mockHtlcLockTransacton.open = true; + + Mocks.TransactionRepository.setTransactions([ + mockHtlcLockTransacton + ]); + await expect(handler.bootstrap()).toResolve(); }); @@ -163,9 +175,14 @@ describe("Htlc lock", () => { .vendorField("dummy") .sign(passphrases[0]) .build(); + + let mockHtlcLockTransacton = Mapper.mapTransactionToModel(htlcLockTransaction); // @ts-ignore - htlcLockTransaction.data.open = true; - setMockTransaction(htlcLockTransaction); + mockHtlcLockTransacton.open = true; + + Mocks.TransactionRepository.setTransactions([ + mockHtlcLockTransacton + ]); await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts index 0229c39e13..e813a43410 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts @@ -1,18 +1,18 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; -import { HtlcLockNotExpiredError, HtlcLockTransactionNotFoundError } from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; +import { HtlcLockNotExpiredError, HtlcLockTransactionNotFoundError } from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { htlcSecretHashHex } from "../__fixtures__/htlc-secrets"; @@ -23,7 +23,8 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; + let app: Application; let senderWallet: Wallets.Wallet; @@ -39,9 +40,9 @@ const mockLastBlockData: Partial = { timestamp: Crypto.Sl const makeBlockHeightTimestamp = (heightRelativeToLastBlock = 2) => mockLastBlockData.height! + heightRelativeToLastBlock; -const makeExpiredTimestamp = type => +const makeExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! - 9 : makeBlockHeightTimestamp(-2); -const makeNotExpiredTimestamp = type => +const makeNotExpiredTimestamp = (type) => type === EpochTimestamp ? mockLastBlockData.timestamp! + 999 : makeBlockHeightTimestamp(9); const mockGetLastBlock = jest.fn(); @@ -53,8 +54,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -74,8 +73,12 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("Htlc refund", () => { - describe.each([EpochTimestamp, BlockHeight])("Htlc refund - expiration type %i", expirationType => { + describe.each([EpochTimestamp, BlockHeight])("Htlc refund - expiration type %i", (expirationType) => { const lockPassphrase = passphrases[2]; let htlcLockTransaction: Interfaces.ITransaction; let htlcRefundTransaction: Interfaces.ITransaction; @@ -171,7 +174,9 @@ describe("Htlc refund", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); @@ -420,7 +425,9 @@ describe("Htlc refund", () => { handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet, walletRepository), ).toResolve(); - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); const balanceBefore = lockWallet.balance; await handler.apply(htlcRefundTransaction, walletRepository); @@ -440,7 +447,7 @@ describe("Htlc refund", () => { ); expect(foundLockWallet).toBeDefined(); expect(foundLockWallet.getAttribute("htlc.locks")[htlcLockTransaction.id!]).toEqual({ - amount: htlcLockTransaction.data.amount, + amount: BigInt(htlcLockTransaction.data.amount), recipientId: htlcLockTransaction.data.recipientId, ...htlcLockTransaction.data.asset!.lock, }); @@ -456,7 +463,9 @@ describe("Htlc refund", () => { handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet, walletRepository), ).toResolve(); - setMockTransaction(htlcLockTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(htlcLockTransaction), + ]); const balanceBefore = lockWallet.balance; await handler.apply(htlcRefundTransaction, walletRepository); diff --git a/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts b/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts index 3e94011c1d..b0f71795ff 100644 --- a/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts @@ -1,17 +1,17 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { InsufficientBalanceError, IpfsHashAlreadyExists } from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { InsufficientBalanceError, IpfsHashAlreadyExists } from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { buildMultiSignatureWallet, @@ -20,7 +20,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -41,8 +41,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -62,6 +60,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("Ipfs", () => { let ipfsTransaction: Interfaces.ITransaction; let secondSignatureIpfsTransaction: Interfaces.ITransaction; @@ -102,7 +104,9 @@ describe("Ipfs", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(ipfsTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(ipfsTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts b/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts index 3107056d53..88514f84d9 100644 --- a/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts @@ -1,17 +1,17 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { InsufficientBalanceError } from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { InsufficientBalanceError } from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { buildMultiSignatureWallet, @@ -20,7 +20,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -41,8 +41,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -62,6 +60,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("MultiPaymentTransaction", () => { let multiPaymentTransaction: Interfaces.ITransaction; let secondSignatureMultiPaymentTransaction: Interfaces.ITransaction; @@ -117,7 +119,9 @@ describe("MultiPaymentTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(multiPaymentTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(multiPaymentTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); @@ -175,9 +179,7 @@ describe("MultiPaymentTransaction", () => { await handler.apply(multiPaymentTransaction, walletRepository); expect(senderWallet.balance).toEqual( - Utils.BigNumber.make(senderBalance) - .minus(totalPaymentsAmount) - .minus(multiPaymentTransaction.data.fee), + Utils.BigNumber.make(senderBalance).minus(totalPaymentsAmount).minus(multiPaymentTransaction.data.fee), ); for (const { recipientId, amount } of multiPaymentTransaction.data.asset!.payments!) { @@ -203,9 +205,7 @@ describe("MultiPaymentTransaction", () => { await handler.revert(multiPaymentTransaction, walletRepository); expect(senderWallet.balance).toEqual( - Utils.BigNumber.make(senderBalance) - .plus(totalPaymentsAmount) - .plus(multiPaymentTransaction.data.fee), + Utils.BigNumber.make(senderBalance).plus(totalPaymentsAmount).plus(multiPaymentTransaction.data.fee), ); expect(senderWallet.nonce.isZero()).toBeTrue(); diff --git a/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts index 228bbb808e..207baf5d56 100644 --- a/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts @@ -1,14 +1,14 @@ import "jest-extended"; -import { Application, Contracts, Services } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { getWalletAttributeSet } from "@arkecosystem/core-test-framework/src/internal/wallet-attributes"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts, Services } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { getWalletAttributeSet } from "@packages/core-test-framework/src/internal/wallet-attributes"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { InsufficientBalanceError, InvalidMultiSignatureError, @@ -16,16 +16,16 @@ import { MultiSignatureKeyCountMismatchError, MultiSignatureMinimumKeysError, UnexpectedMultiSignatureError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Errors, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { IMultiSignatureAsset, IMultiSignatureLegacyAsset } from "@arkecosystem/crypto/src/interfaces"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Errors, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { IMultiSignatureAsset, IMultiSignatureLegacyAsset } from "@packages/crypto/src/interfaces"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { buildRecipientWallet, buildSecondSignatureWallet, buildSenderWallet, initApp } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -45,8 +45,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -64,6 +62,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("MultiSignatureRegistrationTransaction", () => { let multiSignatureTransaction: Interfaces.ITransaction; let secondSignatureMultiSignatureTransaction: Interfaces.ITransaction; @@ -133,12 +135,16 @@ describe("MultiSignatureRegistrationTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(multiSignatureTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(multiSignatureTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); it("should throw if wallet is mutli signature", async () => { - setMockTransaction(multiSignatureTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(multiSignatureTransaction), + ]); recipientWallet.setAttribute("multiSignature", multiSignatureTransaction.data.asset!.multiSignature); await expect(handler.bootstrap()).rejects.toThrow(MultiSignatureAlreadyRegisteredError); }); diff --git a/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts index e5a3163adf..1a402a17ac 100644 --- a/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts @@ -1,23 +1,23 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { InsufficientBalanceError, NotSupportedForMultiSignatureWalletError, SecondSignatureAlreadyRegisteredError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { IMultiSignatureAsset } from "@arkecosystem/crypto/src/interfaces"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -27,7 +27,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -48,8 +48,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -69,6 +67,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("SecondSignatureRegistrationTransaction", () => { let secondSignatureTransaction: Interfaces.ITransaction; let handler: TransactionHandler; @@ -94,7 +96,9 @@ describe("SecondSignatureRegistrationTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(secondSignatureTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(secondSignatureTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/transfer.test.ts b/__tests__/unit/core-transactions/handlers/two/transfer.test.ts index c9f829f6fc..11b6898920 100644 --- a/__tests__/unit/core-transactions/handlers/two/transfer.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/transfer.test.ts @@ -1,22 +1,22 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { ColdWalletError, InsufficientBalanceError, SenderWalletMismatchError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { TransferTransactionHandler } from "@arkecosystem/core-transactions/src/handlers/one"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { TransferTransactionHandler } from "@packages/core-transactions/src/handlers/one"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -26,7 +26,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -47,8 +47,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -68,6 +66,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("TransferTransaction", () => { let transferTransaction: Interfaces.ITransaction; let secondSignatureTransferTransaction: Interfaces.ITransaction; @@ -117,7 +119,9 @@ describe("TransferTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(transferTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(transferTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/vote.test.ts b/__tests__/unit/core-transactions/handlers/two/vote.test.ts index 076041d165..38beb65ef6 100644 --- a/__tests__/unit/core-transactions/handlers/two/vote.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/vote.test.ts @@ -1,24 +1,24 @@ import "jest-extended"; -import { Application, Contracts } from "@arkecosystem/core-kernel"; -import { Identifiers } from "@arkecosystem/core-kernel/src/ioc"; -import { Wallets } from "@arkecosystem/core-state"; -import { StateStore } from "@arkecosystem/core-state/src/stores/state"; -import { Generators } from "@arkecosystem/core-test-framework/src"; -import { Factories, FactoryBuilder } from "@arkecosystem/core-test-framework/src/factories"; -import passphrases from "@arkecosystem/core-test-framework/src/internal/passphrases.json"; -import { Mempool } from "@arkecosystem/core-transaction-pool/src/mempool"; +import { Application, Contracts } from "@packages/core-kernel"; +import { Identifiers } from "@packages/core-kernel/src/ioc"; +import { Wallets } from "@packages/core-state"; +import { StateStore } from "@packages/core-state/src/stores/state"; +import { Generators } from "@packages/core-test-framework/src"; +import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; +import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; +import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { AlreadyVotedError, InsufficientBalanceError, NoVoteError, UnvoteMismatchError, VotedForNonDelegateError, -} from "@arkecosystem/core-transactions/src/errors"; -import { TransactionHandler } from "@arkecosystem/core-transactions/src/handlers"; -import { TransactionHandlerRegistry } from "@arkecosystem/core-transactions/src/handlers/handler-registry"; -import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; -import { BuilderFactory } from "@arkecosystem/crypto/src/transactions"; +} from "@packages/core-transactions/src/errors"; +import { TransactionHandler } from "@packages/core-transactions/src/handlers"; +import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; +import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; +import { BuilderFactory } from "@packages/crypto/src/transactions"; import { configManager } from "@packages/crypto/src/managers"; import { @@ -28,7 +28,7 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { setMockTransaction } from "../mocks/transaction-repository"; +import { Mocks, Mapper } from "@packages/core-test-framework"; let app: Application; let senderWallet: Wallets.Wallet; @@ -49,8 +49,6 @@ beforeEach(() => { configManager.setConfig(config); Managers.configManager.setConfig(config); - setMockTransaction(null); - app = initApp(); walletRepository = app.get(Identifiers.WalletRepository); @@ -70,6 +68,10 @@ beforeEach(() => { walletRepository.index(recipientWallet); }); +afterEach(() => { + Mocks.TransactionRepository.setTransactions([]); +}); + describe("VoteTransaction", () => { let voteTransaction: Interfaces.ITransaction; let secondSignatureVoteTransaction: Interfaces.ITransaction; @@ -148,26 +150,36 @@ describe("VoteTransaction", () => { describe("bootstrap", () => { it("should resolve", async () => { - setMockTransaction(voteTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(voteTransaction), + ]); await expect(handler.bootstrap()).toResolve(); - setMockTransaction(unvoteTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(unvoteTransaction), + ]); await expect(handler.bootstrap()).toResolve(); }); it("should throw on vote if wallet already voted", async () => { - setMockTransaction(voteTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(voteTransaction), + ]); senderWallet.setAttribute("vote", delegateWallet.publicKey); await expect(handler.bootstrap()).rejects.toThrow(AlreadyVotedError); }); it("should throw on unvote if wallet did not vote", async () => { - setMockTransaction(unvoteTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(unvoteTransaction), + ]); await expect(handler.bootstrap()).rejects.toThrow(NoVoteError); }); it("should throw on unvote if wallet vote is mismatch", async () => { - setMockTransaction(unvoteTransaction); + Mocks.TransactionRepository.setTransactions([ + Mapper.mapTransactionToModel(unvoteTransaction), + ]); senderWallet.setAttribute("vote", "no_a_public_key"); await expect(handler.bootstrap()).rejects.toThrow(UnvoteMismatchError); }); diff --git a/__tests__/unit/core-webhooks/__fixtures__/assets.ts b/__tests__/unit/core-webhooks/__fixtures__/assets.ts index 895339aa26..aeddb32948 100644 --- a/__tests__/unit/core-webhooks/__fixtures__/assets.ts +++ b/__tests__/unit/core-webhooks/__fixtures__/assets.ts @@ -13,5 +13,5 @@ export const dummyWebhook: Webhook = { // condition: "condition", // }, // ], - conditions: [] + conditions: [], }; diff --git a/__tests__/unit/core-webhooks/database.test.ts b/__tests__/unit/core-webhooks/database.test.ts index e373c789a4..de0da13f8e 100644 --- a/__tests__/unit/core-webhooks/database.test.ts +++ b/__tests__/unit/core-webhooks/database.test.ts @@ -29,9 +29,7 @@ beforeEach(() => { app = new Application(new Container()); app.bind("path.cache").toConstantValue(dirSync().name); - app.bind(Identifiers.Database) - .to(Database) - .inSingletonScope(); + app.bind(Identifiers.Database).to(Database).inSingletonScope(); database = app.get(Identifiers.Database); database.boot(); diff --git a/__tests__/unit/core-webhooks/listener.test.ts b/__tests__/unit/core-webhooks/listener.test.ts index 7eace47a02..ba8ddae389 100644 --- a/__tests__/unit/core-webhooks/listener.test.ts +++ b/__tests__/unit/core-webhooks/listener.test.ts @@ -5,11 +5,11 @@ import { Container, Utils } from "@packages/core-kernel"; import { Database } from "@packages/core-webhooks/src/database"; import { Identifiers } from "@packages/core-webhooks/src/identifiers"; import { Listener } from "@packages/core-webhooks/src/listener"; -import { Webhook } from "@arkecosystem/core-webhooks/src/interfaces"; +import { Webhook } from "@packages/core-webhooks/src/interfaces"; import { dirSync, setGracefulCleanup } from "tmp"; -import { HttpOptions, HttpResponse } from "@arkecosystem/core-kernel/src/utils"; +import { HttpOptions, HttpResponse } from "@packages/core-kernel/src/utils"; import { dummyWebhook } from "./__fixtures__/assets"; -import * as coditions from "@arkecosystem/core-webhooks/src/conditions"; +import * as coditions from "@packages/core-webhooks/src/conditions"; let app: Application; let database: Database; @@ -27,12 +27,9 @@ beforeEach(() => { app = new Application(new Container.Container()); app.bind("path.cache").toConstantValue(dirSync().name); - app.bind(Identifiers.Database) - .to(Database) - .inSingletonScope(); + app.bind(Identifiers.Database).to(Database).inSingletonScope(); - app.bind(Container.Identifiers.LogService) - .toConstantValue(logger); + app.bind(Container.Identifiers.LogService).toConstantValue(logger); database = app.get(Identifiers.Database); database.boot(); @@ -41,11 +38,13 @@ beforeEach(() => { webhook = Object.assign({}, dummyWebhook); - spyOnPost = jest.spyOn(Utils.http, "post").mockImplementation(async (url: string, opts?: HttpOptions | undefined) => { - return { - statusCode: 200 - } as HttpResponse; - }); + spyOnPost = jest + .spyOn(Utils.http, "post") + .mockImplementation(async (url: string, opts?: HttpOptions | undefined) => { + return { + statusCode: 200, + } as HttpResponse; + }); }); afterEach(() => { @@ -59,7 +58,7 @@ describe("Listener", () => { it("should broadcast to registered webhooks", async () => { database.create(webhook); - await listener.handle({ name: "event", data: "dummy_data"}); + await listener.handle({ name: "event", data: "dummy_data" }); expect(spyOnPost).toHaveBeenCalled(); expect(logger.debug).toHaveBeenCalled(); @@ -68,11 +67,13 @@ describe("Listener", () => { it("should log error if broadcast is not successful", async () => { database.create(webhook); - const spyOnPost = jest.spyOn(Utils.http, "post").mockImplementation(async (url: string, opts?: HttpOptions | undefined) => { - throw new Error(); - }); + const spyOnPost = jest + .spyOn(Utils.http, "post") + .mockImplementation(async (url: string, opts?: HttpOptions | undefined) => { + throw new Error(); + }); - await listener.handle({ name: "event", data: "dummy_data"}); + await listener.handle({ name: "event", data: "dummy_data" }); expect(spyOnPost).toHaveBeenCalled(); expect(logger.error).toHaveBeenCalled(); @@ -95,7 +96,7 @@ describe("Listener", () => { key: "test", value: 1, condition: "eq", - } + }, ]; database.create(webhook); @@ -110,7 +111,7 @@ describe("Listener", () => { key: "test", value: 1, condition: "eq", - } + }, ]; database.create(webhook); @@ -129,7 +130,7 @@ describe("Listener", () => { key: "test", value: 1, condition: "eq", - } + }, ]; database.create(webhook); diff --git a/__tests__/unit/core-webhooks/server/__support__/index.ts b/__tests__/unit/core-webhooks/server/__support__/index.ts index 898287e4de..19a4a0bfd3 100644 --- a/__tests__/unit/core-webhooks/server/__support__/index.ts +++ b/__tests__/unit/core-webhooks/server/__support__/index.ts @@ -9,24 +9,18 @@ import { dirSync } from "tmp"; export const initApp = (): Application => { const app: Application = new Application(new Container()); - app.bind(Identifiers.EventDispatcherService) - .to(MemoryEventDispatcher) - .inSingletonScope(); + app.bind(Identifiers.EventDispatcherService).to(MemoryEventDispatcher).inSingletonScope(); app.bind(Identifiers.LogService).toConstantValue({ info: jest.fn(), notice: jest.fn(), debug: jest.fn() }); app.bind("path.cache").toConstantValue(dirSync().name); - app.bind(WebhookIdentifiers.Database) - .to(Database) - .inSingletonScope(); + app.bind(WebhookIdentifiers.Database).to(Database).inSingletonScope(); app.get(WebhookIdentifiers.Database).boot(); // Setup Server... - app.bind(WebhookIdentifiers.Server) - .to(Server) - .inSingletonScope(); + app.bind(WebhookIdentifiers.Server).to(Server).inSingletonScope(); return app; }; diff --git a/__tests__/unit/core-webhooks/service-provider.test.ts b/__tests__/unit/core-webhooks/service-provider.test.ts index 56c6fca1e6..a1c9d985ab 100644 --- a/__tests__/unit/core-webhooks/service-provider.test.ts +++ b/__tests__/unit/core-webhooks/service-provider.test.ts @@ -3,7 +3,7 @@ import "jest-extended"; import { Identifiers, Server, ServiceProvider as CoreApiServiceProvider } from "@packages/core-api/src"; import { ServiceProvider } from "@packages/core-webhooks/src"; import { Application, Container, Providers } from "@packages/core-kernel"; -import { NullEventDispatcher } from "@arkecosystem/core-kernel/src/services/events/drivers/null"; +import { NullEventDispatcher } from "@packages/core-kernel/src/services/events/drivers/null"; import { defaults } from "@packages/core-api/src/defaults"; import { defaults as webhooksDefaults } from "@packages/core-webhooks/src/defaults"; import { dirSync, setGracefulCleanup } from "tmp"; @@ -19,58 +19,31 @@ const logger = { beforeEach(() => { app = new Application(new Container.Container()); - app - .bind(Container.Identifiers.PluginConfiguration) - .to(Providers.PluginConfiguration) - .inSingletonScope(); + app.bind(Container.Identifiers.PluginConfiguration).to(Providers.PluginConfiguration).inSingletonScope(); - app - .bind(Container.Identifiers.StateStore) - .toConstantValue({}); + app.bind(Container.Identifiers.StateStore).toConstantValue({}); - app - .bind(Container.Identifiers.BlockchainService) - .toConstantValue({}); + app.bind(Container.Identifiers.BlockchainService).toConstantValue({}); - app - .bind(Container.Identifiers.BlockRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.BlockRepository).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionRepository).toConstantValue({}); - app - .bind(Container.Identifiers.WalletRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.WalletRepository).toConstantValue({}); - app - .bind(Container.Identifiers.PeerNetworkMonitor) - .toConstantValue({}); + app.bind(Container.Identifiers.PeerNetworkMonitor).toConstantValue({}); - app - .bind(Container.Identifiers.PeerStorage) - .toConstantValue({}); + app.bind(Container.Identifiers.PeerStorage).toConstantValue({}); - app - .bind(Container.Identifiers.RoundRepository) - .toConstantValue({}); + app.bind(Container.Identifiers.RoundRepository).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionPoolQuery) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolQuery).toConstantValue({}); - app - .bind(Container.Identifiers.TransactionPoolProcessorFactory) - .toConstantValue({}); + app.bind(Container.Identifiers.TransactionPoolProcessorFactory).toConstantValue({}); - app - .bind(Container.Identifiers.EventDispatcherService) - .to(NullEventDispatcher); + app.bind(Container.Identifiers.EventDispatcherService).to(NullEventDispatcher); - app - .bind(Container.Identifiers.LogService) - .toConstantValue(logger); + app.bind(Container.Identifiers.LogService).toConstantValue(logger); app.bind("path.cache").toConstantValue(dirSync().name); }); @@ -79,7 +52,7 @@ afterAll(() => setGracefulCleanup()); describe("ServiceProvider", () => { let serviceProvider: ServiceProvider; - let coreApiServiceProvider: CoreApiServiceProvider + let coreApiServiceProvider: CoreApiServiceProvider; beforeEach(async () => { coreApiServiceProvider = app.resolve(CoreApiServiceProvider); @@ -155,5 +128,5 @@ describe("ServiceProvider", () => { it("should not be required", async () => { await expect(serviceProvider.required()).resolves.toBeFalse(); - }) + }); }); diff --git a/packages/core-test-framework/src/index.ts b/packages/core-test-framework/src/index.ts index ed3fc287f2..f2b8c1b9fe 100644 --- a/packages/core-test-framework/src/index.ts +++ b/packages/core-test-framework/src/index.ts @@ -10,5 +10,6 @@ import * as Generators from "./app/generators"; import * as Factories from "./factories"; // Utilities for common tasks like sending HTTP requests or altering wallets export * from "./utils"; // todo: export as Utils +import * as Mocks from "./mocks"; // todo: export as Utils -export { Factories, Generators }; +export { Factories, Generators, Mocks }; diff --git a/packages/core-test-framework/src/mocks/block-repository.ts b/packages/core-test-framework/src/mocks/block-repository.ts new file mode 100644 index 0000000000..a98d440f9f --- /dev/null +++ b/packages/core-test-framework/src/mocks/block-repository.ts @@ -0,0 +1,67 @@ +import { BlockRepository, RepositorySearchResult } from "@arkecosystem/core-database/src/repositories"; +import { Block } from "@arkecosystem/core-database/src/models"; +import { SearchFilter, SearchPagination } from "@arkecosystem/core-database/src/repositories/search"; + +export type DelegateForgedBlock = { + generatorPublicKey: string; + totalRewards: string; + totalFees: string; + totalProduced: number; +}; +export type LastForgedBlock = { id: string; height: string; generatorPublicKey: string; timestamp: number }; + +let mockBlock: Partial | undefined; +let mockBlocks: Partial[] = []; +let mockDelegatesForgedBlocks: DelegateForgedBlock[] = []; +let mockLastForgedBlocks: LastForgedBlock[] = []; + +export const setBlock = (block: Partial | undefined) => { + mockBlock = block; +}; + +export const setBlocks = (blocks: Partial[]) => { + mockBlocks = blocks; +}; + +export const setDelegateForgedBlocks = (blocks: DelegateForgedBlock[]) => { + mockDelegatesForgedBlocks = blocks; +}; + +export const setLastForgedBlocks = (blocks: LastForgedBlock[]) => { + mockLastForgedBlocks = blocks; +}; + +class BlockRepositoryMock implements Partial { + public async findByIdOrHeight(idOrHeight: string | number): Promise { + return mockBlock as Block; + } + + public async search(filter: SearchFilter): Promise> { + return { + rows: mockBlocks as Block[], + count: mockBlocks.length, + countIsEstimate: false, + }; + } + + public async searchByQuery( + query: Record, + pagination: SearchPagination, + ): Promise> { + return { + rows: mockBlocks as Block[], + count: mockBlocks.length, + countIsEstimate: false, + }; + } + + public async getDelegatesForgedBlocks() { + return mockDelegatesForgedBlocks; + } + + public async getLastForgedBlocks() { + return mockLastForgedBlocks; + } +} + +export const instance = new BlockRepositoryMock(); diff --git a/packages/core-test-framework/src/mocks/blockchain.ts b/packages/core-test-framework/src/mocks/blockchain.ts new file mode 100644 index 0000000000..ff5d300cf0 --- /dev/null +++ b/packages/core-test-framework/src/mocks/blockchain.ts @@ -0,0 +1,31 @@ +import { IBlock } from "@arkecosystem/crypto/src/interfaces"; +import { Blockchain } from "@arkecosystem/core-blockchain"; + +let mockBlock: Partial | undefined; +let mockIsSynced: boolean = true; + +export const setBlock = (block: Partial | undefined) => { + mockBlock = block; +}; + +export const setIsSynced = (isSynced: boolean) => { + mockIsSynced = isSynced; +}; + +class BlockchainMock implements Partial { + public getLastBlock(): IBlock { + return mockBlock as IBlock; + } + + public getLastHeight(): number { + return mockBlock?.data ? mockBlock.data.height : 1; + } + + public isSynced(block?: any): boolean { + return mockIsSynced; + } + + public async removeBlocks(nblocks: number): Promise {} +} + +export const instance = new BlockchainMock(); diff --git a/packages/core-test-framework/src/mocks/index.ts b/packages/core-test-framework/src/mocks/index.ts new file mode 100644 index 0000000000..d87c75fa6a --- /dev/null +++ b/packages/core-test-framework/src/mocks/index.ts @@ -0,0 +1,25 @@ +import * as BlockRepository from "./block-repository"; +import * as Blockchain from "./blockchain"; +import * as NetworkMonitor from "./network-monitor"; +import * as PeerStorage from "./peer-storage"; +import * as TransactionPoolQuery from "./query"; +import * as RoundRepository from "./round-repository"; +import * as ServiceProviderRepository from "./service-provider-repository"; +import * as StateStore from "./state-store"; +import * as TransactionRepository from "./transaction-repository"; +import * as TransactionPoolProcessor from "./transaction-pool-processor"; +import * as WalletRepository from "./wallet-respository"; + +export { + BlockRepository, + Blockchain, + NetworkMonitor, + PeerStorage, + TransactionPoolQuery, + RoundRepository, + ServiceProviderRepository, + StateStore, + TransactionRepository, + TransactionPoolProcessor, + WalletRepository, +}; diff --git a/packages/core-test-framework/src/mocks/network-monitor.ts b/packages/core-test-framework/src/mocks/network-monitor.ts new file mode 100644 index 0000000000..08c2e031d1 --- /dev/null +++ b/packages/core-test-framework/src/mocks/network-monitor.ts @@ -0,0 +1,15 @@ +import { NetworkMonitor } from "@arkecosystem/core-p2p/src/network-monitor"; + +let mockNetworkHeight: number = 0; + +export const setNetworkHeight = (networkHeight: number) => { + mockNetworkHeight = networkHeight; +}; + +class NetworkMonitorMock implements Partial { + public getNetworkHeight(): number { + return mockNetworkHeight; + } +} + +export const instance = new NetworkMonitorMock(); diff --git a/packages/core-test-framework/src/mocks/peer-storage.ts b/packages/core-test-framework/src/mocks/peer-storage.ts new file mode 100644 index 0000000000..6eb3c76d64 --- /dev/null +++ b/packages/core-test-framework/src/mocks/peer-storage.ts @@ -0,0 +1,24 @@ +import { PeerStorage } from "@arkecosystem/core-p2p/src/peer-storage"; +import { Contracts } from "@arkecosystem/core-kernel"; + +let mockPeers: Partial[] = []; + +export const setPeers = (peers: Partial[]) => { + mockPeers = peers; +}; + +class PeerStorageMock implements Partial { + public getPeers(): Contracts.P2P.Peer[] { + return mockPeers as Contracts.P2P.Peer[]; + } + + public hasPeer(ip: string): boolean { + return mockPeers.length > 0; + } + + public getPeer(ip: string): Contracts.P2P.Peer { + return mockPeers[0] as Contracts.P2P.Peer; + } +} + +export const instance = new PeerStorageMock(); diff --git a/packages/core-test-framework/src/mocks/query.ts b/packages/core-test-framework/src/mocks/query.ts new file mode 100644 index 0000000000..7a82b5f985 --- /dev/null +++ b/packages/core-test-framework/src/mocks/query.ts @@ -0,0 +1,43 @@ +import { Transaction } from "@arkecosystem/crypto/src/transactions"; +import { Contracts } from "@arkecosystem/core-kernel"; +import { Interfaces } from "@arkecosystem/crypto"; + +let mockTransactions: Partial[] = []; + +export const setTransactions = (transactions: Partial[]) => { + mockTransactions = transactions; +}; + +export class CustomQueryIterable implements Partial { + public transactions: Interfaces.ITransaction[]; + + public constructor(items) { + this.transactions = items; + } + + public *[Symbol.iterator](): Iterator { + for (const transaction of this.transactions) { + yield transaction; + } + } + + public whereId(id: any): any { + return this; + } + + public has(): boolean { + return this.transactions.length > 0; + } + + public first(): Interfaces.ITransaction { + return this.transactions[0]; + } +} + +class TransactionPoolQueryMock implements Partial { + public getFromHighestPriority(): Contracts.TransactionPool.QueryIterable { + return (new CustomQueryIterable(mockTransactions) as unknown) as Contracts.TransactionPool.QueryIterable; + } +} + +export const instance = new TransactionPoolQueryMock(); diff --git a/packages/core-test-framework/src/mocks/round-repository.ts b/packages/core-test-framework/src/mocks/round-repository.ts new file mode 100644 index 0000000000..e2159d2d40 --- /dev/null +++ b/packages/core-test-framework/src/mocks/round-repository.ts @@ -0,0 +1,16 @@ +import { RoundRepository } from "@arkecosystem/core-database/src/repositories"; +import { Round } from "@arkecosystem/core-database/src/models"; + +let mockRounds: Partial[] = []; + +export const setRounds = (rounds: Partial[]) => { + mockRounds = rounds; +}; + +class RoundRepositoryMock implements Partial { + public async findById(id: string): Promise { + return mockRounds as Round[]; + } +} + +export const instance = new RoundRepositoryMock(); diff --git a/packages/core-test-framework/src/mocks/service-provider-repository.ts b/packages/core-test-framework/src/mocks/service-provider-repository.ts new file mode 100644 index 0000000000..b90028e435 --- /dev/null +++ b/packages/core-test-framework/src/mocks/service-provider-repository.ts @@ -0,0 +1,15 @@ +import { Providers } from "@arkecosystem/core-kernel"; + +let mockServiceProviders: Providers.ServiceProvider[] = []; + +export const setServiceProviders = (serviceProviders: Providers.ServiceProvider[]) => { + mockServiceProviders = serviceProviders; +}; + +class ServiceProviderRepositoryMocks implements Partial { + public allLoadedProviders(): Providers.ServiceProvider[] { + return mockServiceProviders; + } +} + +export const instance = new ServiceProviderRepositoryMocks(); diff --git a/packages/core-test-framework/src/mocks/state-store.ts b/packages/core-test-framework/src/mocks/state-store.ts new file mode 100644 index 0000000000..d1748a8ecf --- /dev/null +++ b/packages/core-test-framework/src/mocks/state-store.ts @@ -0,0 +1,29 @@ +import { StateStore } from "@arkecosystem/core-state/src/stores/state"; +import { IBlock } from "@arkecosystem/crypto/src/interfaces"; + +let mockBlock: Partial | undefined; +let lastHeight: number = 0; + +export const setBlock = (block: Partial | undefined) => { + mockBlock = block; +}; + +export const setLastHeight = (height: number) => { + lastHeight = height; +}; + +class StateStoreMocks implements Partial { + public getLastBlock(): IBlock { + return mockBlock as IBlock; + } + + public getGenesisBlock(): IBlock { + return mockBlock as IBlock; + } + + public getLastHeight(): number { + return lastHeight; + } +} + +export const instance = new StateStoreMocks(); diff --git a/packages/core-test-framework/src/mocks/transaction-pool-processor.ts b/packages/core-test-framework/src/mocks/transaction-pool-processor.ts new file mode 100644 index 0000000000..2ac4347103 --- /dev/null +++ b/packages/core-test-framework/src/mocks/transaction-pool-processor.ts @@ -0,0 +1,43 @@ +import { Contracts } from "@arkecosystem/core-kernel"; +import { Interfaces } from "@packages/crypto"; + +let accept: string[] = []; +let broadcast: string[] = []; +let invalid: string[] = []; +let excess: string[] = []; +let errors: { [id: string]: Contracts.TransactionPool.ProcessorError } | undefined = undefined; + +export const setProcessorState = (state: any): void => { + accept = state.accept ? state.accept : []; + broadcast = state.broadcast ? state.broadcast : []; + broadcast = state.broadcast ? state.broadcast : []; + invalid = state.invalid ? state.invalid : []; + excess = state.excess ? state.excess : []; + errors = state.errors ? state.errors : undefined; +}; + +class TransactionPoolProcessorMock implements Partial { + public async process(data: Interfaces.ITransactionData[]): Promise {} + + public get accept(): string[] { + return accept; + } + + public get broadcast(): string[] { + return broadcast; + } + + public get invalid(): string[] { + return invalid; + } + + public get excess(): string[] { + return excess; + } + + public get errors(): any { + return errors; + } +} + +export const instance = new TransactionPoolProcessorMock(); diff --git a/packages/core-test-framework/src/mocks/transaction-repository.ts b/packages/core-test-framework/src/mocks/transaction-repository.ts new file mode 100644 index 0000000000..45dc67c9d6 --- /dev/null +++ b/packages/core-test-framework/src/mocks/transaction-repository.ts @@ -0,0 +1,107 @@ +import { RepositorySearchResult, TransactionRepository } from "@arkecosystem/core-database/src/repositories"; +import { Transaction } from "@arkecosystem/core-database/src/models"; +import { SearchCriteria, SearchFilter, SearchPagination } from "@arkecosystem/core-database/src/repositories/search"; + +export type FeeStatistics = { + type: number; + typeGroup: number; + avg: string; + min: string; + max: string; + sum: string; +}; + +let mockTransaction: Partial | undefined; +let mockTransactions: Partial[] = []; +let mockFeeStatistics: FeeStatistics[] = []; + +export const setTransaction = (transaction: Partial | undefined) => { + mockTransaction = transaction; +}; + +export const setTransactions = (transactions: Partial[]) => { + mockTransactions = transactions; +}; + +export const setFeeStatistics = (feeStatistics: FeeStatistics[]) => { + mockFeeStatistics = feeStatistics; +}; + +class TransactionRepositoryMock implements Partial { + public async findByIdAndType(type: number, id: string): Promise { + return mockTransaction ? (mockTransaction as Transaction) : undefined; + } + + public async findById(id: string): Promise { + return mockTransaction as Transaction; + } + + public async search(filter: SearchFilter): Promise> { + let transitions = mockTransactions as Transaction[]; + + const type: SearchCriteria | undefined = filter.criteria + ? filter.criteria.find((x) => x.field === "type") + : undefined; + + if (type) { + transitions = transitions.filter((x) => x.type === type.value); + } + + return { + rows: transitions as Transaction[], + count: transitions.length, + countIsEstimate: false, + }; + } + + public async searchByQuery( + query: Record, + pagination: SearchPagination, + ): Promise> { + return { + rows: mockTransactions as Transaction[], + count: mockTransactions.length, + countIsEstimate: false, + }; + } + + public async findByType(type: number, typeGroup: number, limit?: number, offset?: number) { + return mockTransactions as any; + } + + public async findByIds(ids: any[]) { + return mockTransactions as Transaction[]; + } + + public async findReceivedTransactions(): Promise<{ recipientId: string; amount: string }[]> { + return mockTransactions.map((x) => { + return { recipientId: x.recipientId!.toString(), amount: x.amount!.toString() }; + }); + } + + public async findByHtlcLocks(lockIds: string[]): Promise { + return mockTransactions as Transaction[]; + } + + public async getOpenHtlcLocks(): Promise> { + return mockTransactions as any; + } + + public async getClaimedHtlcLockBalances(): Promise<{ amount: string; recipientId: string }[]> { + return mockTransactions.map((x) => { + return { recipientId: x.recipientId!.toString(), amount: x.amount!.toString() }; + }); + } + + public async getRefundedHtlcLockBalances(): Promise<{ amount: string; senderPublicKey: string }[]> { + return mockTransactions.map((x) => { + return { senderPublicKey: x.senderPublicKey!.toString(), amount: x.amount!.toString() }; + }); + } + + public async getFeeStatistics(days: number, minFee?: number): Promise { + return mockFeeStatistics; + } +} + +export const instance = new TransactionRepositoryMock(); diff --git a/packages/core-test-framework/src/mocks/wallet-respository.ts b/packages/core-test-framework/src/mocks/wallet-respository.ts new file mode 100644 index 0000000000..0e4d0919b0 --- /dev/null +++ b/packages/core-test-framework/src/mocks/wallet-respository.ts @@ -0,0 +1,16 @@ +import { WalletRepository } from "@arkecosystem/core-state/src/wallets"; +import { Utils } from "@arkecosystem/crypto"; + +let mockNonce: Utils.BigNumber = Utils.BigNumber.make(1); + +export const setNonce = (nonce: Utils.BigNumber) => { + mockNonce = nonce; +}; + +class WalletRepositoryMock implements Partial { + public getNonce(publicKey: string): Utils.BigNumber { + return mockNonce; + } +} + +export const instance = new WalletRepositoryMock(); diff --git a/packages/core-test-framework/src/utils/index.ts b/packages/core-test-framework/src/utils/index.ts index d41261b6b7..3fcec18c24 100644 --- a/packages/core-test-framework/src/utils/index.ts +++ b/packages/core-test-framework/src/utils/index.ts @@ -2,3 +2,7 @@ export * from "./api"; export * from "./generic"; export * from "./rest-client"; export * from "./transaction-factory"; + +import * as Mapper from './mapper' + +export { Mapper } diff --git a/packages/core-test-framework/src/utils/mapper.ts b/packages/core-test-framework/src/utils/mapper.ts new file mode 100644 index 0000000000..bc87501b58 --- /dev/null +++ b/packages/core-test-framework/src/utils/mapper.ts @@ -0,0 +1,22 @@ +import { Interfaces, Utils } from "@packages/crypto"; +import { Models } from "@packages/core-database"; + +export const mapTransactionToModel = (transaction: Interfaces.ITransaction, sequence: number = 0): Models.Transaction => { + return { + id: transaction.id as string, + version: transaction.data.version || 1, + blockId: transaction.data.blockId || "", + sequence: sequence, + timestamp: transaction.data.timestamp, + nonce: transaction.data.nonce || Utils.BigNumber.make(1), + senderPublicKey: transaction.data.senderPublicKey || "", + recipientId: transaction.data.recipientId || "", + type: transaction.data.type, + typeGroup: transaction.data.typeGroup || 1, + vendorField: transaction.data.vendorField, + amount: BigInt(transaction.data.amount), + fee: BigInt(transaction.data.fee), + serialized: transaction.serialized, + asset: transaction.data.asset as Record, + } +};