From 2acdfc0ed101d121c8891cfc1c51880bc4c063c1 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 11:55:06 +0200 Subject: [PATCH 01/30] remove all controller specs -> new e2e tests are comming --- src/test/integration/api/accounts.api-spec.ts | 2 +- src/test/integration/api/blocks.api-spec.ts | 2 +- .../integration/api/collections.api-spec.ts | 2 +- src/test/integration/api/nfts.api-spec.ts | 2 +- src/test/integration/api/nodes.api-spec.ts | 2 +- .../integration/api/providers.api-spec.ts | 2 +- src/test/integration/api/results.api-spec.ts | 2 +- src/test/integration/api/rounds.api-spec.ts | 2 +- src/test/integration/api/shards.api-spec.ts | 2 +- src/test/integration/api/tags.api-spec.ts | 2 +- src/test/integration/api/tokens.api-spec.ts | 2 +- .../integration/api/transactions.api-spec.ts | 2 +- .../controllers/blocks.controller.e2e-spec.ts | 159 -------- .../collections.controller.e2e-spec.ts | 362 ----------------- .../dappconfig.controller.e2e-spec.ts | 45 --- .../delegation.controller.e2e-spec.ts | 53 --- .../health.check.controller.e2e-spec.ts | 33 -- .../maiar.exchange.controller.e2e-spec.ts | 63 --- .../miniblocks.controller.e2e-spec.ts | 57 --- .../controllers/nfts.controller.e2e-spec.ts | 365 ------------------ .../controllers/nodes.controller.e2e-spec.ts | 38 -- .../private.app.module.controller.e2e-spec.ts | 36 -- .../controllers/proxy.controller.e2e-spec.ts | 136 ------- .../pub-sub-listener.controller.e2e-spec.ts | 53 --- .../results.controller.e2e-spec.ts | 131 ------- .../controllers/shards.controller.e2e-spec.ts | 45 --- .../controllers/stake.controller.e2e-spec.ts | 34 -- .../controllers/tags.controller.e2e-spec.ts | 112 +++--- .../controllers/tokens.controller.e2e-spec.ts | 268 ------------- .../transactions.controller.e2e-spec.ts | 97 ----- .../username.controller.e2e-spec.ts | 45 --- .../vmQuery.controller.e2e-spec.ts | 76 ---- .../waiting-list.controller.e2e-spec.ts | 41 -- 33 files changed, 62 insertions(+), 2211 deletions(-) delete mode 100644 src/test/integration/controllers/blocks.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/collections.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/dappconfig.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/delegation.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/health.check.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/maiar.exchange.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/miniblocks.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/nfts.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/nodes.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/private.app.module.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/proxy.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/pub-sub-listener.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/results.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/shards.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/stake.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/tokens.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/transactions.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/username.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/vmQuery.controller.e2e-spec.ts delete mode 100644 src/test/integration/controllers/waiting-list.controller.e2e-spec.ts diff --git a/src/test/integration/api/accounts.api-spec.ts b/src/test/integration/api/accounts.api-spec.ts index 1498b04c2..aadca2d6b 100644 --- a/src/test/integration/api/accounts.api-spec.ts +++ b/src/test/integration/api/accounts.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/blocks.api-spec.ts b/src/test/integration/api/blocks.api-spec.ts index e8062a114..adf4605be 100644 --- a/src/test/integration/api/blocks.api-spec.ts +++ b/src/test/integration/api/blocks.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/collections.api-spec.ts b/src/test/integration/api/collections.api-spec.ts index 8e6f9f913..a88c462e1 100644 --- a/src/test/integration/api/collections.api-spec.ts +++ b/src/test/integration/api/collections.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/nfts.api-spec.ts b/src/test/integration/api/nfts.api-spec.ts index 99eff2fe9..f835e9ed1 100644 --- a/src/test/integration/api/nfts.api-spec.ts +++ b/src/test/integration/api/nfts.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/nodes.api-spec.ts b/src/test/integration/api/nodes.api-spec.ts index e5fbf5af8..5c1866f81 100644 --- a/src/test/integration/api/nodes.api-spec.ts +++ b/src/test/integration/api/nodes.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/providers.api-spec.ts b/src/test/integration/api/providers.api-spec.ts index 3a691a88d..fee03fa8b 100644 --- a/src/test/integration/api/providers.api-spec.ts +++ b/src/test/integration/api/providers.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/results.api-spec.ts b/src/test/integration/api/results.api-spec.ts index 5483408d0..706dcea49 100644 --- a/src/test/integration/api/results.api-spec.ts +++ b/src/test/integration/api/results.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/rounds.api-spec.ts b/src/test/integration/api/rounds.api-spec.ts index 12c2c70bd..4514fab7c 100644 --- a/src/test/integration/api/rounds.api-spec.ts +++ b/src/test/integration/api/rounds.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/shards.api-spec.ts b/src/test/integration/api/shards.api-spec.ts index a07c43114..2d547171d 100644 --- a/src/test/integration/api/shards.api-spec.ts +++ b/src/test/integration/api/shards.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/tags.api-spec.ts b/src/test/integration/api/tags.api-spec.ts index 85c6735a2..8e1ce9330 100644 --- a/src/test/integration/api/tags.api-spec.ts +++ b/src/test/integration/api/tags.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/tokens.api-spec.ts b/src/test/integration/api/tokens.api-spec.ts index eae931202..5b28c33cd 100644 --- a/src/test/integration/api/tokens.api-spec.ts +++ b/src/test/integration/api/tokens.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/api/transactions.api-spec.ts b/src/test/integration/api/transactions.api-spec.ts index e0fb226ef..a985a9139 100644 --- a/src/test/integration/api/transactions.api-spec.ts +++ b/src/test/integration/api/transactions.api-spec.ts @@ -4,7 +4,7 @@ import { Test } from '@nestjs/testing'; import { PublicAppModule } from 'src/public.app.module'; import { ApiChecker } from 'src/utils/api.checker'; -describe("API Testing", () => { +describe.skip("API Testing", () => { let app: INestApplication; beforeAll(async () => { diff --git a/src/test/integration/controllers/blocks.controller.e2e-spec.ts b/src/test/integration/controllers/blocks.controller.e2e-spec.ts deleted file mode 100644 index 677720f91..000000000 --- a/src/test/integration/controllers/blocks.controller.e2e-spec.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Block Controller", () => { - let app: INestApplication; - const path: string = "/blocks"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/blocks', () => { - it('should return 25 blocks details from all shards', async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it('should return 1 block details', async () => { - const params = new URLSearchParams({ - 'size': '1', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(1); - }); - }); - - test.each` - shard - ${1} - ${2} - ${0} - ${4294967295} - ` - ( - `should return 25 blocks from shard $shard`, - async ({ shard }) => { - const params = new URLSearchParams({ - 'shard': shard, - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - expect(res.body[0].shard).toStrictEqual(parseInt(`${shard}`)); - }); - } - ); - }); - - describe('/blocks/count', () => { - it('should return count of all blocks from all shards', async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(42605100); - }); - }); - - [ - { - shard: 1, - count: 10652302, - }, - { - shard: 0, - count: 10656418, - }, - { - shard: 4294967295, - count: 10640421, - }, - { - shard: 2, - count: 10656826, - }, - ].forEach(({ shard, count }) => { - describe(`shard = ${shard}`, () => { - it(`shoudl return count of all blocks from shard ${shard}`, async () => { - const params = new URLSearchParams({ - 'shard': `${shard}`, - }); - - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); - - describe('/blocks/{hash}', () => { - it('should return block information details for a given hash', async () => { - const hash: string = 'c3cd456e15a59bb1f143eefd4986ef010965047f89e303b80822b05177351ccd'; - - await request(app.getHttpServer()) - .get(`${path}/${hash}`) - .expect(200) - .then(res => { - expect(res.body.hash).toStrictEqual(hash); - expect(res.body.epoch).toStrictEqual(500); - expect(res.body.nonce).toStrictEqual(7212812); - expect(res.body.prevHash).toStrictEqual('be95ddc0f2a38f1732c5fba296ea340a92dff62cab74ac710b5395cc3a1d349d'); - expect(res.body.proposer).toStrictEqual('7e97327bac868aba21777a1fd336e260d1dfb3357d7e117a3ce6d4c2e9869ceed756eb094042dd961f1c0e9c47612f0986fb15b39847688fdf90b02fb13ff700ee3ce0b31738942e447fd0f40c77b7d0ae974c03a364a67dad0cd9ec039f3b09'); - expect(res.body.pubKeyBitmap).toStrictEqual('ffffffffffffff7f'); - expect(res.body.round).toStrictEqual(7214879); - expect(res.body.shard).toStrictEqual(1); - expect(res.body.size).toStrictEqual(2095); - expect(res.body.sizeTxs).toStrictEqual(31137); - expect(res.body.stateRootHash).toStrictEqual('623b558cb2f057e0a1e90e748373f5739893dadeeab8ae7bdd4fa092bf5635a0'); - expect(res.body.timestamp).toStrictEqual(1639406874); - expect(res.body.txCount).toStrictEqual(39); - expect(res.body.gasConsumed).toStrictEqual(492435900); - expect(res.body.gasRefunded).toStrictEqual(190541397); - expect(res.body.gasPenalized).toStrictEqual(0); - expect(res.body.maxGasLimit).toStrictEqual(1500000000); - expect(res.body.miniBlocksHashes).toBeDefined(); - expect(res.body.validators).toBeDefined(); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Bad Request for a invalid block hash', async () => { - const hash: string = 'c3cd456e15a59bb1f143eefd4986ef010965047f89e303b80822b05177351c'; - - await request(app.getHttpServer()) - .get(`${path}/${hash}`) - .expect(400) - .then(res => { - expect(res.body.message).toContain("Validation failed"); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/collections.controller.e2e-spec.ts b/src/test/integration/controllers/collections.controller.e2e-spec.ts deleted file mode 100644 index 4f2e39ce0..000000000 --- a/src/test/integration/controllers/collections.controller.e2e-spec.ts +++ /dev/null @@ -1,362 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("collections Controller", () => { - let app: INestApplication; - const path: string = "/collections"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/collections', () => { - - it('should return 25 collections', async () => { - await request(app.getHttpServer()) - .get(path) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it('should return 5 collections', async () => { - const params = new URLSearchParams({ - 'size': '5', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(5); - }); - }); - - it('should return collection detailes for a given identifier', async () => { - const params = new URLSearchParams({ - 'identifiers': 'MEDAL-ae074f', - }); - - const expected = - [ - { - collection: "MEDAL-ae074f", - type: "NonFungibleESDT", - name: "GLUMedals", - ticker: "MEDAL-ae074f", - owner: "erd126y66ear20cdskrdky0kpzr9agjul7pcut7ktlr6p0eu8syxhvrq0gsqdj", - timestamp: 1654019676, - canFreeze: false, - canWipe: false, - canPause: false, - canTransferNftCreateRole: false, - canChangeOwner: false, - canUpgrade: false, - canAddSpecialRoles: false, - traits: [], - }]; - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toStrictEqual(expected); - }); - }); - - it('should return two collections details', async () => { - const params = new URLSearchParams({ - 'identifiers': 'MEDAL-ae074f,EROBOT-527a29', - }); - - const expected = - [ - { - collection: "MEDAL-ae074f", - type: "NonFungibleESDT", - name: "GLUMedals", - ticker: "MEDAL-ae074f", - owner: "erd126y66ear20cdskrdky0kpzr9agjul7pcut7ktlr6p0eu8syxhvrq0gsqdj", - timestamp: 1654019676, - canFreeze: false, - canWipe: false, - canPause: false, - canTransferNftCreateRole: false, - canChangeOwner: false, - canUpgrade: false, - canAddSpecialRoles: false, - traits: [], - }, - { - collection: "EROBOT-527a29", - type: "NonFungibleESDT", - name: "eRobots", - ticker: "EROBOT-527a29", - owner: "erd1nz42knvgmxpevepsyvq9dx3wzdgtd6lmu96y28tuupayazgx4fvs3w9d09", - timestamp: 1638990678, - canFreeze: false, - canWipe: false, - canPause: false, - canTransferNftCreateRole: false, - canChangeOwner: true, - canUpgrade: true, - canAddSpecialRoles: true, - traits: [], - }, - ]; - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toStrictEqual(expected); - }); - }); - - it('should return one collection details based on canCreate role address', async () => { - const params = new URLSearchParams({ - 'canCreate': 'erd1qqqqqqqqqqqqqpgq09vq93grfqy7x5fhgmh44ncqfp3xaw57ys5s7j9fed', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body.length).toBeGreaterThanOrEqual(1); - }); - }); - - it('should return one collection details based on canBurn role address', async () => { - const params = new URLSearchParams({ - 'canCreate': 'erd1kj2tpra7e5vayparwv0fzhgsmnrw442r5u53sphjfs2h8lrl54sstuf6y4', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body.length).toBeGreaterThanOrEqual(1); - }); - }); - - test.each` - types - ${'NonFungibleESDT'} - ${'SemiFungibleESDT'} - ${'MetaESDT'} - ` - ( - `for the given collection type $types, should return 25 collections`, - async ({ types }) => { - const params = new URLSearchParams({ - 'type': types, - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - expect(res.body).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: `${types}` }), - ]) - ); - }); - } - ); - }); - - describe('/collections/count', () => { - it('should return total collections count', async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(6200); - }); - }); - - it('should count for a given collection identifier', async () => { - const params = new URLSearchParams({ - 'identifiers': 'MEDAL-ae074f', - }); - - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(1); - }); - }); - - test.each` - types - ${'NonFungibleESDT'} - ${'SemiFungibleESDT'} - ${'MetaESDT'} - ` - ( - `for the given collection type $types, should return collections count`, - async ({ types }) => { - const params = new URLSearchParams({ - 'type': types, - }); - - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(40); - }); - } - ); - - it('should return collection count based on canCreate role address', async () => { - const params = new URLSearchParams({ - 'canCreate': 'erd1qqqqqqqqqqqqqpgq09vq93grfqy7x5fhgmh44ncqfp3xaw57ys5s7j9fed', - }); - - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(1); - }); - }); - - it('should return collection count based on canBurn role address', async () => { - const params = new URLSearchParams({ - 'canCreate': 'erd1kj2tpra7e5vayparwv0fzhgsmnrw442r5u53sphjfs2h8lrl54sstuf6y4', - }); - - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(1); - }); - }); - }); - - describe('collections/{collection}', () => { - it('should return collection details for a given collection identifier', async () => { - const identifier: string = 'MEDAL-ae074f'; - const expected = - { - collection: "MEDAL-ae074f", - type: "NonFungibleESDT", - name: "GLUMedals", - ticker: "MEDAL-ae074f", - owner: "erd126y66ear20cdskrdky0kpzr9agjul7pcut7ktlr6p0eu8syxhvrq0gsqdj", - timestamp: 1654019676, - canFreeze: false, - canWipe: false, - canPause: false, - canTransfer: true, - canTransferNftCreateRole: false, - canChangeOwner: false, - canUpgrade: false, - canAddSpecialRoles: false, - roles: [ - { - address: "erd1qqqqqqqqqqqqqpgq8ne37ed06034qxfhm09f03ykjfqwx8s7hvrqackmzt", - canCreate: true, - canBurn: false, - canAddQuantity: false, - canUpdateAttributes: false, - canAddUri: false, - roles: [ - "ESDTRoleNFTCreate", - ], - }, - ], - traits: [], - }; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(200) - .then(res => { - expect(res.body).toStrictEqual(expected); - }); - }); - }); - - describe('/collections/{identifier}/nfts', () => { - it('should return 25 NFTs from a given collection', async () => { - const identifier: string = 'MEDAL-ae074f'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/nfts`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it('should return 5 NFTs from a given collection', async () => { - const identifier: string = 'MEDAL-ae074f'; - const params = new URLSearchParams({ - 'size': '5', - }); - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/nfts?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(5); - }); - }); - }); - - describe('/collections/{identifier}/nfts/count', () => { - it('should return total number of NFTs from a given collection', async () => { - const identifier: string = 'MEDAL-ae074f'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/nfts/count`) - .expect(200) - .then(res => { - expect(+res.text).toStrictEqual(120); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Bad Request if collection identifier does not contain the right format', async () => { - const identifier: string = 'MEDALae074f'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(400) - .then(res => { - expect(res.body.message).toEqual("Validation failed for argument 'collection': Invalid collection identifier."); - }); - }); - - it('should return 400 Bad Request if collection type is not correct', async () => { - const params = new URLSearchParams({ - 'type': 'NONFungibleESDT', - }); - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(400) - .then(res => { - expect(res.body.message).toEqual("Validation failed for argument 'type' (one of the following values is expected: NonFungibleESDT, SemiFungibleESDT, MetaESDT)"); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/dappconfig.controller.e2e-spec.ts b/src/test/integration/controllers/dappconfig.controller.e2e-spec.ts deleted file mode 100644 index b80374914..000000000 --- a/src/test/integration/controllers/dappconfig.controller.e2e-spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Dapp-Config Controller", () => { - let app: INestApplication; - const path: string = "/dapp/config"; - - beforeEach(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/dapp/config', () => { - it('should return configuration used in dapps', async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body.id).toBeDefined(); - expect(res.body.name).toBeDefined(); - expect(res.body.egldLabel).toBeDefined(); - expect(res.body.decimals).toBeDefined(); - expect(res.body.egldDenomination).toBeDefined(); - expect(res.body.gasPerDataByte).toBeDefined(); - expect(res.body.apiTimeout).toBeDefined(); - expect(res.body.walletConnectDeepLink).toBeDefined(); - expect(res.body.walletConnectBridgeAddresses).toBeDefined(); - expect(res.body.walletAddress).toBeDefined(); - expect(res.body.apiAddress).toBeDefined(); - expect(res.body.explorerAddress).toBeDefined(); - expect(res.body.chainId).toBeDefined(); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/delegation.controller.e2e-spec.ts b/src/test/integration/controllers/delegation.controller.e2e-spec.ts deleted file mode 100644 index 01b8ff71f..000000000 --- a/src/test/integration/controllers/delegation.controller.e2e-spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Delegations Controller", () => { - let app: INestApplication; - const delegationPath: string = "/delegation"; - const delegationLegacyPath: string = "/delegation-legacy"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/delegation', () => { - it('should return delegation staking contract information', async () => { - await request(app.getHttpServer()) - .get(`${delegationPath}`) - .expect(200) - .then(res => { - expect(res.body.stake).toBeDefined(); - expect(res.body.topUp).toBeDefined(); - expect(res.body.locked).toBeDefined(); - expect(res.body.minDelegation).toBeDefined(); - }); - }); - }); - - describe('/delegation-legacy', () => { - it('should return legacy delegation contract global information', async () => { - await request(app.getHttpServer()) - .get(`${delegationLegacyPath}`) - .expect(200) - .then(res => { - expect(res.body.totalWithdrawOnlyStake).toBeDefined(); - expect(res.body.totalWaitingStake).toBeDefined(); - expect(res.body.totalActiveStake).toBeDefined(); - expect(res.body.totalUnstakedStake).toBeDefined(); - expect(res.body.totalDeferredPaymentStake).toBeDefined(); - expect(res.body.numUsers).toBeDefined(); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/health.check.controller.e2e-spec.ts b/src/test/integration/controllers/health.check.controller.e2e-spec.ts deleted file mode 100644 index 17a201d8e..000000000 --- a/src/test/integration/controllers/health.check.controller.e2e-spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Hello Controller", () => { - let app: INestApplication; - const path: string = "/hello"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/hello', () => { - it("should returns 'hello', used for performing health checks ", async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.text).toStrictEqual('hello'); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/maiar.exchange.controller.e2e-spec.ts b/src/test/integration/controllers/maiar.exchange.controller.e2e-spec.ts deleted file mode 100644 index 20872b11c..000000000 --- a/src/test/integration/controllers/maiar.exchange.controller.e2e-spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("xExchange Controller", () => { - let app: INestApplication; - const path: string = "/mex"; - - beforeEach(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - it("should returns economics details of xExchange ", async () => { - await request(app.getHttpServer()) - .get(`${path}/economics`) - .expect(200) - .then(res => { - expect(res.body.totalSupply).toBeDefined(); - expect(res.body.circulatingSupply).toBeDefined(); - expect(res.body.price).toBeDefined(); - expect(res.body.marketCap).toBeDefined(); - expect(res.body.volume24h).toBeDefined(); - expect(res.body.marketPairs).toBeDefined(); - }); - }); - - it("should returns 25 active liquidity pools available on xExchange ", async () => { - await request(app.getHttpServer()) - .get(`${path}/pairs`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it("should returns list of 25 tokens listed on xExchange ", async () => { - await request(app.getHttpServer()) - .get(`${path}/tokens`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it("should returns list of farms listed on xExchange ", async () => { - await request(app.getHttpServer()) - .get(`${path}/farms`) - .expect(200) - .then(res => { - expect((res.body).length).toBeGreaterThanOrEqual(20); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/miniblocks.controller.e2e-spec.ts b/src/test/integration/controllers/miniblocks.controller.e2e-spec.ts deleted file mode 100644 index 3aed7ec1c..000000000 --- a/src/test/integration/controllers/miniblocks.controller.e2e-spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Miniblocks Controller", () => { - let app: INestApplication; - const path: string = "/miniblocks"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/miniblocks', () => { - it('should return miniBlock details for a given identifier', async () => { - const miniblock: string = 'e336ba1b720bb153b4e0d2049d722b0e39bf275f9d35e79b0f757271a963ad4c'; - const expected = { - miniBlockHash: "e336ba1b720bb153b4e0d2049d722b0e39bf275f9d35e79b0f757271a963ad4c", - receiverBlockHash: "ee60ef38ab592d4a32a3ba5783996ae72afda9d2bf40295fcf7c43915120227f", - receiverShard: 2, - senderBlockHash: "ee60ef38ab592d4a32a3ba5783996ae72afda9d2bf40295fcf7c43915120227f", - senderShard: 2, - timestamp: 1644529902, - type: "TxBlock", - }; - - await request(app.getHttpServer()) - .get(`${path}/${miniblock}`) - .expect(200) - .then(res => { - expect(res.body).toStrictEqual(expected); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Bad Request if an invalid block hash is given', async () => { - const miniBlockHash: string = 'invalidMiniBlockHash'; - - await request(app.getHttpServer()) - .get(`${path}/${miniBlockHash}`) - .expect(400) - .then(res => { - expect(res.body.message).toContain("Validation failed"); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/nfts.controller.e2e-spec.ts b/src/test/integration/controllers/nfts.controller.e2e-spec.ts deleted file mode 100644 index 196a3c40b..000000000 --- a/src/test/integration/controllers/nfts.controller.e2e-spec.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { ComplexityInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("NFT Controller", () => { - let app: INestApplication; - const path: string = "/nfts"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors(new ComplexityInterceptor()); - await app.init(); - }); - - describe('/nfts', () => { - it('should return a list of 25 Non-Fungible / Semi-Fungible / MetaESDT tokens available on blockchain', async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it("/nfts?withSupply - should return 200 status code and one list of nfts with filter withSupply", async () => { - const params = new URLSearchParams({ - 'withSupply': 'true', - }); - - await request(app.getHttpServer()) - .get(path + "?" + params) - .expect(200); - }); - it('should return a list of 5 Non-Fungible / Semi-Fungible / MetaESDT tokens available on blockchain', async () => { - const params = new URLSearchParams({ - 'size': '5', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(5); - }); - }); - - it('should return a list of NFTs for a given collection identifier', async () => { - const params = new URLSearchParams({ - 'collection': 'MEDAL-ae074f', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - expect(res.body[0].collection).toStrictEqual('MEDAL-ae074f'); - }); - }); - - it('should return a specific NFT for a given NFT identifier', async () => { - const params = new URLSearchParams({ - 'identifiers': 'MEDAL-ae074f-78', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(1); - expect(res.body[0].collection).toStrictEqual('MEDAL-ae074f'); - expect(res.body[0].identifier).toStrictEqual('MEDAL-ae074f-78'); - }); - }); - - test.each` - types - ${'NonFungibleESDT'} - ${'SemiFungibleESDT'}` - ( - `for the given type $types, should return 25 tokens`, - async ({ types }) => { - const params = new URLSearchParams({ - 'type': types, - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - expect(res.body).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: `${types}` }), - ]) - ); - }); - }); - - it('should return a list of 25 esdts that are marked as scam', async () => { - const params = new URLSearchParams({ - 'isNsfw': 'true', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - - for (const response of res.body) { - expect(response.isNsfw).toStrictEqual(true); - } - }); - }); - - it('should return a list of 25 SFTs that have supply when withSupply is true', async () => { - const params = new URLSearchParams({ - 'withSupply': 'true', - 'type': 'SemiFungibleESDT', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - - for (const response of res.body) { - expect(response.type).toStrictEqual('SemiFungibleESDT'); - expect(response.supply).toBeDefined(); - } - }); - }); - - it('should return a list of 25 NFTs and supply attribute should not be defined even with withSupply true', async () => { - const params = new URLSearchParams({ - 'withSupply': 'true', - 'type': 'NonFungibleESDT', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - - for (const response of res.body) { - expect(response.type).toStrictEqual('NonFungibleESDT'); - expect(response.supply).not.toBeDefined(); - } - }); - }); - - it('should return a list of 25 tokens without supply even if withSupply option is false', async () => { - const params = new URLSearchParams({ - 'withSupply': 'false', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - - for (const response of res.body) { - expect(response.supply).not.toBeDefined(); - } - }); - }); - - it('should return a list of 25 SFTs that have supply', async () => { - const params = new URLSearchParams({ - 'withSupply': 'true', - 'type': 'SemiFungibleESDT', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - - for (const response of res.body) { - expect(response.type).toStrictEqual('SemiFungibleESDT'); - expect(response.supply).toBeDefined(); - } - }); - }); - }); - - describe('/nfts/count', () => { - it('should returns the total number of Non-Fungible / Semi-Fungible / MetaESDT tokens', async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(1001167); - }); - }); - - [ - { - filter: 'type', - value: 'NonFungibleESDT', - count: 991113, - }, - { - filter: 'type', - value: 'SemiFungibleESDT', - count: 23101, - }, - { - filter: 'collection', - value: 'EROBOT-527a29', - count: 200, - }, - { - filter: 'name', - value: 'Gritty Summit Chaser', - count: 1, - }, - { - filter: 'tags', - value: 'elrond', - count: 298265, - }, - { - filter: 'isWhitelistedStorage', - value: 'true', - count: 733653, - }, - { - filter: 'hasUris', - value: 'true', - count: 928696, - }, - { - filter: 'isNsfw', - value: 'true', - count: 287, - }, - { - filter: 'before', - value: '1660114204', - count: 1008974, - }, - { - filter: 'after', - value: '1660134204', - count: 2, - }, - - ].forEach(({ filter, value, count }) => { - describe(`filter = ${filter}`, () => { - it(`should return total count based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}/count?${filter}=${value}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); - - describe('/nfts/{identifier}', () => { - it('should returns the details of an Non-Fungible / Semi-Fungible / MetaESDT token for a given identifier', async () => { - const identifier: string = 'EROBOT-527a29-c8'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(200) - .then(res => { - expect(res.body.identifier).toStrictEqual(identifier); - }); - }); - }); - - describe('/nfts/{identifier}/supply', () => { - it('should returns Non-Fungible / Semi-Fungible / MetaESDT token supply details for a given identifier', async () => { - const identifier: string = 'EROBOT-527a29-c8'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/supply`) - .expect(200) - .then(res => { - expect(res.body.supply).toStrictEqual('1'); - }); - }); - }); - - describe('/nfts/{identifier}/accounts', () => { - it('should returns Non-Fungible / Semi-Fungible / MetaESDT token accounts details for a given identifier', async () => { - const identifier: string = 'EROBOT-527a29-c8'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/accounts`) - .expect(200) - .then(res => { - expect(res.body[0].address).toBeDefined(); - expect(res.body[0].balance).toBeDefined(); - }); - }); - }); - - describe('/nfts/{identifier}/accounts/count', () => { - it('should returns Non-Fungible / Semi-Fungible / MetaESDT token accounts details for a given identifier', async () => { - const identifier: string = 'EROBOT-527a29-c8'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/accounts/count`) - .expect(200) - .then(res => { - expect(+res.text).toStrictEqual(1); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Bad Request if given collection identifier is invalid (format incorect)', async () => { - const identifier: string = 'abc123'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(400) - .then(res => { - expect(res.body.message).toStrictEqual("Validation failed for argument 'identifier': Invalid NFT identifier."); - }); - }); - - it('should return 404 Not Found if given collection identifier is not found', async () => { - const identifier: string = 'EROBOTT-527a29-c8'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(404) - .then(res => { - expect(res.body.message).toStrictEqual("NFT not found"); - }); - }); - - it(`should return 400 status code because "withScamInfo" flag is active and size is greater than 100 (limit)`, async () => { - const params = new URLSearchParams({ - 'from': '0', - 'size': '101', - 'withScamInfo': 'true', - }); - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(400); - }); - }); - - afterAll(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/nodes.controller.e2e-spec.ts b/src/test/integration/controllers/nodes.controller.e2e-spec.ts deleted file mode 100644 index 441d7568d..000000000 --- a/src/test/integration/controllers/nodes.controller.e2e-spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Nodes Controller", () => { - let app: INestApplication; - const path: string = "/nodes"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/nodes', () => { - it('should return all nodes with status "jailed"', async () => { - const params = new URLSearchParams({ - 'status': 'jailed', - }); - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - for (const response of res.body) { - expect(response.status).toStrictEqual('jailed'); - } - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/private.app.module.controller.e2e-spec.ts b/src/test/integration/controllers/private.app.module.controller.e2e-spec.ts deleted file mode 100644 index 0c4ea1b0e..000000000 --- a/src/test/integration/controllers/private.app.module.controller.e2e-spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { TestingModule, Test } from "@nestjs/testing"; -import { ApiMetricsController } from "src/common/metrics/api.metrics.controller"; -import { RemoteCacheController } from "src/endpoints/caching/remote.cache.controller"; -import { HealthCheckController } from "src/endpoints/health-check/health.check.controller"; -import { ProcessNftsPrivateController } from "src/endpoints/process-nfts/process.nfts.private.controller"; -import { PrivateAppModule } from "src/private.app.module"; - -describe('PrivateAppModule', () => { - let module: TestingModule; - - beforeEach(async () => { - module = await Test.createTestingModule({ - imports: [PrivateAppModule], - }).compile(); - }); - - it('should have ApiMetricsController', () => { - const controller = module.get(ApiMetricsController); - expect(controller).toBeDefined(); - }); - - it('should have RemoteCacheController', () => { - const controller = module.get(RemoteCacheController); - expect(controller).toBeDefined(); - }); - - it('should have HealthCheckController', () => { - const controller = module.get(HealthCheckController); - expect(controller).toBeDefined(); - }); - - it('should have ProcessNftsPrivateController', () => { - const controller = module.get(ProcessNftsPrivateController); - expect(controller).toBeDefined(); - }); -}); diff --git a/src/test/integration/controllers/proxy.controller.e2e-spec.ts b/src/test/integration/controllers/proxy.controller.e2e-spec.ts deleted file mode 100644 index 22b4217c3..000000000 --- a/src/test/integration/controllers/proxy.controller.e2e-spec.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import { ProxyController } from 'src/endpoints/proxy/proxy.controller'; - -describe('Proxy Controller', () => { - let proxyController: ProxyController; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - proxyController = moduleRef.get(ProxyController); - }); - - describe('getAddress', () => { - it('should return address details (gateway source)', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddress(address); - - expect(result).toEqual(expect.objectContaining({ - data: expect.objectContaining({ - account: expect.objectContaining({ - address: address, - username: "alice.elrond", - }), - }), - })); - }); - }); - - describe('getAddressBalance', () => { - it('should return address current balance', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddressBalance(address); - - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getAddressNonce', () => { - it('should return address nonce', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddressNonce(address); - - expect(result.data.nonce).toStrictEqual(45); - }); - }); - - describe('getAddressShard', () => { - it('should return address shard', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddressShard(address); - - expect(result).toEqual(expect.objectContaining({ - data: expect.objectContaining({ - shardID: 0, - }), - })); - }); - }); - - describe('getAddressTransactions', () => { - it('should return address transactions', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddressTransactions(address); - - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getAddressEsdt', () => { - it('should return address tokens', async () => { - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const result = await proxyController.getAddressEsdt(address); - - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getNetworkStatusShard', () => { - it('should return network status shard', async () => { - const shard: string = '0'; - const result = await proxyController.getNetworkStatusShard(shard); - - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getNetworkConfig', () => { - it('should return network configuration', async () => { - const result = await proxyController.getNetworkConfig(); - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getNetworkEconomics', () => { - it('should return network economics', async () => { - const result = await proxyController.getNetworkEconomics(); - expect(result).toEqual(expect.objectContaining({ - code: 'successful', - })); - }); - }); - - describe('getBlockByShardAndNonce', () => { - it('should return block details by shard and nonce', async () => { - const shard: string = "0"; - const nonce: number = 100; - const result = await proxyController.getBlockByShardAndNonce(shard, nonce); - - expect(result).toEqual(expect.objectContaining({ - data: expect.objectContaining({ - block: expect.objectContaining({ - nonce: 100, - round: 100, - epoch: 0, - shard: 0, - }), - }), - code: 'successful', - })); - }); - }); -}); diff --git a/src/test/integration/controllers/pub-sub-listener.controller.e2e-spec.ts b/src/test/integration/controllers/pub-sub-listener.controller.e2e-spec.ts deleted file mode 100644 index 0bdae79c5..000000000 --- a/src/test/integration/controllers/pub-sub-listener.controller.e2e-spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { TestingModule, Test } from "@nestjs/testing"; -import { PubSubListenerController } from "src/common/pubsub/pub.sub.listener.controller"; - -const cacheServiceMock = { - deleteLocal: jest.fn(), - refreshLocal: jest.fn(), -}; - -describe('PubSubListenerController', () => { - let controller: PubSubListenerController; - - beforeEach(async () => { - const module: TestingModule = await Test.createTestingModule({ - controllers: [PubSubListenerController], - providers: [ - { provide: CacheService, useValue: cacheServiceMock }, - ], - }).compile(); - - controller = module.get(PubSubListenerController); - }); - - afterEach(() => { - jest.resetAllMocks(); - }); - - it('should be defined', () => { - expect(controller).toBeDefined(); - }); - - it('should delete cache keys', async () => { - const keys = ['key1', 'key2', 'key3']; - - await controller.deleteCacheKey(keys); - - expect(cacheServiceMock.deleteLocal).toHaveBeenCalledTimes(keys.length); - - let index = 1; - for (const key of keys) { - expect(cacheServiceMock.deleteLocal).toHaveBeenNthCalledWith(index, key); - index++; - } - }); - - it('should refresh cache key', async () => { - const info = { key: 'test-key', ttl: 1000 }; - - await controller.refreshCacheKey(info); - - expect(cacheServiceMock.refreshLocal).toHaveBeenCalledWith(info.key, info.ttl); - }); -}); diff --git a/src/test/integration/controllers/results.controller.e2e-spec.ts b/src/test/integration/controllers/results.controller.e2e-spec.ts deleted file mode 100644 index 696c9e7b7..000000000 --- a/src/test/integration/controllers/results.controller.e2e-spec.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Results Controller", () => { - let app: INestApplication; - const path: string = "/results"; - - beforeEach(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('results', () => { - it('should return 25 smart contract results', async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); - - it('should return one smart contract result details', async () => { - const params = new URLSearchParams({ - 'size': '1', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(1); - expect(res.body[0].hash).toBeDefined(); - expect(res.body[0].timestamp).toBeDefined(); - expect(res.body[0].nonce).toBeDefined(); - expect(res.body[0].gasLimit).toBeDefined(); - expect(res.body[0].gasPrice).toBeDefined(); - expect(res.body[0].value).toBeDefined(); - expect(res.body[0].sender).toBeDefined(); - expect(res.body[0].receiver).toBeDefined(); - expect(res.body[0].data).toBeDefined(); - expect(res.body[0].prevTxHash).toBeDefined(); - expect(res.body[0].originalTxHash).toBeDefined(); - expect(res.body[0].callType).toBeDefined(); - }); - }); - - it('should return one smart contract result details for a given miniBlockHash', async () => { - const params = new URLSearchParams({ - 'originalTxHashes': 'f01660479c8481a1c07e78508898130e45dc8657bf2fc5c2f377623eb18f734d', - }); - - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(2); - expect(res.body.find((x: any) => x.hash === 'bc68da1de1926031f03211dc1610b4513043ccd497fdc09817aa721e20555057')).toBeDefined(); - expect(res.body.find((x: any) => x.hash === '6410188f7c240e795e1a0fc9c4656e406bae57721b4a685a49cfa73ae855d7d4')).toBeDefined(); - }); - }); - }); - - describe('/results/count', () => { - it('should return total number of smart contracts results', async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(18100199); - }); - }); - }); - - describe('/results/{scHash}', () => { - it('shoult return smart contract details for a given hash', async () => { - const scHash: string = 'bc68da1de1926031f03211dc1610b4513043ccd497fdc09817aa721e20555057'; - await request(app.getHttpServer()) - .get(`${path}/${scHash}`) - .expect(200) - .then(res => { - expect(res.body.hash).toStrictEqual('bc68da1de1926031f03211dc1610b4513043ccd497fdc09817aa721e20555057'); - expect(res.body.timestamp).toStrictEqual(1638181584); - expect(res.body.nonce).toStrictEqual(80); - expect(res.body.gasLimit).toStrictEqual(0); - expect(res.body.gasPrice).toStrictEqual(1000000000); - expect(res.body.value).toStrictEqual('18887450000000'); - expect(res.body.sender).toStrictEqual('erd1qqqqqqqqqqqqqpgqvc7gdl0p4s97guh498wgz75k8sav6sjfjlwqh679jy'); - expect(res.body.receiver).toStrictEqual('erd1005j3q6tlfcpsqcsw3pe5v5ag5xtfckje3ckkm6h4ef92epjzywq9nqqc3'); - expect(res.body.data).toStrictEqual('QDZmNmI='); - expect(res.body.prevTxHash).toStrictEqual('f01660479c8481a1c07e78508898130e45dc8657bf2fc5c2f377623eb18f734d'); - expect(res.body.originalTxHash).toStrictEqual('f01660479c8481a1c07e78508898130e45dc8657bf2fc5c2f377623eb18f734d'); - expect(res.body.callType).toStrictEqual('0'); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Bad Request if given scHash is not a valid transaction hash', async () => { - const scHash: string = 'bc68da1de1926031f03211dc1610b4513043ccd497fdc09817aa721es20555057'; - - await request(app.getHttpServer()) - .get(`${path}/${scHash}`) - .expect(400) - .then(res => { - expect(res.body.message).toContain("Validation failed"); - }); - }); - - it('should return 404 Not Found', async () => { - const scHash: string = 'bc68da1de1926031f03211dc1610b4513043ccd497fdc09817aa721e2055505T'; - - await request(app.getHttpServer()) - .get(`${path}/${scHash}`) - .expect(404) - .then(res => { - expect(res.body.message).toStrictEqual("Smart contract result not found"); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/shards.controller.e2e-spec.ts b/src/test/integration/controllers/shards.controller.e2e-spec.ts deleted file mode 100644 index 0343c3539..000000000 --- a/src/test/integration/controllers/shards.controller.e2e-spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Shards Controller", () => { - let app: INestApplication; - const path: string = "/shards"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - it("should return all available shards", async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(4); - }); - }); - - it("should return 1 shard details", async () => { - const params = new URLSearchParams({ - 'size': '1', - }); - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body[0].shard).toBeDefined(); - expect(res.body[0].validators).toBeDefined(); - expect(res.body[0].activeValidators).toBeDefined(); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/stake.controller.e2e-spec.ts b/src/test/integration/controllers/stake.controller.e2e-spec.ts deleted file mode 100644 index afb5412ac..000000000 --- a/src/test/integration/controllers/stake.controller.e2e-spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Stake Controller", () => { - let app: INestApplication; - const path: string = "/stake"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - it("should return general staking details", async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body.totalValidators).toBeDefined(); - expect(res.body.activeValidators).toBeDefined(); - expect(res.body.queueSize).toBeDefined(); - expect(res.body.totalStaked).toBeDefined(); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/tags.controller.e2e-spec.ts b/src/test/integration/controllers/tags.controller.e2e-spec.ts index b0b1dd153..0e60e9537 100644 --- a/src/test/integration/controllers/tags.controller.e2e-spec.ts +++ b/src/test/integration/controllers/tags.controller.e2e-spec.ts @@ -1,88 +1,76 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; +import { INestApplication } from "@nestjs/common"; +import { Test } from "@nestjs/testing"; +import { Tag } from "src/endpoints/nfttags/entities/tag"; +import { TagService } from "src/endpoints/nfttags/tag.service"; import request = require('supertest'); -import { URLSearchParams } from 'url'; +import { TagController } from "src/endpoints/nfttags/tag.controller"; +import { TagModule } from "src/endpoints/nfttags/tag.module"; -describe("Tags Controller", () => { +describe('TagController', () => { let app: INestApplication; const path: string = "/tags"; + const tagService = { + getNftTags: jest.fn(), + getNftTagCount: jest.fn(), + getNftTag: jest.fn(), + }; + beforeAll(async () => { const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - + controllers: [TagController], + imports: [TagModule], + }) + .overrideProvider(TagService) + .useValue(tagService) + .compile(); app = moduleRef.createNestApplication(); await app.init(); }); - describe('/tags', () => { - it("should return 25 tags", async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - }); - }); + it(`/GET tags`, async () => { + const mockTags: Tag[] = [{ tag: 'multiversx', count: 48974 }, { tag: 'xPortal', count: 34750 }]; + tagService.getNftTags.mockResolvedValue(mockTags); - it('should return a list of 10 tags that contains "elrond" in tag name ', async () => { - const params = new URLSearchParams({ - 'search': 'elrond', - 'size': '10', - }); + const params = new URLSearchParams({ from: '0', size: '2' }).toString(); - await request(app.getHttpServer()) - .get(`${path}?${params}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(10); - expect(res.body[0].tag).toMatch('elrond'); - }); - }); + await request(app.getHttpServer()) + .get(`${path}?${params}`) + .expect(200) + .expect(mockTags); }); - describe('tags/{tag}', () => { - it('should return NFT tag details for a given tag', async () => { - const tag: string = 'elrond'; + it(`/GET tags/count`, async () => { + tagService.getNftTagCount.mockResolvedValue(10); - await request(app.getHttpServer()) - .get(`${path}/${tag}`) - .expect(200) - .then(res => { - expect(res.body.tag).toMatch('elrond'); - expect(res.body.count).toBeGreaterThanOrEqual(3500); - }); - }); + await request(app.getHttpServer()) + .get(`${path}/count`) + .expect(200) + .expect(response => { + expect(+response.text).toBeGreaterThanOrEqual(10); + }); }); - describe('tags/count', () => { - it('should return total number of NFTs tags', async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(2500); - }); - }); + it(`/GET tags/:tag`, async () => { + const mockTag: Tag = { tag: 'Art', count: 1 }; + tagService.getNftTag.mockResolvedValue(mockTag); - it('should total number of distinct NFT tags', async () => { - const params = new URLSearchParams({ - 'search': 'elrond', - }); + await request(app.getHttpServer()) + .get(`${path}/Art`) + .expect(200) + .expect(mockTag); + }); + + it(`/GET tags/:tag - not found`, async () => { + tagService.getNftTag.mockRejectedValue(new Error('Nft tag not found')); - await request(app.getHttpServer()) - .get(`${path}/count?${params}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(30); - }); - }); + await request(app.getHttpServer()) + .get('/tags/invalidTag') + .expect(404); }); - afterEach(async () => { + afterAll(async () => { await app.close(); }); }); diff --git a/src/test/integration/controllers/tokens.controller.e2e-spec.ts b/src/test/integration/controllers/tokens.controller.e2e-spec.ts deleted file mode 100644 index 434300adf..000000000 --- a/src/test/integration/controllers/tokens.controller.e2e-spec.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Tokens Controller", () => { - let app: INestApplication; - const path: string = "/tokens"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - - await app.init(); - }); - - - describe('/tokens', () => { - [ - { - filter: undefined, - value: undefined, - length: 25, - }, - { - filter: 'size', - value: '5', - length: 5, - }, - ].forEach(({ filter, value, length }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return ${length} tokens based on value ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}?${filter}=${value}`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(parseInt(`${length}`)); - }); - }); - }); - }); - - [ - { - filter: 'search', - value: 'MEX-455c57', - }, - { - filter: 'name', - value: 'MEX', - }, - { - filter: 'identifier', - value: 'MEX-455c57', - }, - { - filter: 'identifiers', - value: 'MEX-455c57', - }, - ].forEach(({ filter, value }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return token details based on value ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}?${filter}=${value}`) - .expect(200) - .then(res => { - expect(res.body).toBeDefined(); - expect(res.body[0].identifier).toStrictEqual('MEX-455c57'); - expect(res.body[0].owner).toStrictEqual('erd1ss6u80ruas2phpmr82r42xnkd6rxy40g9jl69frppl4qez9w2jpsqj8x97'); - expect(res.body[0].assets).toBeDefined(); - }); - }); - }); - }); - - [ - { - filter: 'sort', - value: 'accounts', - }, - { - filter: 'sort', - value: 'transactions', - }, - { - filter: 'sort', - value: 'price', - }, - ].forEach(({ filter, value }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return tokens details based on ${filter} with value ${value} and ordered descendent `, async () => { - const order = 'desc'; - - await request(app.getHttpServer()) - .get(`${path}?${filter}=${value}&${order}`) - .expect(200) - .then(res => { - expect(res.body).toBeDefined(); - expect(res.body[0].transactions).toBeGreaterThan(res.body[1].transactions); - }); - }); - }); - }); - }); - - describe('/tokens/count', () => { - [ - { - filter: 'name', - value: 'MEX', - count: 1, - }, - { - filter: 'identifier', - value: 'MEX-455c57', - count: 1, - }, - ].forEach(({ filter, value, count }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return tokens count based on ${filter} with value ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}/count?${filter}=${value}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); - - describe('/tokens/{identifier}', () => { - it('should return token details based on a specific token identifier', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(200) - .then(res => { - expect(res.body.identifier).toStrictEqual(identifier); - expect(res.body.name).toStrictEqual('MEX'); - expect(res.body.ticker).toStrictEqual('MEX'); - expect(res.body.owner).toStrictEqual('erd1ss6u80ruas2phpmr82r42xnkd6rxy40g9jl69frppl4qez9w2jpsqj8x97'); - expect(res.body.decimals).toStrictEqual(18); - expect(res.body.isPaused).toStrictEqual(false); - expect(res.body.transactions).toBeGreaterThanOrEqual(1504696); - expect(res.body.accounts).toBeGreaterThanOrEqual(11021); - expect(res.body.assets).toBeDefined(); - - expect(res.body.canUpgrade).toStrictEqual(true); - expect(res.body.canMint).toStrictEqual(true); - expect(res.body.canBurn).toStrictEqual(true); - expect(res.body.canChangeOwner).toStrictEqual(true); - expect(res.body.canPause).toStrictEqual(true); - expect(res.body.canFreeze).toStrictEqual(true); - expect(res.body.canWipe).toStrictEqual(true); - }); - }); - - it('should returns general supply information for a specific token', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/supply`) - .expect(200) - .then(res => { - expect(res.body).toBeDefined(); - expect(res.body.supply).toBeDefined(); - expect(res.body.circulatingSupply).toBeDefined(); - expect(res.body.minted).toBeDefined(); - expect(res.body.burnt).toBeDefined(); - expect(res.body.initialMinted).toBeDefined(); - }); - }); - - it('should returns general supply information for a specific token', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/supply`) - .expect(200) - .then(res => { - expect(res.body).toBeDefined(); - expect(res.body.supply).toBeDefined(); - expect(res.body.circulatingSupply).toBeDefined(); - expect(res.body.minted).toBeDefined(); - expect(res.body.burnt).toBeDefined(); - expect(res.body.initialMinted).toBeDefined(); - }); - }); - - it('should returns a list of accounts that hold a specific token', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/accounts`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(25); - expect(res.body[0].address).toStrictEqual('erd1qqqqqqqqqqqqqpgqa0fsfshnff4n76jhcye6k7uvd7qacsq42jpsp6shh2'); - }); - }); - - it('should returns the total number of accounts that hold a specific token', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/accounts/count`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(50679); - }); - }); - - it('should return a list of accounts that can perform various actions on a specific token', async () => { - const identifier: string = 'MEX-455c57'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/roles`) - .expect(200) - .then(res => { - expect(res.body).toHaveLength(21); - - for (const item of res.body) { - expect(item.address).toBeDefined(); - expect(item.canLocalMint).toBeDefined(); - expect(item.canLocalBurn).toBeDefined(); - expect(item.roles).toBeDefined(); - } - }); - }); - - it('should returns roles detalils for a specific address of a given token', async () => { - const identifier: string = 'MEX-455c57'; - const address: string = 'erd1qqqqqqqqqqqqqpgqjpt0qqgsrdhp2xqygpjtfrpwf76f9nvg2jpsg4q7th'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}/roles/${address}`) - .expect(200) - .then(res => { - expect(res.body.canLocalMint).toStrictEqual(true); - expect(res.body.canLocalBurn).toStrictEqual(true); - expect(res.body.roles[0]).toStrictEqual('ESDTRoleLocalMint'); - expect(res.body.roles[1]).toStrictEqual('ESDTRoleLocalBurn'); - }); - }); - }); - - describe('Validations', () => { - it('should return 400 Status Code if given token identifier is invalid', async () => { - const identifier: string = 'abc123'; - - await request(app.getHttpServer()) - .get(`${path}/${identifier}`) - .expect(400) - .then(res => { - expect(res.body.message).toEqual("Validation failed for argument 'identifier': Invalid token identifier."); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/transactions.controller.e2e-spec.ts b/src/test/integration/controllers/transactions.controller.e2e-spec.ts deleted file mode 100644 index 7f5654c91..000000000 --- a/src/test/integration/controllers/transactions.controller.e2e-spec.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { BinaryUtils } from '@multiversx/sdk-nestjs-common'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Transactions Controller", () => { - let app: INestApplication; - const path: string = "/transactions"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - [ - { - filter: 'sender', - value: '4294967295', - }, - { - filter: 'sender', - value: 'erd1576w79rz7zq8jv5nuzrnntghrxjnzapjppcv6u7pya257gk9x9eq59qrhu', - }, - ].forEach(({ filter, value }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return transaction sender with value ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}?${filter}=${value}`) - .expect(200) - .then(res => { - expect(res.body).toBeDefined(); - expect(res.body[0].sender).toStrictEqual(value); - }); - }); - }); - }); - - [ - { - filter: 'sender', - value: '4294967295', - count: 12900, - }, - { - filter: 'sender', - value: 'erd1576w79rz7zq8jv5nuzrnntghrxjnzapjppcv6u7pya257gk9x9eq59qrhu', - count: 189, - }, - { - filter: 'isRelayed', - value: 'true', - count: 3060906, - }, - ].forEach(({ filter, value, count }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return total number of transactions of sender ${value}`, async () => { - await request(app.getHttpServer()) - .get(`${path}/count?${filter}=${value}`) - .expect(200) - .then(res => { - expect(+res.text).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - - [ - { - filter: 'isRelayed', - value: 'true', - }, - ].forEach(({ filter, value }) => { - describe(`when filter ${filter} is applied`, () => { - it(`should return all transactions with relayedTx`, async () => { - await request(app.getHttpServer()) - .get(`${path}?${filter}=${value}`) - .expect(200) - .then(res => { - for (const item of res.body) { - const decodedData = BinaryUtils.base64Decode(item.data); - expect(decodedData).toContain('relayedTx'); - expect(item.isRelayed).toBeDefined(); - } - }); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/username.controller.e2e-spec.ts b/src/test/integration/controllers/username.controller.e2e-spec.ts deleted file mode 100644 index 043168ea5..000000000 --- a/src/test/integration/controllers/username.controller.e2e-spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Username Controller", () => { - let app: INestApplication; - const path: string = "/usernames"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - await app.init(); - }); - - describe('/usernames/{username}', () => { - it('should return account details for a given username', async () => { - const username: string = 'alice'; - - await request(app.getHttpServer()) - .get(`${path}/${username}`) - .expect(302); - }); - }); - - describe('Validations', () => { - it('should return code 404 Not Found and response message', async () => { - const username: string = 'InvalidUsername'; - - await request(app.getHttpServer()) - .get(`${path}/${username}`) - .expect(404) - .then(res => { - expect(res.body.message).toStrictEqual('Account not found'); - }); - }); - }); - - afterEach(async () => { - await app.close(); - }); -}); diff --git a/src/test/integration/controllers/vmQuery.controller.e2e-spec.ts b/src/test/integration/controllers/vmQuery.controller.e2e-spec.ts deleted file mode 100644 index 7c01d5da5..000000000 --- a/src/test/integration/controllers/vmQuery.controller.e2e-spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { BadRequestException } from "@nestjs/common"; -import { TestingModule, Test } from "@nestjs/testing"; -import { VmQueryController } from "src/endpoints/vm.query/vm.query.controller"; -import { VmQueryService } from "src/endpoints/vm.query/vm.query.service"; - -describe('VmQueryController', () => { - let vmQueryController: VmQueryController; - let vmQueryService: VmQueryService; - - beforeEach(async () => { - const module: TestingModule = await Test.createTestingModule({ - controllers: [VmQueryController], - providers: [ - { - provide: VmQueryService, - useValue: { - vmQueryFullResult: jest.fn(), - }, - }, - ], - }).compile(); - - vmQueryController = module.get(VmQueryController); - vmQueryService = module.get(VmQueryService); - }); - - it('should be defined', () => { - expect(vmQueryController).toBeDefined(); - }); - - describe('query', () => { - it('should return the data if the vm query is successful', async () => { - const mockResult = { - data: { - data: { - returnData: 'dummy data', - }, - }, - }; - jest.spyOn(vmQueryService, 'vmQueryFullResult').mockResolvedValue(mockResult); - - const result = await vmQueryController.query({ - scAddress: 'dummy', - funcName: 'dummy', - caller: 'dummy', - args: [], - value: 'dummy', - }); - - expect(result).toEqual(mockResult.data.data); - }); - - it('should throw a BadRequestException if the vm query fails', async () => { - const mockResult = { - data: { - data: { - returnData: null, - returnCode: 'dummy code', - returnMessage: 'dummy message', - }, - }, - }; - jest.spyOn(vmQueryService, 'vmQueryFullResult').mockResolvedValue(mockResult); - - await expect( - vmQueryController.query({ - scAddress: 'dummy', - funcName: 'dummy', - caller: 'dummy', - args: [], - value: 'dummy', - }) - ).rejects.toThrow(BadRequestException); - }); - }); -}); diff --git a/src/test/integration/controllers/waiting-list.controller.e2e-spec.ts b/src/test/integration/controllers/waiting-list.controller.e2e-spec.ts deleted file mode 100644 index 748a03a14..000000000 --- a/src/test/integration/controllers/waiting-list.controller.e2e-spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import request = require('supertest'); - -describe("Waiting-List Controller", () => { - let app: INestApplication; - const path: string = "/waiting-list"; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - - await app.init(); - }); - - it("/waiting-list - should return 200 status code and one list of accounts in waiting-list", async () => { - await request(app.getHttpServer()) - .get(`${path}`) - .expect(200); - }); - - it("/waiting-list/count - should return 200 status code and waiting-lists total count", async () => { - await request(app.getHttpServer()) - .get(`${path}/count`) - .expect(200); - }); - - it("/waiting-list/c - should return 200 status code and waiting-lists total count (alternative)", async () => { - await request(app.getHttpServer()) - .get(`${path}/c`) - .expect(200); - }); - - afterEach(async () => { - await app.close(); - }); -}); From 31b3d06c70984299037a312905895d37e0a2f743 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 11:58:25 +0200 Subject: [PATCH 02/30] remove graphql e2e tests --- .../graphql/accounts.graph-spec.ts | 224 ---------- .../integration/graphql/blocks.graph-spec.ts | 183 -------- .../graphql/collections,graph-spec.ts | 230 ---------- .../graphql/dapp.config.graph-spec.ts | 52 --- .../graphql/delegation.graph-spec.ts | 47 --- .../graphql/maiar.exchange.graph-spec.ts | 258 ------------ .../graphql/miniBlocks.graph-spec.ts | 76 ---- .../integration/graphql/network.graph-spec.ts | 109 ----- .../integration/graphql/nfts.graph-spec.ts | 262 ------------ .../graphql/providers.graph-spec.ts | 83 ---- .../integration/graphql/rounds.graph-spec.ts | 167 -------- .../integration/graphql/shard.graph-spec.ts | 47 --- .../smart.contract.result.graph-spec.ts | 169 -------- .../integration/graphql/stake.graph-spec.ts | 43 -- .../integration/graphql/tags.graph-spec.ts | 60 --- .../integration/graphql/tokens.graph-spec.ts | 393 ------------------ .../graphql/transactions.graph-spec.ts | 268 ------------ .../graphql/username.graph-spec.ts | 50 --- .../graphql/waiting.list.graph-spec.ts | 48 --- .../graphql/websocket.graph-spec.ts | 41 -- 20 files changed, 2810 deletions(-) delete mode 100644 src/test/integration/graphql/accounts.graph-spec.ts delete mode 100644 src/test/integration/graphql/blocks.graph-spec.ts delete mode 100644 src/test/integration/graphql/collections,graph-spec.ts delete mode 100644 src/test/integration/graphql/dapp.config.graph-spec.ts delete mode 100644 src/test/integration/graphql/delegation.graph-spec.ts delete mode 100644 src/test/integration/graphql/maiar.exchange.graph-spec.ts delete mode 100644 src/test/integration/graphql/miniBlocks.graph-spec.ts delete mode 100644 src/test/integration/graphql/network.graph-spec.ts delete mode 100644 src/test/integration/graphql/nfts.graph-spec.ts delete mode 100644 src/test/integration/graphql/providers.graph-spec.ts delete mode 100644 src/test/integration/graphql/rounds.graph-spec.ts delete mode 100644 src/test/integration/graphql/shard.graph-spec.ts delete mode 100644 src/test/integration/graphql/smart.contract.result.graph-spec.ts delete mode 100644 src/test/integration/graphql/stake.graph-spec.ts delete mode 100644 src/test/integration/graphql/tags.graph-spec.ts delete mode 100644 src/test/integration/graphql/tokens.graph-spec.ts delete mode 100644 src/test/integration/graphql/transactions.graph-spec.ts delete mode 100644 src/test/integration/graphql/username.graph-spec.ts delete mode 100644 src/test/integration/graphql/waiting.list.graph-spec.ts delete mode 100644 src/test/integration/graphql/websocket.graph-spec.ts diff --git a/src/test/integration/graphql/accounts.graph-spec.ts b/src/test/integration/graphql/accounts.graph-spec.ts deleted file mode 100644 index 970a6e036..000000000 --- a/src/test/integration/graphql/accounts.graph-spec.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Accounts', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Accounts', () => { - it('should return 25 accounts', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ accounts(input:{ - size: 25 - }){ - address - balance - nonce - shard - assets{ - name - description - tags - iconPng - iconSvg - } - } - }`, - }) - .expect(200) - .then(res => { - for (const item of res.body.data.accounts) { - expect(item.address).toBeDefined(); - } - expect(res.body.data.accounts).toBeDefined(); - expect(res.body.data.accounts).toHaveLength(25); - }); - }); - }); - - describe('Query - Get Account', () => { - it('should return account details for a given address', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ account(input:{ - address: "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz" - }){ - address - balance - nonce - shard - rootHash - txCount - scrCount - username - developerReward - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account).toBeDefined(); - }); - }); - }); - - describe('Query - Get Accounts Count', () => { - it('should return total number of accounts', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ accountsCount(input: {}) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.accountsCount).toBeGreaterThanOrEqual(1797710); - }); - }); - }); - - describe('Query - Get Account smart contracts results Count', () => { - it('should return total number of smart contracts results', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - account(input:{ - address: "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz" - }){ - scrCount - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account.scrCount).toBeGreaterThanOrEqual(41); - }); - }); - }); - - describe('Query - Get account transactions count', () => { - it('should return total number of transactions', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - account(input:{ - address: "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz" - }){ - txCount - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account.txCount).toBeGreaterThanOrEqual(32); - }); - }); - }); - - describe('Query - Get account contracts count', () => { - it('should return total number of contracts', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - account(input:{ - address: "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz" - }){ - contractAccountCount - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account.contractAccountCount).toBeGreaterThanOrEqual(0); - }); - }); - }); - - describe('Query - Get account stake details', () => { - it('should return total staked amount for the given provider ', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - account(input:{ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc0llllsayxegu" - }){ - stake{ - totalStaked - unstakedTokens{ - amount - epochs - expires - } - } - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account.stake).toBeDefined(); - expect(res.body.data.account.stake.totalStaked).toBeDefined(); - expect(res.body.data.account.stake.unstakedTokens).toBeDefined(); - }); - }); - }); - - describe('Query - Get account keys details', () => { - it('should return all active/queued nodes where given account is owner ', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - account(input:{ - address: "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc0llllsayxegu" - }){ - keys{ - blsKey - queueIndex - queueSize - rewardAddress - stake - status - topUp - } - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.account.keys).toBeDefined(); - for (const item of res.body.data.account.keys) { - expect(item.blsKey).toBeDefined(); - expect(item.queueIndex).toBeDefined(); - expect(item.queueSize).toBeDefined(); - expect(item.rewardAddress).toBeDefined(); - expect(item.stake).toBeDefined(); - expect(item.status).toBeDefined(); - expect(item.topUp).toBeDefined(); - } - }); - }); - }); - -}); diff --git a/src/test/integration/graphql/blocks.graph-spec.ts b/src/test/integration/graphql/blocks.graph-spec.ts deleted file mode 100644 index 816fd2468..000000000 --- a/src/test/integration/graphql/blocks.graph-spec.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Blocks', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Blocks', () => { - it('should returns a list of all blocks from all shards', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - blocks(input:{ - }){ - hash - epoch - nonce - prevHash - proposer - pubKeyBitmap - round - shard - size - sizeTxs - stateRootHash - timestamp - txCount - gasConsumed - gasRefunded - gasPenalized - maxGasLimit - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.blocks).toBeDefined(); - }); - }); - - it('should returns a list of all blocks from shard 2 and epoch 79 and nonce 1151901', async () => { - const blocksFilter = { - shard: 2, - epoch: 79, - nonce: 1151901, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - blocks(input:{ - shard: ${blocksFilter.shard}, epoch: ${blocksFilter.epoch}, nonce: ${blocksFilter.nonce} - }){ - hash - epoch - nonce - prevHash - proposer - pubKeyBitmap - round - shard - size - sizeTxs - stateRootHash - timestamp - txCount - gasConsumed - gasRefunded - gasPenalized - maxGasLimit - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.blocks).toBeDefined(); - expect(res.body.data.blocks[0].epoch).toStrictEqual(79); - expect(res.body.data.blocks[0].nonce).toStrictEqual(1151901); - expect(res.body.data.blocks[0].shard).toStrictEqual(2); - }); - }); - }); - - describe('Query - Get Block', () => { - it('should returns block information details for a given hash.', async () => { - const blockHash = { - hash: `"a7edf0f43819fb6205c77a04f65d9e301f6d7bf1c44fc0e6e1225a401fee5011"`, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - blockHash(input:{ - hash: ${blockHash.hash} - }){ - hash - epoch - nonce - prevHash - proposer - pubKeyBitmap - round - shard - size - sizeTxs - stateRootHash - timestamp - txCount - gasConsumed - gasRefunded - gasPenalized - maxGasLimit - validators - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.blockHash).toBeDefined(); - expect(res.body.data.blockHash.hash).toStrictEqual('a7edf0f43819fb6205c77a04f65d9e301f6d7bf1c44fc0e6e1225a401fee5011'); - }); - }); - }); - - describe('Query - Get Blocks Count', () => { - [ - { - filter: 'shard', - value: 2, - count: 1069686, - }, - { - filter: 'epoch', - value: 79, - count: 57571, - }, - { - filter: 'proposer', - value: `"11f3b1f7aba458061ba7bdc51291494ef0555016c121de5ed1c2ef464487ca3fe263e11a0762d524c10d1c82dd72490c143956ad48a419f26cc65cfff154a7a32cd4d89b06bf5d39700717485fa6a65cf2443257bb1676b38e5323b7b0435892"`, - count: 957032, - }, - { - filter: 'nonce', - value: 1151901, - count: 2, - }, - ].forEach(({ filter, value, count }) => { - describe(`filter = ${filter}`, () => { - it(`should return total count based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - blocksCount(input:{ - ${filter}: ${value} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.blocksCount).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/collections,graph-spec.ts b/src/test/integration/graphql/collections,graph-spec.ts deleted file mode 100644 index 3500c7183..000000000 --- a/src/test/integration/graphql/collections,graph-spec.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Collection', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Collection Details', () => { - it('should return collection details for a given NonFungibleESDT collection identifier', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - collection(input:{ - collection: "MEDAL-ae074f" - }){ - collection - type - name - ticker - owner{ - address - } - timestamp - canFreeze - canWipe - canPause - canTransferNftCreateRole - canChangeOwner - canUpgrade - canAddSpecialRoles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collection).toBeDefined(); - expect(res.body.data.collection.collection).toStrictEqual('MEDAL-ae074f'); - expect(res.body.data.collection.type).toStrictEqual('NonFungibleESDT'); - }); - }); - }); - - describe('Query - Get Collections Details', () => { - it('should return 25 collections details', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - collections(input:{ - size:25}){ - collection - type - name - ticker - owner{ - address - } - timestamp - canFreeze - canWipe - canPause - canTransferNftCreateRole - canChangeOwner - canUpgrade - canAddSpecialRoles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collections).toBeDefined(); - expect(res.body.data.collections).toHaveLength(25); - }); - }); - - test.each` - types - ${'NonFungibleESDT'} - ${'SemiFungibleESDT'} - ${'MetaESDT'} - ` - ( - `for the given collection type $types, should return 25 collections`, async ({ types }) => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - collections(input:{ - type:${types}}){ - collection - type - name - ticker - owner{ - address - } - timestamp - canFreeze - canWipe - canPause - canTransferNftCreateRole - canChangeOwner - canUpgrade - canAddSpecialRoles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collections).toHaveLength(25); - for (const item of res.body.data.collections) { - expect(item.type).toStrictEqual(types); - } - }); - } - ); - - it('should return 2 collections details for a given collection identifiers', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - collections(input:{ - identifiers:["MEDAL-ae074f","EROBOT-527a29"] - }){ - collection - type - name - ticker - owner{ - address - } - timestamp - canFreeze - canWipe - canPause - canTransferNftCreateRole - canChangeOwner - canUpgrade - canAddSpecialRoles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collections).toHaveLength(2); - expect(res.body.data.collections[0].collection).toStrictEqual('MEDAL-ae074f'); - expect(res.body.data.collections[1].collection).toStrictEqual('EROBOT-527a29'); - - }); - }); - - [ - { - type: 'NonFungibleESDT', - value: '5126', - }, - { - type: 'SemiFungibleESDT', - value: '920', - }, - { - type: 'MetaESDT', - value: '30', - }, - ].forEach(({ type, value }) => { - describe(`when filter ${type} is applied`, () => { - it(`should return collection count`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{collectionsCount(input:{ - type: ${type} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collectionsCount).toBeGreaterThanOrEqual(parseInt(value)); - }); - }); - }); - }); - }); - - [ - { - boolean: true, - value: '7376', - }, - { - boolean: false, - value: '7440', - }, - ].forEach(({ value, boolean }) => { - describe(`Query - Get Collections Count (with/without excludeMetaESDT filter applied)`, () => { - it(`should return collection count`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - collectionsCount(input:{ - excludeMetaESDT: ${boolean} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.collectionsCount).toBeGreaterThanOrEqual(parseInt(value)); - }); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/dapp.config.graph-spec.ts b/src/test/integration/graphql/dapp.config.graph-spec.ts deleted file mode 100644 index 82209dc4d..000000000 --- a/src/test/integration/graphql/dapp.config.graph-spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('DappConfig', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Configuration used in dapps', () => { - it('should return dapp configuration', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - dappConfig{ - id - name - egldLabel - decimals - egldDenomination - gasPerDataByte - apiTimeout - walletConnectDeepLink - walletConnectBridgeAddresses - walletAddress - apiAddress - explorerAddress - chainId - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.dappConfig).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/delegation.graph-spec.ts b/src/test/integration/graphql/delegation.graph-spec.ts deleted file mode 100644 index b8ac5320e..000000000 --- a/src/test/integration/graphql/delegation.graph-spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Delegation', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Delegation details', () => { - it('should return delegation staking contract information', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - delegation{ - stake - topUp - locked - minDelegation - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.delegation).toBeDefined(); - expect(res.body.data.delegation.stake).toBeDefined(); - expect(res.body.data.delegation.topUp).toBeDefined(); - expect(res.body.data.delegation.locked).toBeDefined(); - expect(res.body.data.delegation.minDelegation).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/maiar.exchange.graph-spec.ts b/src/test/integration/graphql/maiar.exchange.graph-spec.ts deleted file mode 100644 index d8d3ce71b..000000000 --- a/src/test/integration/graphql/maiar.exchange.graph-spec.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('xExchange', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Mex Economics', () => { - it('should returns economics details of xExchange', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexEconomics{ - totalSupply - circulatingSupply - price - marketCap - volume24h - marketPairs - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexEconomics).toBeDefined(); - }); - }); - }); - - describe('Query - Get Mex Pairs', () => { - it('should returns economics details of xExchange', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexPairs(input:{ - }){ - address - id - symbol - name - price - baseId - basePrice - baseSymbol - baseName - quoteId - quotePrice - quoteSymbol - quoteName - totalValue - volume24h - state - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexPairs).toBeDefined(); - }); - }); - }); - - describe('Query - Get Mex Pair', () => { - it('should returns liquidity pool details by providing a combination of two tokens', async () => { - const mexPairInput = { - baseId: `"MEX-455c57"`, - quoteId: `"WEGLD-bd4d79"`, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexPair(input:{ - baseId: ${mexPairInput.baseId}, quoteId: ${mexPairInput.quoteId} - }){ - address - id - symbol - name - price - baseId - basePrice - baseSymbol - baseName - quoteId - quotePrice - quoteSymbol - quoteName - totalValue - volume24h - state - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexPair).toBeDefined(); - }); - }); - - it('should returns "Mex pair not found" if baseId or quoteId are not found', async () => { - const mexPairInput = { - baseId: `"Invalid-455c57"`, - quoteId: `"WEGLD-bd4d79"`, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexPair(input:{ - baseId: ${mexPairInput.baseId}, quoteId: ${mexPairInput.quoteId} - }){ - address - id - symbol - name - price - baseId - basePrice - baseSymbol - baseName - quoteId - quotePrice - quoteSymbol - quoteName - totalValue - volume24h - state - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.errors[0].message).toStrictEqual('Mex pair not found'); - }); - }); - }); - - describe('Query - Get Mex Tokens', () => { - it('should returns a list of tokens listed on xExchange', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexTokens(input:{ - }){ - id - symbol - name - price - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexTokens).toBeDefined(); - }); - }); - - it('should returns a list of tokens listed on xExchange', async () => { - const mexTokenIdentifier = { - id: `"MEX-455c57"`, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexToken(input:{ - id: ${mexTokenIdentifier.id} - }){ - id - symbol - name - price - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexToken.id).toStrictEqual('MEX-455c57'); - }); - }); - - it('should returns "Mex token not found" if token identifier is not valid', async () => { - const mexTokenIdentifier = { - id: `"Invalid-455c57"`, - }; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexToken(input:{ - id: ${mexTokenIdentifier.id} - }){ - id - symbol - name - price - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.errors[0].message).toStrictEqual('Mex token not found'); - expect(res.body.errors[0].extensions.code).toStrictEqual('404'); - }); - }); - }); - - describe('Query - Get Mex Farms', () => { - it('should returns a list of farms listed on xExchange', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - mexFarms(input:{ - }){ - type - address - id - symbol - name - price - farmingId - farmingSymbol - farmingName - farmingPrice - farmedId - farmedSymbol - farmedName - farmedPrice - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.mexFarms).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/miniBlocks.graph-spec.ts b/src/test/integration/graphql/miniBlocks.graph-spec.ts deleted file mode 100644 index a11b0cb52..000000000 --- a/src/test/integration/graphql/miniBlocks.graph-spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('MiniBlocks', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get MiniBlock', () => { - it('should returns miniblock details for a given miniBlockHash.', async () => { - const miniBlockHash: string = `"e336ba1b720bb153b4e0d2049d722b0e39bf275f9d35e79b0f757271a963ad4c"`; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - miniBlockHash(input:{ - miniBlockHash: ${miniBlockHash} - }){ - miniBlockHash - receiverBlockHash - receiverShard - senderBlockHash - senderShard - timestamp - type - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.miniBlockHash).toBeDefined(); - expect(res.body.data.miniBlockHash.miniBlockHash).toStrictEqual('e336ba1b720bb153b4e0d2049d722b0e39bf275f9d35e79b0f757271a963ad4c'); - }); - }); - - it('should return "Miniblock not found" .', async () => { - const miniBlockHash: string = `"e336ba1b720bb153b4e0d2049d722b0e39bf275f9d35e79b0f757271a963ad4"`; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - miniBlockHash(input:{ - miniBlockHash: ${miniBlockHash} - }){ - miniBlockHash - receiverBlockHash - receiverShard - senderBlockHash - senderShard - timestamp - type - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.errors[0].message).toStrictEqual('Miniblock not found'); - expect(res.body.errors[0].extensions.code).toStrictEqual("404"); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/network.graph-spec.ts b/src/test/integration/graphql/network.graph-spec.ts deleted file mode 100644 index d73c1a0f5..000000000 --- a/src/test/integration/graphql/network.graph-spec.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Network', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Constants', () => { - it('should returns network-specific constants that can be used to automatically configure dapps', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - constants{ - chainId - gasPerDataByte - minGasLimit - minGasPrice - minTransactionVersion - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.constants.chainId).toBeDefined(); - expect(res.body.data.constants.gasPerDataByte).toBeDefined(); - expect(res.body.data.constants.minGasLimit).toBeDefined(); - expect(res.body.data.constants.minGasPrice).toBeDefined(); - expect(res.body.data.constants.minTransactionVersion).toBeDefined(); - }); - }); - }); - - describe('Query - Get Economics', () => { - it('should returns general economics information', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - economics{ - totalSupply - circulatingSupply - staked - apr - topUpApr - baseApr - tokenMarketCap - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.economics.totalSupply).toBeDefined(); - expect(res.body.data.economics.circulatingSupply).toBeDefined(); - expect(res.body.data.economics.apr).toBeDefined(); - expect(res.body.data.economics.topUpApr).toBeDefined(); - expect(res.body.data.economics.baseApr).toBeDefined(); - expect(res.body.data.economics.tokenMarketCap).toBeDefined(); - }); - }); - }); - - describe('Query - Get Stats', () => { - it('should returns general network statistics', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - stats{ - shards - blocks - accounts - transactions - refreshRate - epoch - roundsPassed - roundsPerEpoch - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.stats.shards).toBeDefined(); - expect(res.body.data.stats.blocks).toBeDefined(); - expect(res.body.data.stats.accounts).toBeDefined(); - expect(res.body.data.stats.transactions).toBeDefined(); - expect(res.body.data.stats.refreshRate).toBeDefined(); - expect(res.body.data.stats.epoch).toBeDefined(); - expect(res.body.data.stats.roundsPassed).toBeDefined(); - expect(res.body.data.stats.roundsPerEpoch).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/nfts.graph-spec.ts b/src/test/integration/graphql/nfts.graph-spec.ts deleted file mode 100644 index 7ca4d9b2c..000000000 --- a/src/test/integration/graphql/nfts.graph-spec.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Nfts', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get NFT details', () => { - it('should return NonFungibleESDT token details for a given NFT identifier', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - nft(input:{ - identifier:"CATSFAM-46c28f-0211" - }){ - identifier - attributes - nonce - type - name - creator{ - address - } - royalties - uris - url - media{ - url - originalUrl - thumbnailUrl - fileType - fileSize - } - isWhitelistedStorage - owner{ - address - } - supply - ticker - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.nft).toBeDefined(); - expect(res.body.data.nft.identifier).toStrictEqual('CATSFAM-46c28f-0211'); - }); - }); - - describe('Query - Get NFT details', () => { - it('should return MetaESDT token details for a given MetaESDT identifier', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - nft(input:{ - identifier:"XMEX-fda355-15" - }){ - identifier - attributes - nonce - type - name - creator{ - address - } - royalties - uris - url - media{ - url - originalUrl - thumbnailUrl - fileType - fileSize - } - isWhitelistedStorage - owner{ - address - } - supply - ticker - unlockEpoch - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.nft).toBeDefined(); - expect(res.body.data.nft.identifier).toStrictEqual('XMEX-fda355-15'); - expect(res.body.data.nft.unlockEpoch).toStrictEqual(1410); - }); - }); - }); - - test.each` - types - ${'NonFungibleESDT'} - ${'SemiFungibleESDT'}` - ( - `for the given type $types, should return 10 esdt tokens`, async ({ types }) => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - nfts(input:{ - type: ${types}, size:10 - }){ - identifier - timestamp - attributes - nonce - type - name - creator{ - address - } - royalties - url - media{ - url - originalUrl - thumbnailUrl - fileType - fileSize - } - isWhitelistedStorage - tags - ticker - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.nfts).toHaveLength(10); - for (const item of res.body.data.nfts) { - expect(item.type).toStrictEqual(types); - } - }); - } - ); - - it('should return NonFugibleESDTs details based on two NFT identifiers', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - nfts(input:{ - identifiers: ["MOS-b9b4b2-2710", "MEDAL-ae074f-78"] - }){ - identifier - timestamp - attributes - nonce - type - name - creator{ - address - } - royalties - url - media{ - url - originalUrl - thumbnailUrl - fileType - fileSize - } - isWhitelistedStorage - tags - ticker - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.nfts).toBeDefined(); - expect(res.body.data.nfts[0].identifier).toStrictEqual('MEDAL-ae074f-78'); - expect(res.body.data.nfts[1].identifier).toStrictEqual('MOS-b9b4b2-2710'); - }); - }); - }); - - describe('Query - Get Count', () => { - [ - { - filter: 'type', - value: 'NonFungibleESDT', - count: 991113, - }, - { - filter: 'type', - value: 'SemiFungibleESDT', - count: 23101, - }, - { - filter: 'isWhitelistedStorage', - value: 'true', - count: 733653, - }, - { - filter: 'hasUris', - value: 'true', - count: 928696, - }, - { - filter: 'isNsfw', - value: 'true', - count: 287, - }, - { - filter: 'before', - value: '1660114204', - count: 1008974, - }, - { - filter: 'after', - value: '1660134204', - count: 2, - }, - { - filter: 'nonce', - value: '200', - count: 200, - }, - - ].forEach(({ filter, value, count }) => { - describe(`filter = ${filter}`, () => { - it(`should return total count based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{nftsCount(input:{ - ${filter}: ${value} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.nftsCount).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/providers.graph-spec.ts b/src/test/integration/graphql/providers.graph-spec.ts deleted file mode 100644 index b56741990..000000000 --- a/src/test/integration/graphql/providers.graph-spec.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Providers', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Providers', () => { - it('should returns provider details based on address', async () => { - const address: string = `"erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc0llllsayxegu"`; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - provider(input:{ - address: ${address} - }){ - provider - serviceFee - delegationCap - apr - numUsers - cumulatedRewards - identity - numNodes - stake - topUp - locked - featured - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.provider).toBeDefined(); - expect(res.body.data.provider.provider).toStrictEqual("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc0llllsayxegu"); - }); - }); - - it('should returns a list of all providers', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - providers(input:{ - }){ - provider - serviceFee - delegationCap - apr - numUsers - cumulatedRewards - identity - numNodes - stake - topUp - locked - featured - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.providers).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/rounds.graph-spec.ts b/src/test/integration/graphql/rounds.graph-spec.ts deleted file mode 100644 index f63da657e..000000000 --- a/src/test/integration/graphql/rounds.graph-spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Rounds', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Rounds', () => { - it('should returns a list of 10 rounds available on blockchain', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - rounds(input:{ - size: 10 - }){ - blockWasProposed - round - epoch - timestamp - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.rounds).toBeDefined(); - expect(res.body.data.rounds).toHaveLength(10); - - for (const item of res.body.data.rounds) { - expect(item.blockWasProposed).toBeDefined(); - expect(item.round).toBeDefined(); - expect(item.epoch).toBeDefined(); - expect(item.timestamp).toBeDefined(); - } - }); - }); - }); - - describe('Query - Get Rounds with filters applied', () => { - [ - { - filter: 'validator', - value: '"014f8602f899c42bb485edff240e1b4ad90a0d9cb029331619ca7b4378e18dc423899adfbf318001e11d5a1c865dd11556bb2172d8912f5a9f86bfad45d503d7c9fa3d082f919181e4c15f8231137c8393186998ee3143b8b5d43e444a8fca07"', - }, - { - filter: 'shard', - value: 1, - }, - { - filter: 'epoch', - value: 594, - }, - - ].forEach(({ filter, value }) => { - describe(`with filter = ${filter}`, () => { - it(`should return rounds details based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - rounds(input:{ - ${filter}: ${value} - }){ - blockWasProposed - round - epoch - timestamp - } - }`, - }) - .then(res => { - expect(res.body.data.rounds).toBeDefined(); - for (const item of res.body.data.rounds) { - expect(item.blockWasProposed).toBeDefined(); - expect(item.round).toBeDefined(); - expect(item.epoch).toBeDefined(); - expect(item.timestamp).toBeDefined(); - } - }); - }); - }); - }); - }); - - describe('Query - Get Rounds count with filters applied', () => { - [ - { - filter: 'validator', - value: '"014f8602f899c42bb485edff240e1b4ad90a0d9cb029331619ca7b4378e18dc423899adfbf318001e11d5a1c865dd11556bb2172d8912f5a9f86bfad45d503d7c9fa3d082f919181e4c15f8231137c8393186998ee3143b8b5d43e444a8fca07"', - count: 1039340, - }, - { - filter: 'shard', - value: 1, - count: 999843, - }, - { - filter: 'epoch', - value: 594, - count: 9604, - }, - - ].forEach(({ filter, value, count }) => { - describe(`with filter = ${filter}`, () => { - it(`should return rounds count based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - roundsCount(input:{ - ${filter}: ${value} - }) - }`, - }) - .then(res => { - expect(res.body.data.roundsCount).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); - - describe('Query - Get Round', () => { - it('should returns round details from a specific shard and round', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - round(input:{ - shard: 2, round: 781 - }){ - blockWasProposed - round - shard - epoch - timestamp - signers - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.round.blockWasProposed).toBeDefined(); - expect(res.body.data.round.round).toStrictEqual(781); - expect(res.body.data.round.shard).toStrictEqual(2); - expect(res.body.data.round.epoch).toBeDefined(); - expect(res.body.data.round.timestamp).toBeDefined(); - expect(res.body.data.round.signers).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/shard.graph-spec.ts b/src/test/integration/graphql/shard.graph-spec.ts deleted file mode 100644 index c5a9feb82..000000000 --- a/src/test/integration/graphql/shard.graph-spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Shard', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Shards', () => { - it('should returns all available shards', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - shards(input:{ - }){ - shard - validators - activeValidators - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.shards).toBeDefined(); - expect(res.body.data.shards).toEqual( - expect.arrayContaining([ - expect.objectContaining({ shard: 0 || 1 || 2 || 4294967295 })]) - ); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/smart.contract.result.graph-spec.ts b/src/test/integration/graphql/smart.contract.result.graph-spec.ts deleted file mode 100644 index 337df1dc8..000000000 --- a/src/test/integration/graphql/smart.contract.result.graph-spec.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Smart Contract Results', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Smart Contract Results', () => { - it('should returns 5 smart contract results available on the blockchain', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - results(input:{ - size: 5 - }){ - hash - timestamp - nonce - gasLimit - gasPrice - value - sender - receiver - receiverAssets{ - name - tags - } - data - prevTxHash - originalTxHash - callType - miniBlockHash - action{ - category - name - description - arguments - } - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.results).toBeDefined(); - }); - }); - }); - - describe('Query - Get Smart Contract Result', () => { - const miniBlockHash: string = "067c4d662c03c8d17b0feb14217734a6a0a341e96ab922b657f9eb3c515b7773"; - [ - { - filter: 'originalTxHashes', - value: '"758480f61a6530a7d5f11e6074626672d6a1a880882fbf47ca1fc554436ec2ad"', - }, - { - filter: 'miniBlockHash', - value: '"067c4d662c03c8d17b0feb14217734a6a0a341e96ab922b657f9eb3c515b7773"', - }, - - ].forEach(({ filter, value }) => { - describe(`filter = ${filter}`, () => { - it(`should return smart contract result based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - results(input:{ - ${filter}: ${value} - }){ - hash - timestamp - nonce - gasLimit - gasPrice - value - sender - receiver - receiverAssets{ - name - tags - } - data - prevTxHash - originalTxHash - callType - miniBlockHash - action{ - category - name - description - arguments - } - } - }`, - }) - .then(res => { - expect(res.body.data.results[0].miniBlockHash).toStrictEqual(miniBlockHash); - }); - }); - }); - }); - }); - - describe('Query - Get Smart Contract Results Count', () => { - it('should returns smart contract results count', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - resultsCount - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.resultsCount).toBeGreaterThanOrEqual(110372303); - }); - }); - }); - - describe('Query - Get Smart Contract Result', () => { - it('should returns smart contract results details based on scHash', async () => { - const scHash: string = "a5c935b7639a40e7d0e169f2053dcff3ebcbf04c8ee38799bb2075f1fa3f1688"; - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - result(input:{ - scHash: "a5c935b7639a40e7d0e169f2053dcff3ebcbf04c8ee38799bb2075f1fa3f1688" - }){ - hash - timestamp - nonce - gasLimit - gasPrice - value - sender - receiver - prevTxHash - originalTxHash - callType - miniBlockHash - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.result).toBeDefined(); - expect(res.body.data.result.hash).toStrictEqual(scHash); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/stake.graph-spec.ts b/src/test/integration/graphql/stake.graph-spec.ts deleted file mode 100644 index 2e7e91de0..000000000 --- a/src/test/integration/graphql/stake.graph-spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Stake', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Stake', () => { - it('should returns general staking information', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - stake { - totalValidators - activeValidators - queueSize - totalStaked - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.stake).toBeDefined(); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/tags.graph-spec.ts b/src/test/integration/graphql/tags.graph-spec.ts deleted file mode 100644 index ca6697d7e..000000000 --- a/src/test/integration/graphql/tags.graph-spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Tags', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Tags details', () => { - it('should return 25 tags', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tags(input:{ - size:25 - }){ - tag - count - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tags).toBeDefined(); - expect(res.body.data.tags).toHaveLength(25); - }); - }); - }); - - describe('Query - Get Tags count', () => { - it('should return total tags count', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tagsCount - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tagsCount).toBeGreaterThanOrEqual(32100); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/tokens.graph-spec.ts b/src/test/integration/graphql/tokens.graph-spec.ts deleted file mode 100644 index acfc87758..000000000 --- a/src/test/integration/graphql/tokens.graph-spec.ts +++ /dev/null @@ -1,393 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Tokens', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Tokens', () => { - it('should return 25 tokens', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokens(input:{ - }){ - identifier - name - ticker - owner - decimals - isPaused - assets{ - website - description - status - pngUrl - svgUrl - ledgerSignature - } - transactions - accounts - canUpgrade - canMint - canBurn - canChangeOwner - canPause - canFreeze - canWipe - price - marketCap - supply - circulatingSupply - } - }`, - }) - .expect(200) - .then(res => { - for (const item of res.body.data.tokens) { - expect(item.identifier).toBeDefined(); - } - expect(res.body.data.tokens).toBeDefined(); - expect(res.body.data.tokens).toHaveLength(25); - }); - }); - - it('should return token details when identifier filter is applied with value "MEX-455c57"', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokens(input:{ - identifier: "MEX-455c57" - }){ - identifier - name - ticker - owner - decimals - isPaused - assets{ - website - description - status - pngUrl - svgUrl - ledgerSignature - } - transactions - accounts - canUpgrade - canMint - canBurn - canChangeOwner - canPause - canFreeze - canWipe - price - marketCap - supply - circulatingSupply - } - }`, - }) - .expect(200) - .then(res => { - for (const item of res.body.data.tokens) { - expect(item.identifier).toStrictEqual("MEX-455c57"); - } - expect(res.body.data.tokens).toHaveLength(1); - }); - }); - - it('should return tokens details when identifiers filter is applied with value "MEX-455c57" and "RIDE-7d18e9"', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokens(input:{ - identifiers: ["MEX-455c57","RIDE-7d18e9"] - }){ - identifier - name - ticker - owner - decimals - isPaused - assets{ - website - description - status - pngUrl - svgUrl - ledgerSignature - } - transactions - accounts - canUpgrade - canMint - canBurn - canChangeOwner - canPause - canFreeze - canWipe - price - marketCap - supply - circulatingSupply - } - }`, - }) - .expect(200) - .then(res => { - const results = res.body.data.tokens; - const tokensResults = results.map((tokens: { identifier: any; }) => tokens.identifier); - - expect(res.body.data.tokens).toHaveLength(2); - expect(tokensResults.includes('MEX-455c57')).toBeTruthy(); - expect(tokensResults.includes('RIDE-7d18e9')).toBeTruthy(); - }); - }); - }); - - describe('GET - Token Supply', () => { - it('should return supply details for a specific token', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenSupply(input:{ - identifier: "MEX-455c57" - }){ - burnt - circulatingSupply - initialMinted - lockedAccounts{ - address - balance - name - } - minted - supply - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokenSupply.burnt).toBeDefined(); - expect(res.body.data.tokenSupply.circulatingSupply).toBeDefined(); - expect(res.body.data.tokenSupply.initialMinted).toBeDefined(); - expect(res.body.data.tokenSupply.lockedAccounts).toBeDefined(); - expect(res.body.data.tokenSupply.minted).toBeDefined(); - expect(res.body.data.tokenSupply.supply).toBeDefined(); - }); - }); - }); - - describe('GET - MetaESDT token details', () => { - it('should return minted, burnt, supply, circulatingSupply fields for a specific MetaESDT', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenSupply(input:{ - identifier: "XMEX-fda355" - }){ - burnt - circulatingSupply - initialMinted - minted - supply - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokenSupply.burnt).toBeDefined(); - expect(res.body.data.tokenSupply.circulatingSupply).toBeDefined(); - expect(res.body.data.tokenSupply.initialMinted).toBeDefined(); - expect(res.body.data.tokenSupply.minted).toBeDefined(); - expect(res.body.data.tokenSupply.supply).toBeDefined(); - }); - }); - }); - - describe('GET - Token Roles', () => { - it('should return roles details for a specific token', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenRoles(input:{ - identifier:"MEX-455c57" - }){ - address - canLocalBurn - canLocalMint - roles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokenRoles[0]).toEqual(expect.objectContaining({ - address: "erd1qqqqqqqqqqqqqpgqjpt0qqgsrdhp2xqygpjtfrpwf76f9nvg2jpsg4q7th", - canLocalBurn: true, - canLocalMint: true, - roles: expect.arrayContaining([ - "ESDTRoleLocalMint", - "ESDTRoleLocalBurn", - ]), - })); - }); - }); - }); - - describe('GET - Token Accounts', () => { - it('should return all token accounts', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenAccounts(input:{ - identifier: "MEX-455c57" - }){ - address - balance - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokenAccounts[0]).toEqual(expect.objectContaining({ - address: "erd1qqqqqqqqqqqqqpgqa0fsfshnff4n76jhcye6k7uvd7qacsq42jpsp6shh2", - balance: res.body.data.tokenAccounts[0].balance, - })); - }); - }); - - it('should throw error with status code 404 if given identifier is not token', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenAccounts(input:{ - identifier: "MEX" - }){ - address - balance - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.errors[0].message).toStrictEqual('Token not found'); - expect(res.body.errors[0].extensions.response.statusCode).toStrictEqual(404); - }); - }); - }); - - describe('GET - Address Token Roles', () => { - it('should return address token roles', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenRolesAddress(input:{ - address: "erd1qqqqqqqqqqqqqpgq7qhsw8kffad85jtt79t9ym0a4ycvan9a2jps0zkpen", - identifier: "MEX-455c57" - }){ - canLocalBurn - canLocalMint - roles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokenRolesAddress).toEqual(expect.objectContaining({ - canLocalBurn: true, - canLocalMint: false, - roles: expect.arrayContaining([ - "ESDTRoleLocalBurn", - ]), - })); - }); - }); - - it('should throw error with status code 404 if given identifier is not token', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokenRolesAddress(input:{ - address: "erd1qqqqqqqqqqqqqpgq7qhsw8kffad85jtt79t9ym0a4ycvan9a2jps0zkpen", - identifier: "MEX" - }){ - canLocalBurn - canLocalMint - roles - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.errors[0].message).toStrictEqual('Token not found'); - expect(res.body.errors[0].extensions.response.statusCode).toStrictEqual(404); - }); - }); - }); - - describe('GET - Tokens Count', () => { - [ - { - tokenFilter: 'name', - value: '"MEX"', - count: 1, - }, - { - tokenFilter: 'identifier', - value: '"MEX-455c57"', - count: 1, - }, - { - tokenFilter: 'identifiers', - value: '["MEX-455c57", "RIDE-7d18e9"]', - count: 2, - }, - ].forEach(({ tokenFilter, value, count }) => { - describe(`when filter ${tokenFilter} is applied`, () => { - it(`should return tokens count`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - tokensCount(input:{ - ${tokenFilter}: ${value} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.tokensCount).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/transactions.graph-spec.ts b/src/test/integration/graphql/transactions.graph-spec.ts deleted file mode 100644 index 24891e365..000000000 --- a/src/test/integration/graphql/transactions.graph-spec.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Transactions', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Transaction', () => { - it('should return transaction details for a given transaction hash', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - transaction(input:{ - hash: "22eae3fd93d2ad09f09d5aa76c22655532dd5ab14805f242fec920e484c26778" - }){ - txHash - gasLimit - gasPrice - gasUsed - miniBlockHash - nonce - receipt{ - data - sender - value - } - receiverAccount{ - address - } - senderAccount{ - address - } - signature - status - value - fee - timestamp - data - action{ - arguments - name - category - description - - } - results { - hash - timestamp - nonce - gasLimit - gasPrice - value - sender - receiver - data - prevTxHash - originalTxHash - callType - } - logs { - id - address - events{ - address - identifier - topics - } - } - } - }`, - }) - .expect(200) - .then(res => { - const txHash: string = "22eae3fd93d2ad09f09d5aa76c22655532dd5ab14805f242fec920e484c26778"; - - expect(res.body.data.transaction).toBeDefined(); - expect(res.body.data.transaction.txHash).toStrictEqual(txHash); - expect(res.body.data.transaction.results).toBeDefined(); - expect(res.body.data.transaction.logs).toBeDefined(); - }); - }); - }); - - describe('Query - Get Count', () => { - [ - { - filter: 'hashes', - value: `["2d4875377f4ce54d8f8ba51cfeaa50b85a9ce20520a66fdaabb3ebdf9e3195a1", "5a873cbc1ead69bc474a93f2dbffa689c1bb84c413ab7b634682f0c4c4e430af"]`, - count: 2, - }, - { - filter: 'sender', - value: '"erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"', - count: 28, - }, - { - filter: 'senderShard', - value: '1', - count: 28075100, - }, - { - filter: 'receiverShard', - value: '2', - count: 12605200, - }, - { - filter: 'receiver', - value: '"erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"', - count: 30, - }, - { - filter: 'miniBlockHash', - value: '"362ab57e2688b0040bd1593e7719e13564db03e873b3d204c4bb0aa54e7a1bc3"', - count: 1, - }, - { - filter: 'before', - value: '1660114204', - count: 54345000, - }, - { - filter: 'after', - value: '1660134204', - count: 975560, - }, - - ].forEach(({ filter, value, count }) => { - describe(`filter = ${filter}`, () => { - it(`should return total count based on ${filter} filter with value ${value}`, async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{transactionsCount(input:{ - ${filter}: ${value} - }) - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.transactionsCount).toBeGreaterThanOrEqual(count); - }); - }); - }); - }); - }); - - describe('Query - Get Transactions', () => { - it('should return transactions based on hashes filter', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - transactions(input:{ - hashes: ["2d4875377f4ce54d8f8ba51cfeaa50b85a9ce20520a66fdaabb3ebdf9e3195a1", "5a873cbc1ead69bc474a93f2dbffa689c1bb84c413ab7b634682f0c4c4e430af"] - }){ - txHash - gasLimit - gasPrice - gasUsed - miniBlockHash - nonce - signature - status - value - fee - timestamp - data - action{ - arguments - name - category - description - } - results { - hash - timestamp - nonce - gasLimit - gasPrice - value - sender - receiver - data - prevTxHash - originalTxHash - callType - } - logs { - id - address - events{ - address - identifier - topics - } - } - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.transactions).toBeDefined(); - expect(res.body.data.transactions[0].txHash).toStrictEqual('2d4875377f4ce54d8f8ba51cfeaa50b85a9ce20520a66fdaabb3ebdf9e3195a1'); - expect(res.body.data.transactions[1].txHash).toStrictEqual('5a873cbc1ead69bc474a93f2dbffa689c1bb84c413ab7b634682f0c4c4e430af'); - }); - }); - }); - - describe('Query - Get Transactions', () => { - it('should return an array of transactions with value field value <> 0', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - transactions(input:{ - token: "EGLD" - }){ - txHash - gasLimit - gasPrice - gasUsed - miniBlockHash - nonce - receiverAddress - receiverShard - round - senderAddress - senderShard - signature - status - value - fee - timestamp - data - function - action{ - category - name - description - arguments - } - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.transactions).toBeDefined(); - expect(res.body.data.transactions.value).not.toEqual('0'); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/username.graph-spec.ts b/src/test/integration/graphql/username.graph-spec.ts deleted file mode 100644 index 9c1a11959..000000000 --- a/src/test/integration/graphql/username.graph-spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('Username', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Account details', () => { - it('should username account details', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - username(input:{ - username: "alice" - }){ - address - balance - nonce - shard - rootHash - txCount - scrCount - username - developerReward - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.username.username).toStrictEqual("alice.elrond"); - }); - }); - }); -}); diff --git a/src/test/integration/graphql/waiting.list.graph-spec.ts b/src/test/integration/graphql/waiting.list.graph-spec.ts deleted file mode 100644 index 6e70e68b9..000000000 --- a/src/test/integration/graphql/waiting.list.graph-spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe('WaitingList', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - describe('Query - Get Waiting List', () => { - it('should returns node waiting list', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - waitingList(input:{ - }){ - address - value - nonce - rank - } - }`, - }) - .expect(200) - .then(res => { - for (const item of res.body.data.waitingList) { - expect(item.address).toBeDefined(); - expect(item.value).toBeDefined(); - expect(item.nonce).toBeDefined(); - expect(item.rank).toBeDefined(); - } - }); - }); - }); -}); diff --git a/src/test/integration/graphql/websocket.graph-spec.ts b/src/test/integration/graphql/websocket.graph-spec.ts deleted file mode 100644 index 80f35b1db..000000000 --- a/src/test/integration/graphql/websocket.graph-spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { INestApplication } from "@nestjs/common"; -import { Test, TestingModule } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import request = require('supertest'); - -describe.skip('WebSocket', () => { - let app: INestApplication; - const gql = '/graphql'; - - beforeAll(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('Query - Get Websocket url', () => { - it('should returns config used for accessing websocket on the same cluster', async () => { - await request(app.getHttpServer()) - .post(gql) - .send({ - query: `{ - webSocketConfig{ - url - } - }`, - }) - .expect(200) - .then(res => { - expect(res.body.data.webSocketConfig).toBeDefined(); - expect(res.body.data.webSocketConfig.url).toContain('socket'); - }); - }); - }); -}); From d06a4551949a06db95e5c52a942f796bc475b943 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:00:31 +0200 Subject: [PATCH 03/30] remove warm --- .github/workflows/integration.graph.test.yml | 8 -------- .github/workflows/integration.tests.yml | 8 -------- 2 files changed, 16 deletions(-) diff --git a/.github/workflows/integration.graph.test.yml b/.github/workflows/integration.graph.test.yml index 14ccb4fb6..05e0cf6be 100644 --- a/.github/workflows/integration.graph.test.yml +++ b/.github/workflows/integration.graph.test.yml @@ -61,14 +61,6 @@ jobs: - run: npm ci - name: Initialize run: npm run init - - name: Warm - run: | - if ${{ github.ref == 'refs/heads/main' }}; then - npm run test:e2e:warm - else - npm run test:e2e:warm:mocked - fi - shell: bash - name: Run integration tests run: npm run test:graph diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml index a6065d60f..75ccbe7be 100644 --- a/.github/workflows/integration.tests.yml +++ b/.github/workflows/integration.tests.yml @@ -64,14 +64,6 @@ jobs: - run: npm ci - name: Initialize run: npm run init - - name: Warm - run: | - if ${{ github.ref == 'refs/heads/main' }}; then - npm run test:e2e:warm - else - npm run test:e2e:warm:mocked - fi - shell: bash - name: Run integration tests run: npm run test:e2e:cov - uses: codecov/codecov-action@v3 From 2f8757ed7c38909bbd5a0fa83e852d443d7e84d2 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:07:03 +0200 Subject: [PATCH 04/30] resolve e2e action --- .github/workflows/integration.tests.yml | 47 +++---------------------- 1 file changed, 5 insertions(+), 42 deletions(-) diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml index 75ccbe7be..d9c8c5bda 100644 --- a/.github/workflows/integration.tests.yml +++ b/.github/workflows/integration.tests.yml @@ -1,10 +1,7 @@ # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions -name: Integration API - -env: - CODECOV_VERSION: 'v0.3.1' +name: E2E tests on: push: @@ -21,40 +18,7 @@ jobs: node-version: [16.x] # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ - # Service containers to run with `container-job` - services: - # Label used to access the service container - redis: - # Docker Hub image - image: redis - # Set health checks to wait until redis has started - options: >- - --health-cmd "redis-cli ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - ports: - # Maps port 6379 on service container to the host - - 6379:6379 - mysql: - image: mysql:8 - env: - MYSQL_USER: user - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: root - MYSQL_DATABASE: api - ports: - - 3306 - options: --health-cmd "mysqladmin ping" --health-interval 10s --health-timeout 5s --health-retries 10 - rabbitmq: - image: rabbitmq:3-alpine - ports: - - 5672:5672 steps: - - name: Set up MySQL - run: | - sudo /etc/init.d/mysql start - mysql -e 'CREATE DATABASE IF NOT EXISTS api;' -uroot -proot - uses: actions/checkout@v3 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v3 @@ -62,15 +26,14 @@ jobs: node-version: ${{ matrix.node-version }} cache: 'npm' - run: npm ci - - name: Initialize - run: npm run init - - name: Run integration tests + - run: npm run init + - run: npm test:e2e + - name: Collect code coverage run: npm run test:e2e:cov - uses: codecov/codecov-action@v3 with: files: ./coverage/e2e/clover.xml - version: ${{ env.CODECOV_VERSION }} - flags: integrationtests + flags: e2etests name: codecov-umbrella fail_ci_if_error: true verbose: true From 8bf10fc966c41e94ed768b98003897686b38e9ba Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:08:29 +0200 Subject: [PATCH 05/30] fix_2 --- .github/workflows/integration.tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml index d9c8c5bda..0b7d1382d 100644 --- a/.github/workflows/integration.tests.yml +++ b/.github/workflows/integration.tests.yml @@ -27,7 +27,7 @@ jobs: cache: 'npm' - run: npm ci - run: npm run init - - run: npm test:e2e + - run: npm run test:e2e - name: Collect code coverage run: npm run test:e2e:cov - uses: codecov/codecov-action@v3 From 710373dd9ed1c461d845dd4623b17a660b142784 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:09:54 +0200 Subject: [PATCH 06/30] remove graph action --- .github/workflows/integration.graph.test.yml | 66 -------------------- 1 file changed, 66 deletions(-) delete mode 100644 .github/workflows/integration.graph.test.yml diff --git a/.github/workflows/integration.graph.test.yml b/.github/workflows/integration.graph.test.yml deleted file mode 100644 index 05e0cf6be..000000000 --- a/.github/workflows/integration.graph.test.yml +++ /dev/null @@ -1,66 +0,0 @@ -# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions - -name: Integration GraphQL - -on: - push: - branches: [main, development] - pull_request: - branches: [main, development] - -jobs: - build: - runs-on: ubuntu-latest - - strategy: - matrix: - node-version: [16.x] - # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ - - # Service containers to run with `container-job` - services: - # Label used to access the service container - redis: - # Docker Hub image - image: redis - # Set health checks to wait until redis has started - options: >- - --health-cmd "redis-cli ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - ports: - # Maps port 6379 on service container to the host - - 6379:6379 - mysql: - image: mysql:8 - env: - MYSQL_USER: user - MYSQL_PASSWORD: password - MYSQL_ROOT_PASSWORD: root - MYSQL_DATABASE: api - ports: - - 3306 - options: --health-cmd "mysqladmin ping" --health-interval 10s --health-timeout 5s --health-retries 10 - rabbitmq: - image: rabbitmq:3-alpine - ports: - - 5672:5672 - steps: - - name: Set up MySQL - run: | - sudo /etc/init.d/mysql start - mysql -e 'CREATE DATABASE IF NOT EXISTS api;' -uroot -proot - - uses: actions/checkout@v3 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node-version }} - cache: 'npm' - - run: npm ci - - name: Initialize - run: npm run init - - name: Run integration tests - run: npm run test:graph - From 7e43d5602be739a6b47194ad8b311f9f0d29ea1b Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:11:34 +0200 Subject: [PATCH 07/30] remove also services e2e tests -> now we have unit tests --- .../integration/services/caching.e2e-spec.ts | 79 -- .../services/dapp.config.e2e-spec.ts | 87 -- .../integration/services/data-api.e2e-spec.ts | 204 ----- src/test/integration/services/e2e-init.ts | 116 --- .../integration/services/esdt.e2e-spec.ts | 167 ---- .../services/identities.e2e-spec.ts | 115 --- .../integration/services/keybase.e2e-spec.ts | 29 - src/test/integration/services/nft.e2e-spec.ts | 836 ------------------ .../nft.extendedattributes.e2e-spec.ts | 90 -- .../services/nft.media.e2e-spec.ts | 115 --- .../services/nft.metadata.e2e-spec.ts | 74 -- .../services/nft.thumbnail.e2e-spec.ts | 44 - .../services/process.nfts.e2e-spec.ts | 164 ---- .../services/token.asset.e2e-spec.ts | 45 - .../services/token.transfer.e2e-spec.ts | 201 ----- .../services/transaction.get.e2e-spec.ts | 127 --- .../services/transactions.e2e-spec.ts | 291 ------ .../services/waiting.list.e2e-spec.ts | 78 -- .../services/warm.e2e-warm-spec.ts | 34 - 19 files changed, 2896 deletions(-) delete mode 100644 src/test/integration/services/caching.e2e-spec.ts delete mode 100644 src/test/integration/services/dapp.config.e2e-spec.ts delete mode 100644 src/test/integration/services/data-api.e2e-spec.ts delete mode 100644 src/test/integration/services/e2e-init.ts delete mode 100644 src/test/integration/services/esdt.e2e-spec.ts delete mode 100644 src/test/integration/services/identities.e2e-spec.ts delete mode 100644 src/test/integration/services/keybase.e2e-spec.ts delete mode 100644 src/test/integration/services/nft.e2e-spec.ts delete mode 100644 src/test/integration/services/nft.extendedattributes.e2e-spec.ts delete mode 100644 src/test/integration/services/nft.media.e2e-spec.ts delete mode 100644 src/test/integration/services/nft.metadata.e2e-spec.ts delete mode 100644 src/test/integration/services/nft.thumbnail.e2e-spec.ts delete mode 100644 src/test/integration/services/process.nfts.e2e-spec.ts delete mode 100644 src/test/integration/services/token.asset.e2e-spec.ts delete mode 100644 src/test/integration/services/token.transfer.e2e-spec.ts delete mode 100644 src/test/integration/services/transaction.get.e2e-spec.ts delete mode 100644 src/test/integration/services/transactions.e2e-spec.ts delete mode 100644 src/test/integration/services/waiting.list.e2e-spec.ts delete mode 100644 src/test/integration/services/warm.e2e-warm-spec.ts diff --git a/src/test/integration/services/caching.e2e-spec.ts b/src/test/integration/services/caching.e2e-spec.ts deleted file mode 100644 index 97e3b7d85..000000000 --- a/src/test/integration/services/caching.e2e-spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Constants } from '@multiversx/sdk-nestjs-common'; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { Test } from '@nestjs/testing'; -import { ApiConfigModule } from 'src/common/api-config/api.config.module'; -import { DynamicModuleUtils } from 'src/utils/dynamic.module.utils'; - -describe('Caching Service', () => { - let cachingService: CacheService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [ - ApiConfigModule, - DynamicModuleUtils.getCacheModule(), - ], - }).compile(); - - cachingService = moduleRef.get(CacheService); - }); - - describe('Cache Local', () => { - //CRUD - it(`should return undefined, 'test' key isn't set`, async () => { - const cacheValue = await cachingService.getLocal('test'); - expect(cacheValue).toBeUndefined(); - }); - - it(`should return 'test' value after key is set`, async () => { - await cachingService.setLocal('test', 'test', Constants.oneSecond()); - - const cacheValue = await cachingService.getLocal('test'); - expect(cacheValue).toBe('test'); - }); - - it(`should return 'test-update' value after key is set`, async () => { - await cachingService.setLocal('test', 'test-update', Constants.oneSecond()); - - const cacheValue = await cachingService.getLocal('test'); - expect(cacheValue).toBe('test-update'); - }); - - it(`should return undefined because key is invalidated`, async () => { - await cachingService.deleteInCache('test'); - - const cacheValue = await cachingService.getLocal('test'); - expect(cacheValue).toBeUndefined(); - }); - - }); - - describe('Get Or Set Cache', () => { - it(`should return 'test' value after key is set`, async () => { - // eslint-disable-next-line require-await - const cacheValue = await cachingService.getOrSet('test', async () => 'test', Constants.oneSecond()); - expect(cacheValue).toBe('test'); - }); - }); - - describe('Batch process in chunks', () => { - const input: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - const output: Array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']; - const emptyOutput: Array = Array(15).fill(null); - const cacheKeyFunction = (number: Number) => number.toString(); - const handlerFunction = async (number: Number) => await number.toString(); - - it(`should return emptyOutput because keys aren't set`, async () => { - const cacheValueChunks = await cachingService.batchGetManyRemote(input.map((x) => cacheKeyFunction(x))); - - expect(cacheValueChunks).toStrictEqual(emptyOutput); - }); - - it(`should return ouput keys as string`, async () => { - await cachingService.batchProcess(input, cacheKeyFunction, handlerFunction, Constants.oneSecond()); - - const cacheValueChunks = await cachingService.batchGetManyRemote(input.map((x) => cacheKeyFunction(x))); - expect(cacheValueChunks).toStrictEqual(output); - }); - }); -}); diff --git a/src/test/integration/services/dapp.config.e2e-spec.ts b/src/test/integration/services/dapp.config.e2e-spec.ts deleted file mode 100644 index 2461daae7..000000000 --- a/src/test/integration/services/dapp.config.e2e-spec.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { ApiConfigService } from 'src/common/api-config/api.config.service'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { DappConfigService } from 'src/endpoints/dapp-config/dapp.config.service'; -import { DappConfig } from 'src/endpoints/dapp-config/entities/dapp-config'; - -describe('Dapp Config Service', () => { - let dappConfigService: DappConfigService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - dappConfigService = moduleRef.get(DappConfigService); - }); - - beforeEach(() => { jest.restoreAllMocks(); }); - - describe("getDappConfiguration", () => { - it("should return mainnet dapp configuration", () => { - jest - .spyOn(ApiConfigService.prototype, 'getNetwork') - .mockImplementation(jest.fn(() => 'mainnet')); - - const config = dappConfigService.getDappConfiguration(); - - if (!config) { - throw new Error('Properties are not defined'); - } - - expect(config.id).toStrictEqual('mainnet'); - expect(config.name).toStrictEqual('Mainnet'); - expect(config.chainId).toStrictEqual('1'); - }); - - it("should return devnet dapp configuration", () => { - jest - .spyOn(DappConfigService.prototype, 'getDappConfigurationRaw') - .mockImplementation(jest.fn(() => new DappConfig({ - "id": "devnet", - "name": "Devnet", - "egldLabel": "xEGLD", - "decimals": "4", - "egldDenomination": "18", - "gasPerDataByte": "1500", - "apiTimeout": "4000", - "walletConnectDeepLink": "https://maiar.page.link/?apn=com.multiversx.maiar.wallet&isi=1519405832&ibi=com.multiversx.maiar.wallet&link=https://maiar.com/", - "walletAddress": "https://devnet-wallet.multiversx.com", - "apiAddress": "https://devnet-api.multiversx.com", - "explorerAddress": "http://devnet-explorer.multiversx.com", - "chainId": "D", - }))); - - const config = dappConfigService.getDappConfiguration(); - - if (!config) { - throw new Error('Properties are not defined'); - } - }); - - it("should return devnet-old dapp configuration", () => { - jest - .spyOn(DappConfigService.prototype, 'getDappConfigurationRaw') - .mockImplementation(jest.fn(() => new DappConfig({ - "id": "devnet-old", - "name": "Devnet", - "egldLabel": "xEGLD", - "decimals": "4", - "egldDenomination": "18", - "gasPerDataByte": "1500", - "apiTimeout": "4000", - "walletConnectDeepLink": "https://maiar.page.link/?apn=com.multiversx.maiar.wallet&isi=1519405832&ibi=com.multiversx.maiar.wallet&link=https://maiar.com/", - "walletAddress": "https://devnet-old-wallet.multiversx.com", - "apiAddress": "https://devnet-old-api.multiversx.com", - "explorerAddress": "http://devnet-old-explorer.multiversx.com", - "chainId": "D", - }))); - - const config = dappConfigService.getDappConfiguration(); - - if (!config) { - throw new Error('Properties are not defined'); - } - }); - }); -}); diff --git a/src/test/integration/services/data-api.e2e-spec.ts b/src/test/integration/services/data-api.e2e-spec.ts deleted file mode 100644 index 5eba52df5..000000000 --- a/src/test/integration/services/data-api.e2e-spec.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { ApiService } from "@multiversx/sdk-nestjs-http"; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { Test } from "@nestjs/testing"; -import { ApiConfigService } from "src/common/api-config/api.config.service"; -import { DataApiModule } from "src/common/data-api/data-api.module"; -import { DataApiService } from "src/common/data-api/data-api.service"; -import { DataApiToken } from "src/common/data-api/entities/data-api.token"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/date.extensions'; - -describe('Data API Service', () => { - const mockTokens: Record = { - 'EGLD': { identifier: 'EGLD', market: 'cex' }, - 'USDC': { identifier: 'USDC', market: 'cex' }, - 'MEX-455c57': { identifier: 'MEX-455c57', market: 'xexchange' }, - 'RIDE-7d18e9': { identifier: 'RIDE-7d18e9', market: 'xexchange' }, - 'ITHEUM-df6f26': { identifier: 'ITHEUM-df6f26', market: 'xexchange' }, - }; - - let service: DataApiService; - let apiService: ApiService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [DataApiModule], - }).compile(); - - service = moduleRef.get(DataApiService); - apiService = moduleRef.get(ApiService); - - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, promise: any) => promise())); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - it('should be defined', () => { - expect(service).toBeDefined(); - }); - - describe('getEgldPrice', () => { - it('should return undefined if the Data API feature is disabled', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(service, 'getEsdtTokenPrice').mockResolvedValueOnce(undefined); - - const result = await service.getEgldPrice(1672567200); - - expect(service.getEsdtTokenPrice).toBeCalledWith('EGLD', 1672567200); - expect(result).toBeUndefined(); - }); - }); - - describe('getEsdtTokenPrice', () => { - it('should return undefined if the Data API feature is disabled', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(false); - - const result = await service.getEsdtTokenPrice('TOKEN'); - - expect(result).toBeUndefined(); - }); - - it('should return undefined if the token is not found', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(service, 'getDataApiToken').mockResolvedValueOnce(undefined); - - const result = await service.getEsdtTokenPrice('TOKEN'); - - expect(service.getDataApiToken).toHaveBeenCalledWith('TOKEN'); - expect(result).toBeUndefined(); - }); - - it('should return undefined when data API feature is disabled', async () => { - jest.spyOn(service['apiConfigService'], 'isDataApiFeatureEnabled').mockReturnValue(false); - - const result = await service.getEsdtTokenPrice('EGLD', 123456789); - expect(result).toBeUndefined(); - }); - - it('should fetch the current token price from the data API', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve(mockTokens)); - // eslint-disable-next-line require-await - jest.spyOn(apiService, 'get').mockImplementation(async () => ({ data: 3.14 })); - - const result = await service.getEsdtTokenPrice('EGLD'); - - expect(result).toEqual(3.14); - }); - - it('should fetch token price from the data API', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve(mockTokens)); - // eslint-disable-next-line require-await - jest.spyOn(apiService, 'get').mockImplementation(async () => ({ data: 3.14 })); - - const result = await service.getEsdtTokenPrice('EGLD', 1672567200); - - expect(apiService.get).toHaveBeenCalledWith(expect.stringContaining("&date=2023-01-01")); - expect(result).toEqual(3.14); - }); - - test('should return undefined when API call fails', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - // eslint-disable-next-line require-await - jest.spyOn(apiService, 'get').mockImplementationOnce(async () => { throw new Error('An error occurred'); }); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve(mockTokens)); - jest.spyOn(service['logger'], 'error').mockImplementation(() => { }); - - const price = await service.getEsdtTokenPrice('EGLD'); - - expect(apiService.get).toHaveBeenCalled(); - expect(service['logger'].error).toHaveBeenCalled(); - expect(price).toBeUndefined(); - }); - }); - - describe('getDataApiTokens', () => { - it('returns an empty object if data API feature is disabled', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(false); - - const result = await service.getDataApiTokensRaw(); - - expect(result).toEqual({}); - }); - - it('should fetch tokens from the Data API', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(ApiConfigService.prototype, 'getDataApiServiceUrl').mockReturnValueOnce('https://data-api.multiversx.com'); - const mockCexTokens = { data: [{ identifier: 'EGLD' }, { identifier: 'USDC' }] }; - const mockXExchangeTokens = { data: [{ identifier: 'MEX-455c57' }, { identifier: 'RIDE-7d18e9' }, { identifier: 'ITHEUM-df6f26' }] }; - const mockHatomTokens = { data: [{ identifier: 'HEGLD-d61095' }, { identifier: 'HSEGLD-c13a4e' }, { identifier: 'HWBTC-49ca31' }] }; - - jest.spyOn(apiService, 'get') - .mockReturnValueOnce(Promise.resolve(mockCexTokens)) - .mockReturnValueOnce(Promise.resolve(mockXExchangeTokens)) - .mockReturnValueOnce(Promise.resolve(mockHatomTokens)); - - const result = await service.getDataApiTokensRaw(); - expect(apiService.get).toHaveBeenCalledTimes(3); - expect(result).toEqual({ - 'EGLD': { identifier: 'EGLD', market: 'cex' }, - 'USDC': { identifier: 'USDC', market: 'cex' }, - 'MEX-455c57': { identifier: 'MEX-455c57', market: 'xexchange' }, - 'RIDE-7d18e9': { identifier: 'RIDE-7d18e9', market: 'xexchange' }, - 'ITHEUM-df6f26': { identifier: 'ITHEUM-df6f26', market: 'xexchange' }, - 'HEGLD-d61095': { identifier: 'HEGLD-d61095', market: 'hatom' }, - 'HSEGLD-c13a4e': { identifier: 'HSEGLD-c13a4e', market: 'hatom' }, - 'HWBTC-49ca31': { identifier: 'HWBTC-49ca31', market: 'hatom' }, - }); - }); - - it('should return an empty array if there is an error fetching tokens from the data API', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(apiService, 'get').mockRejectedValueOnce(new Error('An error occurred')); - jest.spyOn(service['logger'], 'error').mockImplementation(() => { }); - - const result = await service.getDataApiTokensRaw(); - - expect(apiService.get).toHaveBeenCalledTimes(3); - expect(service['logger'].error).toHaveBeenCalled(); - expect(result).toEqual({}); - }); - }); - - describe('getDataApiToken', () => { - it('should return undefined if the Data API feature is disabled', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(false); - - const result = await service.getDataApiToken('EGLD'); - - expect(result).toBeUndefined(); - }); - - it('should return undefined if tokens are empty', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve({})); - - const result = await service.getDataApiToken('EGLD'); - - expect(result).toBeUndefined(); - }); - - it('should return undefined if token is not found', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve(mockTokens)); - - const result = await service.getDataApiToken('X'); - - expect(result).toBeUndefined(); - }); - - it('should return the token if it is found', async () => { - jest.spyOn(ApiConfigService.prototype, 'isDataApiFeatureEnabled').mockReturnValueOnce(true); - jest.spyOn(DataApiService.prototype, 'getDataApiTokens').mockReturnValueOnce(Promise.resolve(mockTokens)); - - const result = await service.getDataApiToken('MEX-455c57'); - - expect(result).toEqual({ identifier: 'MEX-455c57', market: 'xexchange' }); - }); - }); -}); diff --git a/src/test/integration/services/e2e-init.ts b/src/test/integration/services/e2e-init.ts deleted file mode 100644 index e756d2fb9..000000000 --- a/src/test/integration/services/e2e-init.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { Constants, FileUtils } from "@multiversx/sdk-nestjs-common"; -import { Test } from "@nestjs/testing"; -import { ApiConfigService } from "src/common/api-config/api.config.service"; -import { CacheInfo } from "src/utils/cache.info"; -import { KeybaseIdentity } from "src/common/keybase/entities/keybase.identity"; -import { KeybaseService } from "src/common/keybase/keybase.service"; -import { NodeService } from "src/endpoints/nodes/node.service"; -import { ProviderService } from "src/endpoints/providers/provider.service"; -import { PublicAppModule } from "src/public.app.module"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import { TokenService } from "src/endpoints/tokens/token.service"; - -export default class Initializer { - private static cachingService: CacheService; - private static apiConfigService: ApiConfigService; - - static async initialize() { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - Initializer.cachingService = - moduleRef.get(CacheService); - Initializer.apiConfigService = - moduleRef.get(ApiConfigService); - const keybaseService = moduleRef.get(KeybaseService); - const nodeService = moduleRef.get(NodeService); - const providerService = moduleRef.get(ProviderService); - const tokenService = moduleRef.get(TokenService); - - if (Initializer.apiConfigService.getMockKeybases()) { - jest - .spyOn(KeybaseService.prototype, 'getProfile') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(() => new KeybaseIdentity())); - } - - if (Initializer.apiConfigService.getMockTokens()) { - const MOCK_PATH = Initializer.apiConfigService.getMockPath(); - const tokens = FileUtils.parseJSONFile(`${MOCK_PATH}tokens.mock.json`); - jest - .spyOn(TokenService.prototype, 'getAllTokensRaw') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => tokens)); - } - - if (Initializer.apiConfigService.getMockNodes()) { - const MOCK_PATH = Initializer.apiConfigService.getMockPath(); - const nodes = FileUtils.parseJSONFile( - `${MOCK_PATH}nodes.mock.json`, - ); - jest - .spyOn(NodeService.prototype, 'getAllNodesRaw') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => nodes)); - - const heartbeat = FileUtils.parseJSONFile( - `${MOCK_PATH}heartbeat.mock.json`, - ); - jest - .spyOn(NodeService.prototype, 'getHeartbeatAndValidators') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => heartbeat)); - - const queue = FileUtils.parseJSONFile(`${MOCK_PATH}queue.mock.json`); - jest - .spyOn(NodeService.prototype, 'getQueue') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => queue)); - } - - const isInitialized = await Initializer.cachingService.getRemote('isInitialized'); - if (isInitialized === true) { - return; - } - - await this.execute( - 'Flushing db', - async () => await Initializer.cachingService.flushDbRemote(), - ); - - await this.execute('Confirm keybase against keybase.io', async () => await keybaseService.confirmIdentityProfiles()); - await this.fetch(CacheInfo.Nodes.key, async () => await nodeService.getAllNodesRaw()); - await this.fetch(CacheInfo.Providers.key, async () => await providerService.getAllProvidersRaw()); - await this.fetch(CacheInfo.AllEsdtTokens.key, async () => await tokenService.getAllTokensRaw()); - - await Initializer.cachingService.setRemote( - 'isInitialized', - true, - Constants.oneHour(), - ); - } - - private static async fetch(key: string, promise: () => Promise) { - const description = `Fetching ${key}`; - - await this.execute(description, async () => { - const value = await promise(); - await Initializer.cachingService.set(key, value, Constants.oneHour()); - }); - } - - private static async execute( - description: string, - promise: () => Promise, - ) { - console.log(`${new Date().toISODateString()}: ${description}`); - const start = Date.now(); - await promise(); - const duration = ((Date.now() - start) / 1000).toFixed(2); - console.log( - `${new Date().toISODateString()}: ${description} completed. Duration: ${duration}s`, - ); - } -} diff --git a/src/test/integration/services/esdt.e2e-spec.ts b/src/test/integration/services/esdt.e2e-spec.ts deleted file mode 100644 index 8bb919425..000000000 --- a/src/test/integration/services/esdt.e2e-spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { EsdtAddressService } from 'src/endpoints/esdt/esdt.address.service'; -import { Test } from "@nestjs/testing"; -import { PublicAppModule } from "src/public.app.module"; -import { EsdtSupply } from "src/endpoints/esdt/entities/esdt.supply"; -import { NftFilter } from "src/endpoints/nfts/entities/nft.filter"; -import { NftType } from "src/endpoints/nfts/entities/nft.type"; -import { EsdtDataSource } from 'src/endpoints/esdt/entities/esdt.data.source'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { EsdtService } from 'src/endpoints/esdt/esdt.service'; - -describe('ESDT Service', () => { - let esdtService: EsdtService; - let esdtAddressService: EsdtAddressService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - esdtService = moduleRef.get(EsdtService); - esdtAddressService = moduleRef.get(EsdtAddressService); - - }); - - describe("Get ESDT For Address", () => { - it("should return esdts of type MetaESDT", async () => { - const address: string = "erd1k3wtee6vzk47halxwm7qud3mrdjrlw4fyjvuhamtzy4hjhe6htcsv9jcgs"; - const filter = new NftFilter(); - filter.type = NftType.MetaESDT; - const results = await esdtAddressService.getNftsForAddress(address, filter, { from: 0, size: 2 }); - - expect(results).toHaveLength(2); - - for (const result of results) { - expect(result.type).toStrictEqual("MetaESDT"); - } - }); - - it("should return esdts of type SemiFungibleESDT", async () => { - const address: string = "erd1k3wtee6vzk47halxwm7qud3mrdjrlw4fyjvuhamtzy4hjhe6htcsv9jcgs"; - const filter = new NftFilter(); - filter.type = NftType.SemiFungibleESDT; - - const results = await esdtAddressService.getNftsForAddress(address, filter, { from: 0, size: 2 }); - - expect(results).toHaveLength(2); - - for (const result of results) { - expect(result.type).toStrictEqual("SemiFungibleESDT"); - } - }); - - it("should return esdts of type NonFungibleESDT", async () => { - const address: string = "erd1k3wtee6vzk47halxwm7qud3mrdjrlw4fyjvuhamtzy4hjhe6htcsv9jcgs"; - const filter = new NftFilter(); - filter.type = NftType.NonFungibleESDT; - - const results = await esdtAddressService.getNftsForAddress(address, filter, { from: 0, size: 2 }); - - expect(results).toHaveLength(2); - - for (const result of results) { - expect(result.type).toStrictEqual("NonFungibleESDT"); - } - }); - - it("should return esdts of type NonFungibleESDT and SemiFungibleESDT", async () => { - const address: string = "erd1k3wtee6vzk47halxwm7qud3mrdjrlw4fyjvuhamtzy4hjhe6htcsv9jcgs"; - const resultNft = await esdtAddressService.getNftsForAddress(address, { type: NftType.NonFungibleESDT }, { from: 0, size: 100 }); - const resultSft = await esdtAddressService.getNftsForAddress(address, { type: NftType.SemiFungibleESDT }, { from: 0, size: 100 }); - - for (const result of resultNft) { - expect(result.type).toStrictEqual("NonFungibleESDT"); - } - - for (const result of resultSft) { - expect(result.type).toStrictEqual("SemiFungibleESDT"); - } - }); - - it('gateway & elastic esdts of address should be the same', async () => { - const esdtAddress: string = 'erd1qqqqqqqqqqqqqpgqhe8t5jewej70zupmh44jurgn29psua5l2jps3ntjj3'; - const gatewayNfts = await esdtAddressService.getNftsForAddress(esdtAddress, new NftFilter(), { from: 0, size: 25 }, EsdtDataSource.gateway); - const elasticNfts = await esdtAddressService.getNftsForAddress(esdtAddress, new NftFilter(), { from: 0, size: 25 }, EsdtDataSource.elastic); - - const sortedGatewayNfts = gatewayNfts.sort((a, b) => a.identifier.localeCompare(b.identifier)); - const sortedElasticNfts = elasticNfts.sort((a, b) => a.identifier.localeCompare(b.identifier)); - - expect(sortedGatewayNfts).toStrictEqual(sortedElasticNfts); - }); - }); - - describe("Get ESDT Token Properties", () => { - it("should return the properties of the token ( ticker property should not be present )", async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, promise: any) => promise())); - - const tokenIdentifier: string = "EGLDMEX-0be9e5"; - const results = await esdtService.getEsdtTokenProperties(tokenIdentifier); - - if (!results) { - throw new Error("Properties are not defined"); - } - - expect(results.hasOwnProperty("identifier")).toBeTruthy(); - expect(results.hasOwnProperty("name")).toBeTruthy(); - expect(results.hasOwnProperty("owner")).toBeTruthy(); - expect(results.hasOwnProperty("isPaused")).toBeTruthy(); - expect(results.hasOwnProperty("canUpgrade")).toBeTruthy(); - expect(results.hasOwnProperty("canMint")).toBeTruthy(); - expect(results.hasOwnProperty("canBurn")).toBeTruthy(); - expect(results.hasOwnProperty("canChangeOwner")).toBeTruthy(); - expect(results.hasOwnProperty("canPause")).toBeTruthy(); - expect(results.hasOwnProperty("canFreeze")).toBeTruthy(); - expect(results.hasOwnProperty("canWipe")).toBeTruthy(); - }); - }); - - describe('Get Esdt Addresses Roles', () => { - it('return addresses role', async () => { - const tokenIdentifier: string = "EGLDMEX-0be9e5"; - const results = await esdtService.getEsdtAddressesRoles(tokenIdentifier); - - if (!results) { - throw new Error('Roles properties are not defined'); - } - - for (const result of results) { - expect(result.canLocalBurn).toBeDefined(); - expect(result.canLocalMint).toBeDefined(); - expect(result.roles).toBeDefined(); - } - }); - }); - - describe('Get Esdt Addresses Roles Raw', () => { - it('EGLDMEX token should have valid roles', async () => { - const tokenIdentifier: string = "EGLDMEX-0be9e5"; - const results = await esdtService.getEsdtAddressesRolesRaw(tokenIdentifier); - - if (!results) { - throw new Error('Properties are not defined'); - } - - for (const result of results) { - expect(result.canLocalBurn).toBeDefined(); - expect(result.canLocalMint).toBeDefined(); - expect(result.roles).toBeDefined(); - } - }); - }); - - describe('Get Token Supply', () => { - it('should return esdt token supply', async () => { - const tokenIdentifier: string = "EGLDMEX-0be9e5"; - const results = await esdtService.getTokenSupply(tokenIdentifier); - - if (!results) { - throw new Error('Properties are not defined'); - } - expect(results).toHaveStructure(Object.keys(new EsdtSupply())); - }); - }); -}); diff --git a/src/test/integration/services/identities.e2e-spec.ts b/src/test/integration/services/identities.e2e-spec.ts deleted file mode 100644 index 0673c24ee..000000000 --- a/src/test/integration/services/identities.e2e-spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { Test } from "@nestjs/testing"; -import { ApiConfigService } from "src/common/api-config/api.config.service"; -import { Identity } from "src/endpoints/identities/entities/identity"; -import { IdentitiesService } from "src/endpoints/identities/identities.service"; -import { ProviderService } from "src/endpoints/providers/provider.service"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/array.extensions'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/number.extensions'; -import { PublicAppModule } from "src/public.app.module"; -import { Provider } from "src/endpoints/providers/entities/provider"; - -describe('Identities Service', () => { - let identityService: IdentitiesService; - let providerService: ProviderService; - let apiConfigService: ApiConfigService; - let identities: Identity[]; - let providers: Provider[]; - - const ids: string[] = ['justminingfr', 'staking_agency', 'istari_vision']; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - identityService = moduleRef.get(IdentitiesService); - providerService = moduleRef.get(ProviderService); - apiConfigService = moduleRef.get(ApiConfigService); - - identities = await identityService.getAllIdentities(); - providers = await providerService.getProvidersWithStakeInformation(); - }); - - describe('Identities', () => { - it('all identities should have provider stake, topUp and locked', () => { - for (const identity of identities) { - expect(identity).toHaveProperty('stake'); - expect(identity).toHaveProperty('topUp'); - expect(identity).toHaveProperty('locked'); - } - }); - - it('should be sorted by locked amount', () => { - for (let index = 1; index < identities.length; index++) { - const currentIdentity = identities[index]; - const previousIdentity = identities[index - 1]; - - expect(currentIdentity).toBeDefined(); - expect(previousIdentity).toHaveProperty('locked'); - expect(currentIdentity).toHaveProperty('locked'); - - if (Number(currentIdentity.locked) > Number(previousIdentity.locked)) { - throw new Error(`Invalid sorting by locked for current identity '${currentIdentity.identity ?? currentIdentity.name}' and previous identity '${previousIdentity.identity ?? previousIdentity.name}'`); - } - } - }); - - it('should distribution sum be 1', () => { - for (const identity of identities) { - if (identity.distribution) { - const distributionValues = Object.values(identity.distribution).filter(x => x !== null); - if (distributionValues.length > 0) { - const sum = distributionValues.sum(); - - expect(sum).toStrictEqual(1); - } - } - } - }); - - it('some identities should be confirmed', () => { - expect(identities.length).toBeGreaterThanOrEqual(32); - }); - - it('all providers identities should appear', () => { - if (!apiConfigService.getMockNodes()) { - for (const provider of providers) { - if (provider.identity && provider.locked !== '0') { - const providerIdentity = identities.find(({ identity }) => identity === provider.identity); - - expect(providerIdentity?.identity).toStrictEqual(provider.identity); - expect(providerIdentity).toHaveProperty('locked'); - expect(providerIdentity).toHaveProperty('name'); - } - } - } - }); - }); - - describe('Get All Identities Raw', () => { - it('should return all identities raw', async () => { - const results = await identityService.getAllIdentitiesRaw(); - - for (const result of results) { - expect(result).toBeInstanceOf(Object); - } - }); - }); - - describe('Get Identities', () => { - it('should return a list of identities based on ids', async () => { - const results = await identityService.getIdentities(ids); - - for (const result of results) { - expect(result).toHaveProperties([ - 'apr', 'avatar', 'description', - 'distribution', 'identity', 'location', - 'locked', 'name', 'providers', - 'rank', 'score', 'stake', - 'stakePercent', 'topUp', 'validators', 'website', - ]); - } - }); - }); -}); diff --git a/src/test/integration/services/keybase.e2e-spec.ts b/src/test/integration/services/keybase.e2e-spec.ts deleted file mode 100644 index 067ea8611..000000000 --- a/src/test/integration/services/keybase.e2e-spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Test } from "@nestjs/testing"; -import { KeybaseIdentity } from "src/common/keybase/entities/keybase.identity"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import { PublicAppModule } from "src/public.app.module"; -import { KeybaseService } from "src/common/keybase/keybase.service"; - -describe('Keybase Service', () => { - let keybaseService: KeybaseService; - - const identity: string = 'cryptoshigo'; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - keybaseService = moduleRef.get(KeybaseService); - }); - - beforeEach(() => { jest.restoreAllMocks(); }); - - describe('Get Profile', () => { - it('should return identity profile', () => { - const profile = keybaseService.getProfile(identity); - - expect(profile).toHaveStructure(Object.keys(new KeybaseIdentity())); - }); - }); -}); diff --git a/src/test/integration/services/nft.e2e-spec.ts b/src/test/integration/services/nft.e2e-spec.ts deleted file mode 100644 index 3caff5baf..000000000 --- a/src/test/integration/services/nft.e2e-spec.ts +++ /dev/null @@ -1,836 +0,0 @@ -import { NftQueryOptions } from 'src/endpoints/nfts/entities/nft.query.options'; -import { Test } from "@nestjs/testing"; -import { NftService } from "src/endpoints/nfts/nft.service"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/array.extensions'; -import { PublicAppModule } from "src/public.app.module"; -import { NftFilter } from "src/endpoints/nfts/entities/nft.filter"; -import { NftType } from "src/endpoints/nfts/entities/nft.type"; -import { NftOwner } from 'src/endpoints/nfts/entities/nft.owner'; -import { EsdtAddressService } from 'src/endpoints/esdt/esdt.address.service'; -import { NftAccount } from 'src/endpoints/nfts/entities/nft.account'; -import { QueryPagination } from 'src/common/entities/query.pagination'; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { PluginService } from 'src/common/plugins/plugin.service'; -import { Nft } from 'src/endpoints/nfts/entities/nft'; -import { ScamType } from 'src/common/entities/scam-type.enum'; - - -describe('Nft Service', () => { - let nftService: NftService; - - const mockNftAccount: NftAccount = { - identifier: 'MOS-b9b4b2-2710', - collection: 'MOS-b9b4b2', - timestamp: undefined, - attributes: 'dGFnczpTdHJhbW9zaSxSb21hbmlhLEVscm9uZCxSb21hbmlhREFPO21ldGFkYXRhOlFtVVVoQW1CUUtHa1NxTjc3NU5aQUFZVWFxZDhzc01hZEZnMlVZU0VDU0VSejYvOTE0Lmpzb24=', - nonce: 10000, - type: NftType.NonFungibleESDT, - name: 'Stramosi #10000', - creator: 'erd1qqqqqqqqqqqqqpgq0p9k56lutyjsz288gsrtu64nfj43ll8vys5sjy7luv', - royalties: 10, - uris: [ - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1VVWhBbUJRS0drU3FONzc1TlpBQVlVYXFkOHNzTWFkRmcyVVlTRUNTRVJ6Ni85MTQucG5n', - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1VVWhBbUJRS0drU3FONzc1TlpBQVlVYXFkOHNzTWFkRmcyVVlTRUNTRVJ6Ni85MTQuanNvbg==', - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1VVWhBbUJRS0drU3FONzc1TlpBQVlVYXFkOHNzTWFkRmcyVVlTRUNTRVJ6Ni9jb2xsZWN0aW9uLmpzb24=', - ], - url: 'https://media.elrond.com/nfts/asset/QmUUhAmBQKGkSqN775NZAAYUaqd8ssMadFg2UYSECSERz6/914.png', - media: undefined, - isWhitelistedStorage: true, - thumbnailUrl: '', - tags: ['Stramosi', 'Romania', 'Elrond', 'RomaniaDAO'], - metadata: undefined, - owner: 'erd15gculjmu3r62ldlwyguqdgddez35r2lv6ka8j7s6pwhqlc80httqljzwgm', - balance: '', - supply: undefined, - decimals: undefined, - ticker: '', - scamInfo: undefined, - price: undefined, - valueUsd: undefined, - score: undefined, - isNsfw: undefined, - rank: undefined, - rarities: undefined, - }; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - nftService = moduleRef.get(NftService); - - }); - - beforeEach(() => { jest.restoreAllMocks(); }); - - - describe("NFT List", () => { - it(`should return a list with 25 nfts and verify if nft contains property`, async () => { - const nfts = await nftService.getNfts({ from: 0, size: 25 }, new NftFilter()); - expect(nfts.length).toBe(25); - - for (const nft of nfts) { - expect(nft.hasOwnProperty("identifier")).toBeTruthy(); - expect(nft.hasOwnProperty("collection")).toBeTruthy(); - expect(nft.hasOwnProperty("timestamp")).toBeTruthy(); - } - }); - - it(`should return a list with 50 nfts and verify if nft contains property`, async () => { - const nfts = await nftService.getNfts({ from: 0, size: 50 }, new NftFilter()); - - expect(nfts.length).toBe(50); - - for (const nft of nfts) { - expect(nft.hasOwnProperty("identifier")).toBeTruthy(); - expect(nft.hasOwnProperty("collection")).toBeTruthy(); - expect(nft.hasOwnProperty("timestamp")).toBeTruthy(); - } - }); - - it("should verify if the first element in the pagination filter (from: 0) is different from (from: 1) ", async () => { - const nft_0 = await nftService.getNfts({ from: 0, size: 1 }, new NftFilter()); - const nft_1 = await nftService.getNfts({ from: 1, size: 2 }, new NftFilter()); - - expect(nft_0).not.toStrictEqual(nft_1); - }); - }); - - describe("NFT Filters", () => { - it("should return a list with NonFungibleESDTs from a specific collection", async () => { - const filters = new NftFilter(); - filters.collection = 'CPA-c6d2fb'; - filters.type = NftType.NonFungibleESDT; - - const nfts = await nftService.getNfts({ from: 0, size: 10 }, filters); - - for (const nft of nfts) { - expect(nft.collection).toStrictEqual("CPA-c6d2fb"); - expect(nft.type).toStrictEqual(NftType.NonFungibleESDT); - } - }); - - it("should return a list of NonFungibleESDT with specific identifiers", async () => { - const filters = new NftFilter(); - filters.identifiers = ['EROBOT-527a29-c4', 'EROBOT-527a29-c3']; - - const nfts = await nftService.getNfts({ from: 0, size: 100 }, filters); - const nftsIdentifiers = nfts.map((nft) => nft.identifier); - - expect(nftsIdentifiers.includes("EROBOT-527a29-c4")).toBeTruthy(); - expect(nftsIdentifiers.includes("EROBOT-527a29-c3")).toBeTruthy(); - expect(nftsIdentifiers).toHaveLength(2); - }); - - it("should return a list with all nfts of the creator", async () => { - const filters = new NftFilter(); - filters.creator = "erd1qqqqqqqqqqqqqpgqlxyw866pd8pvfqvphgsz9dgx5mr44uv5ys5sew4epr"; - filters.type = NftType.NonFungibleESDT; - - const nfts = await nftService.getNfts({ from: 0, size: 10 }, filters); - - for (const nft of nfts) { - expect(nft.collection).toStrictEqual("EROBOT-527a29"); - expect(nft.creator).toStrictEqual("erd1qqqqqqqqqqqqqpgqlxyw866pd8pvfqvphgsz9dgx5mr44uv5ys5sew4epr"); - expect(nft.type).toStrictEqual(NftType.NonFungibleESDT); - } - }); - - it("should return a list with all nfts that contains tags", async () => { - const filters = new NftFilter(); - filters.tags = ["xportal"]; - - const nfts = await nftService.getNfts({ from: 0, size: 10 }, filters); - expect(nfts).toHaveLength(10); - - for (const nft of nfts) { - expect(nft.tags).toBeDefined(); - } - }); - - it("should return a list with all nft that has option withOwner on true", async () => { - const filters = new NftFilter(); - filters.identifiers = ['EROBOT-527a29-c4']; - - const options = new NftQueryOptions(); - options.withOwner = true; - - const results = await nftService.getNfts({ from: 0, size: 10 }, filters, options); - - const nftsIdentifiers = results.map((result) => result.identifier); - - expect(nftsIdentifiers.includes("EROBOT-527a29-c4")).toBeTruthy(); - }); - - it(`should verify if returned values of /nfts?identifiers=EROBOT-527a29-c4&withOwner=true has the same values as nfts/EROBOT-527a29-c4`, async () => { - const identifier: string = "EROBOT-527a29-c4"; - const filter = new NftFilter(); - filter.identifiers = [identifier]; - - const results = await nftService.getNfts({ from: 0, size: 1 }, filter); - const result = await nftService.getSingleNft(identifier); - - if (!result) { - throw new Error("Properties are not defined"); - } - - for (const nftResult of results) { - expect(nftResult.identifier).toStrictEqual(result.identifier); - expect(nftResult.collection).toStrictEqual(result.collection); - expect(nftResult.attributes).toStrictEqual(result.attributes); - expect(nftResult.nonce).toStrictEqual(result.nonce); - expect(nftResult.type).toStrictEqual(result.type); - expect(nftResult.creator).toStrictEqual(result.creator); - expect(nftResult.royalties).toStrictEqual(result.royalties); - expect(nftResult.isWhitelistedStorage).toStrictEqual(result.isWhitelistedStorage); - expect(nftResult.tags).toStrictEqual(result.tags); - } - }); - - it(`should return a list with SemiFungibleESDT tokens`, async () => { - const nfts = await nftService.getNfts({ from: 0, size: 25 }, { type: NftType.SemiFungibleESDT }); - - expect(nfts.length).toStrictEqual(25); - - for (const nft of nfts) { - expect(nft.type).toStrictEqual(NftType.SemiFungibleESDT); - } - }); - - it(`should return a list with NonFungibleESDT tokens`, async () => { - const nfts = await nftService.getNfts({ from: 0, size: 25 }, { type: NftType.NonFungibleESDT }); - - expect(nfts.length).toStrictEqual(25); - - for (const nft of nfts) { - expect(nft.type).toStrictEqual(NftType.NonFungibleESDT); - } - }); - - it(`should verify if all returned nfts from a specific collection contain the owner property`, async () => { - const filters = new NftFilter(); - filters.collection = "MOS-b9b4b2"; - - const options = new NftQueryOptions(); - options.withOwner = true; - - const results = await nftService.getNfts({ from: 0, size: 500 }, filters, options); - - const nftsOwner = results.map((result) => result.owner); - - expect(nftsOwner).toBeDefined(); - expect(nftsOwner.length).toStrictEqual(500); - }); - - it("should verify if all esdt of type NonFungibleTokens contains owner property and need to be defined", async () => { - const options = new NftQueryOptions(); - options.withOwner = true; - - const nfts = await nftService.getNfts({ from: 50, size: 25 }, { type: NftType.NonFungibleESDT }, options); - const nftOwners = nfts.map((nft) => nft.owner); - - expect(nftOwners).toHaveLength(25); - }); - - it("should verify if all esdt of type SemiFungibleESDT contains owner property and need to be defined", async () => { - const options = new NftQueryOptions(); - options.withOwner = true; - - const nfts = await nftService.getNfts({ from: 50, size: 25 }, { type: NftType.SemiFungibleESDT }, options); - const nftOwners = nfts.map((nft) => nft.owner); - - expect(nftOwners).toHaveLength(25); - }); - - it('should return all esdt of type NonFungibleESDT details from two collections', async () => { - const filter = new NftFilter(); - filter.collections = ["EROBOT-527a29", "COLLARV2-467a53"]; - - const results = await nftService.getNfts({ from: 0, size: 10 }, filter); - - for (const result of results) { - expect(result.type).toStrictEqual('NonFungibleESDT'); - } - }); - - it('should return nft details with search filter applied and expect that collection name to be found based on search term', async () => { - const filter = new NftFilter(); - filter.search = 'eRobots'; - - const results = await nftService.getNfts({ from: 0, size: 1 }, filter); - - for (const result of results) { - expect(result.collection).toStrictEqual('EROBOT-527a29'); - } - }); - - it('should return 10 nfts that have uris defined', async () => { - const filter = new NftFilter(); - filter.hasUris = true; - - const results = await nftService.getNfts({ from: 0, size: 10 }, filter); - expect(results.length).toStrictEqual(10); - - for (const result of results) { - expect(result.uris).toBeDefined(); - } - }); - - it('should return 10 nfts that have timestamp > 1654630698 ', async () => { - const filter = new NftFilter(); - filter.after = 1654630698; - - const results = await nftService.getNfts({ from: 0, size: 10 }, filter); - expect(results.length).toStrictEqual(10); - - for (const result of results) { - expect(result.timestamp).toBeGreaterThanOrEqual(1654630698); - } - }); - }); - - describe("NFT Count", () => { - it("should return the number of nfts from a collection", async () => { - const filters = new NftFilter(); - filters.collection = 'EROBOT-527a29'; - - const count = await nftService.getNftCount(filters); - - expect(typeof count).toBe("number"); - expect(count).toBeGreaterThanOrEqual(100); - }); - - it("should return the number of nfts from a specific list of identifiers", async () => { - const filters = new NftFilter(); - filters.identifiers = ['EROBOT-527a29-c4', 'EROBOT-527a29-c3']; - - const count = await nftService.getNftCount(filters); - - expect(typeof count).toBe("number"); - expect(count).toStrictEqual(2); - }); - - it("should return the number of nfts from a specific creator", async () => { - const filters = new NftFilter(); - filters.creator = "erd1qqqqqqqqqqqqqpgqlxyw866pd8pvfqvphgsz9dgx5mr44uv5ys5sew4epr"; - - const count = await nftService.getNftCount(filters); - - expect(typeof count).toBe("number"); - expect(count).toBeGreaterThanOrEqual(100); - }); - - it("should return the number of nfts with name specified", async () => { - const filters = new NftFilter(); - filters.name = "Gritty Summit Chaser"; - const count = await nftService.getNftCount(filters); - - expect(typeof count).toBe("number"); - expect(count).toBeGreaterThanOrEqual(1); - }); - - it("should return the number of nfts with collection filter applied", async () => { - const filters = new NftFilter(); - filters.collections = ['EROBOT-527a29', 'MEDAL-ae074f']; - - const count = await nftService.getNftCount(filters); - - expect(count).toBeGreaterThanOrEqual(100); - }); - - it("should return 0 if one collection isWhitelistedStorage = true ", async () => { - const filters = new NftFilter(); - filters.collection = "LKMEX-f4d898"; - filters.isWhitelistedStorage = true; - - const count = await nftService.getNftCount(filters); - expect(count).toStrictEqual(0); - }); - - it("should return 10000 nfts if collection isWhitelistedStorage ", async () => { - const filters = new NftFilter(); - filters.collection = "MOS-b9b4b2"; - filters.isWhitelistedStorage = true; - - const count = await nftService.getNftCount(filters); - expect(count).toStrictEqual(10000); - }); - - it("should return total nfts count from a specific nonce range ", async () => { - const filters = new NftFilter(); - filters.collection = "EBULB-36c762"; - filters.nonceAfter = 30; - filters.nonceBefore = 40; - - const count = await nftService.getNftCount(filters); - expect(count).toStrictEqual(11); - }); - - it(`should return total number of nfts from address with type MetaESDT`, async () => { - const address: string = "erd1qqqqqqqqqqqqqpgqr8z5hkwek0pmytcvla86qjusn4hkufjlrp8s7hhkjk"; - const count = await nftService.getNftCountForAddress(address, { type: NftType.MetaESDT }); - - expect(count > 0).toBeTruthy(); - }); - - it(`should verify collections count for a given address because test simulates collections count with/without MetaESDT`, async () => { - const address: string = "erd1qqqqqqqqqqqqqpgqr8z5hkwek0pmytcvla86qjusn4hkufjlrp8s7hhkjk"; - const filter = new NftFilter(); - filter.excludeMetaESDT = true; - const results = await nftService.getNftCountForAddress(address, new NftFilter()); - const resultsexcludeMetaESDT = await nftService.getNftCountForAddress(address, filter); - - expect(resultsexcludeMetaESDT).toBeLessThan(results); - }); - - it(`should return esdt count for address with type SemiFungibleESDT`, async () => { - const address: string = "erd1dgctxljv7f6x8ngsqden99snygjw37dle3t8ratn59r33slsy4rqc3dpsh"; - const count = await nftService.getNftCountForAddress(address, { type: NftType.SemiFungibleESDT }); - - expect(count).toBeGreaterThanOrEqual(0); - }); - - it(`should return esdt count for address with type NonFungibleESDT`, async () => { - const address: string = "erd1k3wtee6vzk47halxwm7qud3mrdjrlw4fyjvuhamtzy4hjhe6htcsv9jcgs"; - const count = await nftService.getNftCountForAddress(address, { type: NftType.NonFungibleESDT }); - - expect(count).toBeGreaterThanOrEqual(0); - }); - }); - - describe("NFTS Address", () => { - it("should return a list of NonFungible tokens for a specific address", async () => { - const address: string = "erd1fs7dp439gw2at58a2pqn3hdnxqh5vskq5uzjdf9kajkxy3p0vy7qeh7k00"; - - const results = await nftService.getNftsForAddress(address, { from: 0, size: 100 }, { type: NftType.NonFungibleESDT }); - - for (const result of results) { - expect(result.type).toStrictEqual(NftType.NonFungibleESDT); - - expect(result.hasOwnProperty("identifier")).toBeTruthy(); - expect(result.hasOwnProperty("collection")).toBeTruthy(); - expect(result.hasOwnProperty("timestamp")).toBeTruthy(); - expect(result.hasOwnProperty("attributes")).toBeTruthy(); - expect(result.hasOwnProperty("nonce")).toBeTruthy(); - expect(result.hasOwnProperty("name")).toBeTruthy(); - expect(result.hasOwnProperty("creator")).toBeTruthy(); - expect(result.hasOwnProperty("royalties")).toBeTruthy(); - } - }); - - it('should return a list of only with NonFungible/SemiFungibleESDT if excludeMetaESDT filter is applied', async () => { - const address: string = "erd1tq4q846crg8ptwpg4zr985q0s9gj57ugr9da87nqmpg5fu6vjy8qkqd0k6"; - const filter = new NftFilter(); - filter.excludeMetaESDT = true; - const results = await nftService.getNftsForAddress(address, new QueryPagination({ size: 1000 }), filter); - - for (const result of results) { - expect(result.type).not.toEqual("MetaESDT"); - } - }); - - it("should return a list of NonFungibleESDT for a specific address without supply even if withSupply property is true", async () => { - const address: string = "erd1yl6f7cq9gpuprwthxf0c2gsvmnuezwqkqmzf8e40u87t7592af7qpl05cv"; - const options = new NftQueryOptions(); - options.withSupply = true; - - const results = await nftService.getNftsForAddress(address, { from: 0, size: 100 }, { type: NftType.NonFungibleESDT }, undefined, options); - - for (const result of results) { - expect(result.type).toStrictEqual(NftType.NonFungibleESDT); - expect(result.supply).not.toBeDefined(); - } - }); - - it("when withSupply property is false should return a list of tokens (NonFungible, SemiFungibleESDT, MetaESDT) without supply attribute applied", async () => { - const address: string = "erd1yl6f7cq9gpuprwthxf0c2gsvmnuezwqkqmzf8e40u87t7592af7qpl05cv"; - const options = new NftQueryOptions(); - options.withSupply = false; - - const nftResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.NonFungibleESDT }, undefined, options); - for (const result of nftResults) { - expect(result.type).toStrictEqual(NftType.NonFungibleESDT); - expect(result.supply).not.toBeDefined(); - } - - const sftResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.SemiFungibleESDT }, undefined, options); - for (const result of sftResults) { - expect(result.type).toStrictEqual(NftType.SemiFungibleESDT); - expect(result.supply).not.toBeDefined(); - } - - const metaEsdtResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.MetaESDT }, undefined, options); - for (const result of metaEsdtResults) { - expect(result.type).toStrictEqual(NftType.MetaESDT); - expect(result.supply).not.toBeDefined(); - } - }); - - it("should return a list of nfts for a specific address with supply attribute applied only for SemiFungibleESDT and MetaESDT", async () => { - const address: string = "erd1yl6f7cq9gpuprwthxf0c2gsvmnuezwqkqmzf8e40u87t7592af7qpl05cv"; - const options = new NftQueryOptions(); - options.withSupply = true; - - const nftResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.NonFungibleESDT }, undefined, options); - for (const result of nftResults) { - expect(result.type).toStrictEqual(NftType.NonFungibleESDT); - expect(result.supply).not.toBeDefined(); - } - - const sftResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.SemiFungibleESDT }, undefined, options); - for (const result of sftResults) { - expect(result.type).toStrictEqual(NftType.SemiFungibleESDT); - expect(result.supply).toBeDefined(); - } - - const metaEsdtResults = await nftService.getNftsForAddress(address, { from: 0, size: 5 }, { type: NftType.MetaESDT }, undefined, options); - for (const result of metaEsdtResults) { - expect(result.type).toStrictEqual(NftType.MetaESDT); - expect(result.supply).toBeDefined(); - } - }); - - it("returned list should not have owner property defined", async () => { - const address: string = "erd1fs7dp439gw2at58a2pqn3hdnxqh5vskq5uzjdf9kajkxy3p0vy7qeh7k00"; - const options = new NftQueryOptions(); - options.withSupply = true; - - const results = await nftService.getNftsForAddress(address, { from: 0, size: 100 }, { type: NftType.NonFungibleESDT }, undefined, options); - - for (const result of results) { - expect(result.owner).not.toBeDefined(); - } - }); - }); - - describe("NFT Address", () => { - it("should return one nft for a specific account", async () => { - jest - .spyOn(EsdtAddressService.prototype, 'getNftsForAddress') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => [mockNftAccount])); - - const address: string = "erd15gculjmu3r62ldlwyguqdgddez35r2lv6ka8j7s6pwhqlc80httqljzwgm"; - const identifier: string = "MOS-b9b4b2-2710"; - const results = await nftService.getNftForAddress(address, identifier); - - if (!results) { - throw new Error("Properties are not defined"); - } - - expect(results.hasOwnProperty("identifier")).toBeTruthy(); - expect(results.hasOwnProperty("collection")).toBeTruthy(); - expect(results.hasOwnProperty("timestamp")).toBeTruthy(); - expect(results.hasOwnProperty("attributes")).toBeTruthy(); - expect(results.hasOwnProperty("nonce")).toBeTruthy(); - expect(results.hasOwnProperty("name")).toBeTruthy(); - expect(results.hasOwnProperty("creator")).toBeTruthy(); - expect(results.hasOwnProperty("royalties")).toBeTruthy(); - }); - - it("should return undefined if account does not contains an nft", async () => { - jest - .spyOn(EsdtAddressService.prototype, 'getNftsForAddress') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => [])); - - const address: string = "erd15gculjmu3r62ldlwyguqdgddez35r2lv6ka8j7s6pwhqlc80httqljzwgm"; - const identifier: string = "MOS-b9b4b2-2710"; - const results = await nftService.getNftForAddress(address, identifier); - - expect(results).toBeUndefined(); - }); - - it("should return XMEX-fda355-15 token details from a specific account", async () => { - const address: string = "erd1wqgvggslggjgjjl0wpgjhknr2carzd07l4s0cqvqyt5haqmlsvks05vqvp"; - const identifier: string = "XMEX-fda355-15"; - const results = await nftService.getNftForAddress(address, identifier); - - expect(results?.unlockEpoch).toStrictEqual(1410); - }); - - }); - - describe("NFT Owners", () => { - it('should return nft owner', async () => { - const identifier: string = "EROBOT-527a29-c4"; - const owners = await nftService.getNftOwners(identifier, { from: 0, size: 1 }); - - if (!owners) { - throw new Error('Nft properties are not defined'); - } - - expect(owners).toHaveLength(1); - - for (const owner of owners) { - expect(owner).toHaveStructure(Object.keys(new NftOwner())); - expect(owner.balance).toStrictEqual("1"); - } - }); - - it('should return undefined because test simulates that the given identifier is not an nft', async () => { - const identifier: string = 'WEGLD-bd4d79'; - const results = await nftService.getNftOwners(identifier, { from: 0, size: 1 }); - - expect(results).toBeUndefined(); - }); - }); - - describe("Single NFT", () => { - it("should return one nft from collection", async () => { - const identifier: string = "EROBOT-527a29-c4"; - const result = await nftService.getSingleNft(identifier); - - if (!result) { - throw new Error("Properties are not defined"); - } - - expect(result.type).toStrictEqual(NftType.NonFungibleESDT); - expect(result.identifier).toStrictEqual("EROBOT-527a29-c4"); - expect(result.creator).toBeDefined(); - }); - - it('should return undefined', async () => { - jest.spyOn(NftService.prototype, 'getNftsInternal') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_pagination: QueryPagination, _filter: NftFilter, _identifier?: string) => [])); - - const identifier: string = " "; - const result = await nftService.getSingleNft(identifier); - - expect(result).toBeUndefined(); - }); - }); - - describe("Get NFT Identifier Media", () => { - it("should verify if nft media is defined and receive same value", async () => { - const identifier: string = "EROBOT-527a29-c4"; - const filter = new NftFilter(); - filter.identifiers = [identifier]; - - const singleNft = await nftService.getSingleNft(identifier); - const nfts = await nftService.getNfts({ from: 0, size: 1 }, filter); - - if (!singleNft) { - throw new Error("Properties are not defined"); - } - for (const nft of nfts) { - expect(nft.media).toStrictEqual(singleNft.media); - } - }); - }); - - describe('getNftSupply', () => { - it('should return nft supply details', async () => { - const identifier: string = "EROBOT-527a29-c4"; - const result = await nftService.getNftSupply(identifier); - - expect(result).toStrictEqual("1"); - }); - - it('should return undefined because test simulates that identifier does not have the correct format', async () => { - const identifier: string = "EROBOT527a29c4"; - const result = await nftService.getNftSupply(identifier); - - expect(result).toBeUndefined(); - }); - - it('should return undefined because test simulates that nft length is equal with 0', async () => { - jest.spyOn(NftService.prototype, 'getNftsInternal') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_pagination: QueryPagination, _filter: NftFilter, _identifier?: string) => [])); - - const identifier: string = 'EROBOT-527a29-c4'; - const result = await nftService.getNftSupply(identifier); - - expect(result).toBeUndefined(); - }); - }); - - describe('getNftOwnersCount', () => { - it('should return total number of esdts token', async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, promise: any) => promise())); - - jest.spyOn(NftService.prototype, 'getNftOwnersCountRaw') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_dentifier: string) => 1)); - - const identifier: string = "EROBOT-527a29"; - const result = await nftService.getNftOwnersCount(identifier); - - expect(result).toStrictEqual(1); - }); - - it('should return undefined because test simulates that esdt owners are null', async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, promise: any) => promise())); - - jest.spyOn(NftService.prototype, 'getNftOwnersCountRaw') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_dentifier: string) => null)); - - const identifier: string = "EROBOT-527a29"; - const result = await nftService.getNftOwnersCount(identifier); - - expect(result).toBeUndefined(); - }); - }); - - describe('NFT scam info', () => { - beforeEach(() => { - jest - .spyOn(PluginService.prototype, 'batchProcessNfts') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (nfts: Nft[], withScamInfo?: boolean | undefined) => { - for (const nft of nfts) { - if (withScamInfo == true) { - nft.scamInfo = { type: ScamType.potentialScam }; - } - } - })); - - jest - .spyOn(PluginService.prototype, 'processNfts') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (nft: Nft[], _withScamInfo?: boolean) => { - for (const item of nft) { - if (item.collection == 'LOTTERY-7cae2f') { - item.scamInfo = { type: ScamType.potentialScam }; - } - } - - })); - }); - - it("should return a list of NFTs with scam info property present", async () => { - const filter = new NftFilter({ collection: 'LOTTERY-7cae2f' }); - - const options = new NftQueryOptions({ withScamInfo: true }); - - const nfts = await nftService.getNfts({ from: 0, size: 10 }, filter, options); - - for (const nft of nfts) { - expect(nft.scamInfo).toBeDefined(); - expect(nft.scamInfo?.type).toStrictEqual(ScamType.potentialScam); - } - }); - - it("should return a list of NFTs with scam info property present", async () => { - const filter = new NftFilter({ collection: 'LOTTERY-7cae2f' }); - - const options = new NftQueryOptions({ withScamInfo: true }); - - const nfts = await nftService.getNftsForAddress('erd1ar8gg37lu2reg5zpmtmqawqe65fzfsjd2v3p4m993xxjnu8azssq86f24k', { from: 0, size: 10 }, filter, undefined, options); - - for (const nft of nfts) { - expect(nft.scamInfo).toBeDefined(); - expect(nft.scamInfo?.type).toStrictEqual(ScamType.potentialScam); - } - }); - - it("should return a list of NFTs without scam info property", async () => { - const filter = new NftFilter({ collection: 'ROCK-6b8ac9-38' }); - const options = new NftQueryOptions({ withScamInfo: false }); - const nfts = await nftService.getNfts({ from: 0, size: 10 }, filter, options); - - for (const nft of nfts) { - expect(nft.scamInfo).toBeUndefined(); - } - }); - - it("should return scam info for NFT", async () => { - const identifier = 'LOTTERY-7cae2f-01'; - - const nft = await nftService.getSingleNft(identifier); - - expect(nft?.scamInfo).toBeDefined(); - expect(nft?.scamInfo?.type).toStrictEqual(ScamType.potentialScam); - }); - - it("should not return scam info for NFT", async () => { - const identifier = 'TSTMNT-700bfc-01'; - - const nft = await nftService.getSingleNft(identifier); - - expect(nft?.scamInfo).toBeUndefined(); - }); - - it("should return token details and unlockEpoch should be defined", async () => { - const identifier = 'XMEX-fda355-21'; - - const nft = await nftService.getSingleNft(identifier); - - expect(nft?.unlockEpoch).toStrictEqual(1140); - }); - - it("should return scam info for address NFT", async () => { - const identifier = 'LOTTERY-7cae2f-01'; - - const nft = await nftService.getNftForAddress('erd1ar8gg37lu2reg5zpmtmqawqe65fzfsjd2v3p4m993xxjnu8azssq86f24k', identifier); - - expect(nft?.scamInfo).toBeDefined(); - expect(nft?.scamInfo?.type).toStrictEqual(ScamType.potentialScam); - }); - - it("should not return scam info for address NFT", async () => { - const identifier = 'TSTMNT-700bfc-01'; - - const nft = await nftService.getNftForAddress('erd1dv9sw8a2hy3lv98p3sdqazy420j48wtn3vs9q74ezuamv64tcxrqqxquxv', identifier); - - expect(nft?.scamInfo).toBeUndefined(); - }); - }); - - describe('getNfts', () => { - it('should return a list of NFTs from a specific collection filtered by nonceAfter', async () => { - const collection: string = "EBULB-36c762"; - const filter = new NftFilter(); - filter.collection = collection; - filter.nonceAfter = 30; - - const results = await nftService.getNfts(new QueryPagination({ size: 3 }), filter); - - for (const result of results) { - expect(result.collection).toStrictEqual(collection); - } - const nftNonce = results.map((nft) => nft.nonce); - expect(nftNonce.includes(50)).toBeTruthy(); - expect(nftNonce.includes(49)).toBeTruthy(); - expect(nftNonce.includes(48)).toBeTruthy(); - - const nftIdentifier = results.map((nft) => nft.identifier); - expect(nftIdentifier.includes("EBULB-36c762-32")).toBeTruthy(); - expect(nftIdentifier.includes("EBULB-36c762-31")).toBeTruthy(); - expect(nftIdentifier.includes("EBULB-36c762-30")).toBeTruthy(); - }); - - it('should return a list of NFTs from a specific collection filtered by nonceBefore', async () => { - const collection: string = "EBULB-36c762"; - const filter = new NftFilter(); - filter.collection = collection; - filter.nonceBefore = 30; - - const results = await nftService.getNfts(new QueryPagination({ size: 3 }), filter); - - for (const result of results) { - expect(result.collection).toStrictEqual(collection); - } - const nftNonce = results.map((nft) => nft.nonce); - expect(nftNonce.includes(30)).toBeTruthy(); - expect(nftNonce.includes(29)).toBeTruthy(); - expect(nftNonce.includes(28)).toBeTruthy(); - - const nftIdentifier = results.map((nft) => nft.identifier); - expect(nftIdentifier.includes("EBULB-36c762-1e")).toBeTruthy(); - expect(nftIdentifier.includes("EBULB-36c762-1d")).toBeTruthy(); - expect(nftIdentifier.includes("EBULB-36c762-1c")).toBeTruthy(); - }); - }); -}); diff --git a/src/test/integration/services/nft.extendedattributes.e2e-spec.ts b/src/test/integration/services/nft.extendedattributes.e2e-spec.ts deleted file mode 100644 index cbd513b78..000000000 --- a/src/test/integration/services/nft.extendedattributes.e2e-spec.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { NftExtendedAttributesService } from 'src/endpoints/nfts/nft.extendedattributes.service'; -import { PublicAppModule } from "src/public.app.module"; -import { Test } from '@nestjs/testing'; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; - -describe('Nft Extended Attributes Service', () => { - let nftExtendedAttributesService: NftExtendedAttributesService; - - const attributes = { - description: 'The unique MAW NFT Collection! ', - dna: '7eb2a6d3e1e0c93c5920a941744bd38a547858de', - edition: 395, - createdAt: 1639180014636, - attributes: [ - { trait_type: 'Background', value: '10' }, - { trait_type: 'Body', value: 'Suit_1' }, - { trait_type: 'Mouth', value: 'Mouth_Jail' }, - { trait_type: 'Head', value: 'Head_Trib' }, - { trait_type: 'Left Eye', value: 'EyeL_Metalic_Black' }, - { trait_type: 'Right Eye', value: 'EyeR_Yellow' }, - { trait_type: 'Left Ear', value: 'EarL_Metalic_Gold' }, - { trait_type: 'Right Ear', value: 'EarR_Metalic_Black' }, - { trait_type: 'Drops', value: 'Drop3' }, - ], - compiler: 'Trust Staking', - }; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - nftExtendedAttributesService = moduleRef.get(NftExtendedAttributesService); - }); - - beforeEach(() => { - jest.restoreAllMocks(); - }); - - describe("tryGetExtendedAttributesFromBase64EncodedAttributes", () => { - it("should return attributes from base64 encoded", async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_attributes: string) => { - return Object.assign({}, attributes); - })); - - const results = await nftExtendedAttributesService.tryGetExtendedAttributesFromBase64EncodedAttributes('bWV0YWRhdGE6UW1UQjk3dkhMYkdBZnkxVDJQZFUyWE5QdXlXQjd1Znd3aFNoNU1wTENWbjEybS8zOTUuanNvbg=='); - expect(results.attributes).toBeDefined(); - expect(results).toEqual(expect.objectContaining({ - attributes: expect.arrayContaining([ - expect.objectContaining({ - trait_type: 'Background', value: '10', - }), - ]), - })); - }); - - it("should return undefined because test simulates that attributes are not defined", async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_attributes: string) => { - const response = Object.assign({}, attributes); - response.attributes = []; - return response; - })); - - const results = await nftExtendedAttributesService.tryGetExtendedAttributesFromBase64EncodedAttributes(''); - expect(results).toBeUndefined(); - }); - //ToDo catch(error) - }); - - describe("getTags", () => { - it("should return tags based on attributes", () => { - const attributes: string = "dGFnczpFbHJvbmQsUm9ib3RzLFJvYm90LGVSb2JvdHM="; - const tags = nftExtendedAttributesService.getTags(attributes); - - expect(tags).toStrictEqual(['Elrond', 'Robots', 'Robot', 'eRobots']); - }); - - it("should return undefined because test simulates that attributes are not defined", () => { - const attributes: string = "bWV0YWRhdGE6UW1UQjk3dkhMYkdBZnkxVDJQZFUyWE5QdXlXQjd1Znd3aFNoNU1wTENWbjEybS8zOTUuanNvbg=="; - const tags = nftExtendedAttributesService.getTags(attributes); - expect(tags).toStrictEqual([]); - }); - }); -}); diff --git a/src/test/integration/services/nft.media.e2e-spec.ts b/src/test/integration/services/nft.media.e2e-spec.ts deleted file mode 100644 index deca467e5..000000000 --- a/src/test/integration/services/nft.media.e2e-spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/array.extensions'; -import { Test } from '@nestjs/testing'; -import { MediaMimeTypeEnum } from 'src/endpoints/nfts/entities/media.mime.type'; -import { Nft } from 'src/endpoints/nfts/entities/nft'; -import { NftFilter } from 'src/endpoints/nfts/entities/nft.filter'; -import { NftMedia } from 'src/endpoints/nfts/entities/nft.media'; -import { NftType } from 'src/endpoints/nfts/entities/nft.type'; -import { NftService } from 'src/endpoints/nfts/nft.service'; -import { PublicAppModule } from "src/public.app.module"; -import { NftMediaModule } from 'src/queue.worker/nft.worker/queue/job-services/media/nft.media.module'; -import { NftMediaService } from 'src/queue.worker/nft.worker/queue/job-services/media/nft.media.service'; - -describe('Nft Media Service', () => { - let nftMediaService: NftMediaService; - let nftService: NftService; - let nftIdentifier: string; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [NftMediaModule, PublicAppModule], - }).compile(); - - nftMediaService = moduleRef.get(NftMediaService); - nftService = moduleRef.get(NftService); - - const nfts = await nftService.getNfts({ from: 0, size: 1 }, new NftFilter()); - expect(nfts).toHaveLength(1); - - const nft = nfts[0]; - nftIdentifier = nft.identifier; - }); - - beforeEach(() => { - jest.restoreAllMocks(); - }); - - describe("Refresh Media", () => { - it('should return nft media', async () => { - const nftFilter = new Nft(); - nftFilter.identifier = nftIdentifier; - const refreshMedia = await nftMediaService.refreshMedia(nftFilter); - - if (!refreshMedia) { - throw new Error('Media must be defined'); - } - - for (const media of refreshMedia) { - expect(media.url).toBeDefined(); - expect(media).toHaveStructure(Object.keys(new NftMedia())); - } - }); - - it('should not accept content (media file is too large)', async () => { - jest - .spyOn(NftMediaService.prototype as any, "getFileProperties") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => ({ contentType: MediaMimeTypeEnum.mp4, contentLength: 70000001 }))); - - const nft = new Nft({ type: NftType.NonFungibleESDT, uris: ['some_uris'], identifier: 'LSC-a2b6b5-04' }); - - const mediaRaw = await nftMediaService.refreshMedia(nft); - - expect(mediaRaw?.length).toStrictEqual(1); - expect(mediaRaw?.at(0)?.thumbnailUrl).toStrictEqual(NftMediaService.NFT_THUMBNAIL_DEFAULT); - }); - - it('should not accept content (media mime type is not accepted)', async () => { - jest - .spyOn(NftMediaService.prototype as any, "getFileProperties") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => ({ contentType: "NOT_ACCEPTED", contentLength: 1234 }))); - - const nft = new Nft({ type: NftType.NonFungibleESDT, uris: ['some_uris'], identifier: 'LSC-a2b6b5-02' }); - - const mediaRaw = await nftMediaService.refreshMedia(nft); - - expect(mediaRaw?.length).toStrictEqual(0); - }); - - it('should not accept content (file properties not returned)', async () => { - jest - .spyOn(NftMediaService.prototype as any, "getFileProperties") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => null)); - - const nft = new Nft({ type: NftType.NonFungibleESDT, uris: ['some_uris'], identifier: 'LSC-a2b6b5-03' }); - - const mediaRaw = await nftMediaService.refreshMedia(nft); - - expect(mediaRaw?.length).toStrictEqual(0); - }); - - it('should accept content and return valid media', async () => { - jest - .spyOn(NftMediaService.prototype as any, "getFileProperties") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async () => ({ contentType: "image/png", contentLength: 4761020 }))); - - const nft = new Nft({ type: NftType.NonFungibleESDT, uris: ['aHR0cHM6Ly9pcGZzLmlvL2lwZnMvYmFmeWJlaWVrcHV0a3A3eGR2aXpwaWZ2Yzdkcmp5Mml5M2l4NHU3c3psazdobnR6bTdhZ3UyYjZ2NXEvMzg5Ni5wbmc='], identifier: 'K402-22c4bb-c0', collection: 'K402-22c4bb' }); - - const mediaRaw = await nftMediaService.refreshMedia(nft); - - expect(mediaRaw?.length).toStrictEqual(1); - - if (!mediaRaw) { - throw new Error("Media should be returned"); - } - - expect(mediaRaw[0].fileSize).toStrictEqual(4761020); - expect(mediaRaw[0].fileType).toStrictEqual(MediaMimeTypeEnum.png); - expect(mediaRaw[0].url).toStrictEqual('https://media.elrond.com/nfts/asset/bafybeiekputkp7xdvizpifvc7drjy2iy3ix4u7szlk7hntzm7agu2b6v5q/3896.png'); - expect(mediaRaw[0].thumbnailUrl).toStrictEqual('https://media.elrond.com/nfts/thumbnail/K402-22c4bb-d5990d89'); - }); - }); -}); diff --git a/src/test/integration/services/nft.metadata.e2e-spec.ts b/src/test/integration/services/nft.metadata.e2e-spec.ts deleted file mode 100644 index 311f95076..000000000 --- a/src/test/integration/services/nft.metadata.e2e-spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Test } from "@nestjs/testing"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/array.extensions'; -import { PublicAppModule } from "src/public.app.module"; -import { NftMetadataService } from "src/queue.worker/nft.worker/queue/job-services/metadata/nft.metadata.service"; -import { NftService } from "src/endpoints/nfts/nft.service"; -import { NftFilter } from "src/endpoints/nfts/entities/nft.filter"; -import { Nft } from "src/endpoints/nfts/entities/nft"; -import { NftType } from "src/endpoints/nfts/entities/nft.type"; - -describe('Nft Metadata Service', () => { - let nftMetadataService: NftMetadataService; - let nftService: NftService; - let nftIdentifier: string; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - nftMetadataService = moduleRef.get(NftMetadataService); - nftService = moduleRef.get(NftService); - - const nfts = await nftService.getNfts({ from: 0, size: 1 }, new NftFilter()); - expect(nfts).toHaveLength(1); - - const nft = nfts[0]; - nftIdentifier = nft.identifier; - - }); - - describe('Get Or Refresh Metadata', () => { - it(`it should return NFT properties based on nft value `, async () => { - const properties = new Nft(); - properties.name = 'EGLDRIDEFL-74b819-042191'; - properties.attributes = 'AAAACA+tqHq/YcRVAAAAAAAAAhQAAAAAAAACFAAAAAdEsMbf5CtvAAAAAAAAAAdEsMbf5Ctv'; - const nftReturn = await nftMetadataService.getOrRefreshMetadata(properties); - expect(nftReturn).toBeInstanceOf(Object); - }); - - it(`it should return undefined `, async () => { - const properties = new Nft(); - properties.name = 'EGLDRIDEFL-74b819-042191'; - const nftReturn = await nftMetadataService.getOrRefreshMetadata(properties); - expect(nftReturn).toBeUndefined(); - }); - }); - - describe('Get Metadata', () => { - it(`should return metadata of nft`, async () => { - const property = new Nft(); - property.name = nftIdentifier; - const nftReturn = await nftMetadataService.getMetadata(property); - expect(nftReturn).toBeInstanceOf(Object); - }); - }); - - describe('Refresh Metadata', () => { - it(`should refresh metadata of nft`, async () => { - const property = new Nft(); - property.name = nftIdentifier; - const nftReturn = await nftMetadataService.refreshMetadata(property); - expect(nftReturn).toBeInstanceOf(Object); - }); - }); - - describe('Get Metadata Raw', () => { - it(`should return null if nft.type is MetaESDT`, async () => { - const property = new Nft(); - property.type = NftType.MetaESDT; - const nftReturn = await nftMetadataService.getMetadataRaw(property); - expect(nftReturn).toBeNull(); - }); - }); -}); diff --git a/src/test/integration/services/nft.thumbnail.e2e-spec.ts b/src/test/integration/services/nft.thumbnail.e2e-spec.ts deleted file mode 100644 index 448c402ea..000000000 --- a/src/test/integration/services/nft.thumbnail.e2e-spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Test } from "@nestjs/testing"; -import { Nft } from "src/endpoints/nfts/entities/nft"; -import { NftFilter } from "src/endpoints/nfts/entities/nft.filter"; -import { NftService } from "src/endpoints/nfts/nft.service"; -import { PublicAppModule } from "src/public.app.module"; -import { NftThumbnailModule } from "src/queue.worker/nft.worker/queue/job-services/thumbnails/nft.thumbnail.module"; -import { NftThumbnailService } from "src/queue.worker/nft.worker/queue/job-services/thumbnails/nft.thumbnail.service"; - -describe('Nft Queue Service', () => { - let nftQueueService: NftThumbnailService; - let nftService: NftService; - - const myPinataUrl: string = 'https://wwwine.mypinata.cloud/ipfs/QmXhZjHWSiEijsdf2RS1g5jRvDmkiAufNdqp5qVet6gbbe/998.jpg'; - const elrondMediaUrl: string = 'https://media.elrond.com/nfts/thumbnail/default.png'; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [NftThumbnailModule, PublicAppModule], - }).compile(); - - nftQueueService = moduleRef.get(NftThumbnailService); - nftService = moduleRef.get(NftService); - - const nfts = await nftService.getNfts({ from: 0, size: 1 }, new NftFilter()); - expect(nfts).toHaveLength(1); - - }); - - describe('HasThumbnail Generated', () => { - it('should return true if nft has thumbnail generated', async () => { - const nftFilter = new Nft(); - nftFilter.identifier = 'WWWINE-5a5331-03e6'; - const thumbnailGenerated = await nftQueueService.hasThumbnailGenerated(nftFilter.identifier, myPinataUrl); - expect(thumbnailGenerated).toStrictEqual(true); - }); - - it('should return false if nft does not contain thumbnail generated ', async () => { - const nftFilter = new Nft(); - nftFilter.identifier = 'MEXFARM-e7af52-438c8a'; - const thumbnailGenerated = await nftQueueService.hasThumbnailGenerated(nftFilter.identifier, elrondMediaUrl); - expect(thumbnailGenerated).toStrictEqual(false); - }); - }); -}); diff --git a/src/test/integration/services/process.nfts.e2e-spec.ts b/src/test/integration/services/process.nfts.e2e-spec.ts deleted file mode 100644 index 9d65b9c84..000000000 --- a/src/test/integration/services/process.nfts.e2e-spec.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { Test } from '@nestjs/testing'; -import { Nft } from 'src/endpoints/nfts/entities/nft'; -import { NftType } from 'src/endpoints/nfts/entities/nft.type'; -import { NftService } from 'src/endpoints/nfts/nft.service'; -import { NftWorkerService } from 'src/queue.worker/nft.worker/nft.worker.service'; -import { ProcessNftsModule } from 'src/endpoints/process-nfts/process.nfts.module'; -import { QueryPagination } from 'src/common/entities/query.pagination'; -import { NftFilter } from 'src/endpoints/nfts/entities/nft.filter'; -import { ApiConfigService } from 'src/common/api-config/api.config.service'; -import { Constants } from '@multiversx/sdk-nestjs-common'; -import { NftQueryOptions } from 'src/endpoints/nfts/entities/nft.query.options'; -import { ProcessNftsService } from 'src/endpoints/process-nfts/process.nfts.service'; -import { ProcessNftSettings } from 'src/endpoints/process-nfts/entities/process.nft.settings'; -import nftCollection from 'src/test/data/esdt/nft/nft.example'; - -describe('Process Nft Service', () => { - let processNftService: ProcessNftsService; - - const identifier: Nft = { - identifier: 'EROBOT-527a29-c4', - collection: 'EROBOT-527a29', - timestamp: 1645784238, - attributes: 'dGFnczpFbHJvbmQsIFJvYm90cywgUm9ib3QsIGVSb2JvdHM7bWV0YWRhdGE6UW1lRHhBTlQzOUs4VWdRbzRGWFF4SkdKWURYTVVYZ2dNVlRNY1VBWnpuTnM2cS80MzEuanNvbg==', - nonce: 196, - type: NftType.NonFungibleESDT, - name: 'Elrond Robots #196', - creator: 'erd1qqqqqqqqqqqqqpgqlxyw866pd8pvfqvphgsz9dgx5mr44uv5ys5sew4epr', - royalties: 10, - uris: [ - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1lRHhBTlQzOUs4VWdRbzRGWFF4SkdKWURYTVVYZ2dNVlRNY1VBWnpuTnM2cS80MzEucG5n', - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1lRHhBTlQzOUs4VWdRbzRGWFF4SkdKWURYTVVYZ2dNVlRNY1VBWnpuTnM2cS80MzEuanNvbg==', - 'aHR0cHM6Ly9pcGZzLmlvL2lwZnMvUW1lRHhBTlQzOUs4VWdRbzRGWFF4SkdKWURYTVVYZ2dNVlRNY1VBWnpuTnM2cS9jb2xsZWN0aW9uLmpzb24=', - ], - url: 'https://media.elrond.com/nfts/asset/QmeDxANT39K8UgQo4FXQxJGJYDXMUXggMVTMcUAZznNs6q/431.png', - media: [ - { - url: 'https://media.elrond.com/nfts/thumbnail/default.png', - originalUrl: 'https://media.elrond.com/nfts/thumbnail/default.png', - thumbnailUrl: 'https://media.elrond.com/nfts/thumbnail/default.png', - fileType: 'image/png', - fileSize: 29512, - }, - ], - isWhitelistedStorage: true, - thumbnailUrl: '', - tags: ['elrond', ' robots', ' robot', ' erobots'], - metadata: undefined, - owner: 'erd13w5hlehc42zvhd9u78ylrac9axntn9p9jqn9kvy3c052l8rmt2yqa59l76', - balance: undefined, - supply: '1', - decimals: undefined, - ticker: 'EROBOT-527a29', - scamInfo: undefined, - assets: undefined, - score: undefined, - isNsfw: undefined, - rank: undefined, - rarities: undefined, - }; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [ProcessNftsModule], - }).compile(); - - processNftService = moduleRef.get(ProcessNftsService); - - }, Constants.oneHour() * 1000); - - beforeEach(() => { jest.restoreAllMocks(); }); - - describe("processNft", () => { - it("should force refresh media", async () => { - - jest.spyOn(NftService.prototype, 'getSingleNft') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_identifier) => identifier)); - - jest.spyOn(NftWorkerService.prototype, 'addProcessNftQueueJob') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_nft: Nft, _settings: ProcessNftSettings) => true)); - - const filter = new ProcessNftSettings(); - filter.forceRefreshMedia = true; - const nft: string = 'EROBOT-527a29-c4'; - const process = await processNftService.processNft(nft, filter); - - expect(process).toBeTruthy(); - }); - - it("should force refresh metadata", async () => { - jest.spyOn(NftService.prototype, 'getSingleNft') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_identifier) => identifier)); - - jest.spyOn(NftWorkerService.prototype, 'addProcessNftQueueJob') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_nft: Nft, _settings: ProcessNftSettings) => true)); - - const filter = new ProcessNftSettings(); - filter.forceRefreshMetadata = true; - const nft: string = 'EROBOT-527a29-c4'; - const process = await processNftService.processNft(nft, filter); - - expect(process).toBeTruthy(); - }); - - it("should force refresh thumbnail", async () => { - jest.spyOn(NftService.prototype, 'getSingleNft') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_identifier) => identifier)); - - jest.spyOn(NftWorkerService.prototype, 'addProcessNftQueueJob') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_nft: Nft, _settings: ProcessNftSettings) => true)); - - - const filter = new ProcessNftSettings(); - filter.forceRefreshThumbnail = true; - const nft: string = 'EROBOT-527a29-c4'; - const process = await processNftService.processNft(nft, filter); - - expect(process).toBeTruthy(); - }); - - it("should skip refresh thumbnail", async () => { - jest.spyOn(NftService.prototype, 'getSingleNft') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_identifier) => identifier)); - - jest.spyOn(NftWorkerService.prototype, 'addProcessNftQueueJob') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_nft: Nft, _settings: ProcessNftSettings) => true)); - - - const filter = new ProcessNftSettings(); - filter.skipRefreshThumbnail = true; - const nft: string = 'EROBOT-527a29-c4'; - const process = await processNftService.processNft(nft, filter); - - expect(process).toBeTruthy(); - }); - }); - - describe("processCollection", () => { - it("should process collection", async () => { - jest.spyOn(NftService.prototype, 'getNfts') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_queryPagination: QueryPagination, _filter: NftFilter, _queryOptions?: NftQueryOptions) => nftCollection)); - - jest.spyOn(ApiConfigService.prototype, 'getPoolLimit') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(() => 100)); - - const filter = new ProcessNftSettings(); - filter.skipRefreshThumbnail = true; - - const collection: string = "EROBOT-527a29"; - const process = await processNftService.processCollection(collection, filter); - - expect(process).toStrictEqual({ "EROBOT-527a29-c4": true }); - }); - }); -}); diff --git a/src/test/integration/services/token.asset.e2e-spec.ts b/src/test/integration/services/token.asset.e2e-spec.ts deleted file mode 100644 index 8337fd6a2..000000000 --- a/src/test/integration/services/token.asset.e2e-spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Test } from "@nestjs/testing"; -import { AssetsService } from "src/common/assets/assets.service"; -import { PublicAppModule } from "src/public.app.module"; - -describe('Token Service', () => { - let assetsService: AssetsService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - assetsService = moduleRef.get(AssetsService); - }); - - describe('Get All Assets', () => { - it(`should return all assets`, async () => { - const assets = await assetsService.getAllTokenAssets(); - const assetValues = Object.values(assets); - - for (const asset of assetValues) { - expect(asset).toHaveProperty('website'); - expect(asset).toHaveProperty('description'); - expect(asset).toHaveProperty('status'); - expect(asset).toHaveProperty('pngUrl'); - expect(asset).toHaveProperty('svgUrl'); - } - }); - }); - - describe('Get All Assets Raw', () => { - it('should return all assets raw', async () => { - const assets = await assetsService.getAllTokenAssetsRaw(); - const assetValues = Object.values(assets); - - for (const asset of assetValues) { - expect(asset).toHaveProperty('website'); - expect(asset).toHaveProperty('description'); - expect(asset).toHaveProperty('status'); - expect(asset).toHaveProperty('pngUrl'); - expect(asset).toHaveProperty('svgUrl'); - } - }); - }); -}); diff --git a/src/test/integration/services/token.transfer.e2e-spec.ts b/src/test/integration/services/token.transfer.e2e-spec.ts deleted file mode 100644 index 232e218d5..000000000 --- a/src/test/integration/services/token.transfer.e2e-spec.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { Test } from "@nestjs/testing"; -import tokenDetails from "src/test/data/esdt/token/token.example"; -import { PublicAppModule } from "src/public.app.module"; -import { TransactionLogEvent } from "src/endpoints/transactions/entities/transaction.log.event"; -import { TransactionLog } from "src/endpoints/transactions/entities/transaction.log"; -import { TransactionOperationAction } from "src/endpoints/transactions/entities/transaction.operation.action"; -import { TransactionOperationType } from "src/endpoints/transactions/entities/transaction.operation.type"; -import { TransactionDetailed } from "src/endpoints/transactions/entities/transaction.detailed"; -import { SmartContractResult } from "src/endpoints/sc-results/entities/smart.contract.result"; -import { TokenTransferService } from "src/endpoints/tokens/token.transfer.service"; -import transactionsWithLogs from "src/test/data/transactions/transactions.with.logs"; - -describe('Token Transfer Service', () => { - let tokenTransferService: TokenTransferService; - - const txHash: string = '0a89f1b739e0d522d80159bfd3ba8565d04b175c704559898d0fb024a64aa48d'; - const tokenIdentifier: string = 'RIDE-7d18e9'; - const sender: string = 'erd1hz65lr7ry7sa3p8jjeplwzujm2d7ktj7s6glk9hk8f4zj8znftgqaey5f5'; - let transaction: TransactionDetailed; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - tokenTransferService = moduleRef.get(TokenTransferService); - - transaction = new TransactionDetailed(); - transaction.txHash = txHash; - transaction.sender = sender; - }); - - describe('Get Operations For Transaction Logs', () => { - it('should return operations for transaction logs', async () => { - const operations = await tokenTransferService.getOperationsForTransaction(transaction, transactionsWithLogs); - - for (const operation of operations) { - expect(operation).toHaveProperty('action'); - expect(operation).toHaveProperty('identifier'); - expect(operation).toHaveProperty('receiver'); - expect(operation).toHaveProperty('sender'); - expect(operation).toHaveProperty('type'); - expect(operation).toHaveProperty('value'); - } - }); - - it('should return operations for a local mint event', async () => { - const localMintEvent = new TransactionLogEvent(); - localMintEvent.address = 'erd1qqqqqqqqqqqqqpgqg8a36rqxu4ch5v2522jv5avlun94sdv80n4sygxs94'; - localMintEvent.identifier = 'ESDTLocalMint'; - localMintEvent.topics = [ - "V0VHTEQtYmQ0ZDc5", - "", - "AWNFeF2KAAA=", - ]; - const log = new TransactionLog(); - log.events = [localMintEvent]; - - const operations = await tokenTransferService.getOperationsForTransaction(transaction, [log]); - - expect(operations.length).toStrictEqual(1); - - for (const operation of operations) { - expect(operation.action).toStrictEqual(TransactionOperationAction.localMint); - expect(operation.type).toStrictEqual(TransactionOperationType.esdt); - expect(operation.identifier).toStrictEqual('WEGLD-bd4d79'); - } - }); - - - it('should return operations for a transfer event', async () => { - const transferEvent = new TransactionLogEvent(); - transferEvent.address = 'erd1qqqqqqqqqqqqqpgqg8a36rqxu4ch5v2522jv5avlun94sdv80n4sygxs94'; - transferEvent.identifier = 'ESDTTransfer'; - transferEvent.topics = [ - "V0VHTEQtYmQ0ZDc5", - "", - "AWNFeF2KAAA=", - "iMc4pdJsDjorT56BELVA7pwLcaO+BXVppaew/LSCyPc=", - ]; - const log = new TransactionLog(); - log.events = [transferEvent]; - - const operations = await tokenTransferService.getOperationsForTransaction(transaction, [log]); - - expect(operations.length).toStrictEqual(1); - - for (const operation of operations) { - expect(operation.action).toStrictEqual(TransactionOperationAction.transfer); - expect(operation.type).toStrictEqual(TransactionOperationType.esdt); - expect(operation.identifier).toStrictEqual('WEGLD-bd4d79'); - } - }); - - - it('should return operations for a write log event', async () => { - const writeLogEvent = new TransactionLogEvent(); - writeLogEvent.address = 'erd1qqqqqqqqqqqqqpgqg8a36rqxu4ch5v2522jv5avlun94sdv80n4sygxs94'; - writeLogEvent.identifier = 'writeLog'; - writeLogEvent.topics = [ - "iMc4pdJsDjorT56BELVA7pwLcaO+BXVppaew/LSCyPc=", - "QHRvbyBtdWNoIGdhcyBwcm92aWRlZDogZ2FzIG5lZWRlZCA9IDIwOTcyNTUsIGdhcyByZW1haW5lZCA9IDExNzkwMjc0NQ==", - ]; - writeLogEvent.data = "QDZmNmI="; - const log = new TransactionLog(); - log.events = [writeLogEvent]; - - const operations = await tokenTransferService.getOperationsForTransaction(transaction, [log]); - - expect(operations.length).toStrictEqual(1); - - for (const operation of operations) { - expect(operation.action).toStrictEqual(TransactionOperationAction.writeLog); - expect(operation.type).toStrictEqual(TransactionOperationType.log); - expect(operation.message).toStrictEqual("@too much gas provided: gas needed = 2097255, gas remained = 117902745"); - } - }); - - - it('should return operations for a signal error event', async () => { - const signalErrorEvent = new TransactionLogEvent(); - signalErrorEvent.address = 'erd1qqqqqqqqqqqqqpgqg8a36rqxu4ch5v2522jv5avlun94sdv80n4sygxs94'; - signalErrorEvent.identifier = 'signalError'; - signalErrorEvent.topics = [ - "umboqRYjZyO/H5SZZIi2/FfcX27AUSubdLU+9l+VCMs=", - "ZXJyb3Igc2lnbmFsbGVkIGJ5IHNtYXJ0Y29udHJhY3Q=", - ], - signalErrorEvent.data = "QDY1Nzg2NTYzNzU3NDY5NmY2ZTIwNjY2MTY5NmM2NTY0"; - const log = new TransactionLog(); - log.events = [signalErrorEvent]; - - const operations = await tokenTransferService.getOperationsForTransaction(transaction, [log]); - expect(operations.length).toStrictEqual(1); - - for (const operation of operations) { - expect(operation.action).toStrictEqual(TransactionOperationAction.signalError); - expect(operation.type).toStrictEqual(TransactionOperationType.error); - expect(operation.message).toStrictEqual("error signalled by smartcontract"); - } - }); - - - it('should return operations for a egld transfer from smart contract result', async () => { - const scr = new SmartContractResult(); - scr.value = "6761736710959745"; - scr.nonce = 0; - scr.sender = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqghllllsku0nzf"; - scr.receiver = "erd1pln7dkvselu5hmx3qs9elzfaln96k30x0j6ypnh8gsnyvklanxsqmujqq7"; - transaction.results = [scr]; - - const operations = await tokenTransferService.getOperationsForTransaction(transaction, []); - expect(operations.length).toStrictEqual(1); - - for (const operation of operations) { - expect(operation.action).toStrictEqual(TransactionOperationAction.transfer); - expect(operation.type).toStrictEqual(TransactionOperationType.egld); - } - }); - - describe('Get Token Transfer Properties', () => { - it('should return token transfer properties', async () => { - const properties = await tokenTransferService.getTokenTransferProperties(tokenIdentifier); - if (!properties) { - throw new Error('Properties are not defined'); - } - - expect(properties).toHaveProperty('type'); - expect(properties).toHaveProperty('ticker'); - expect(properties).toHaveProperty('name'); - expect(properties).toHaveProperty('svgUrl'); - }); - - it('token transfer should have "TokenTransferProperties"', async () => { - const properties = await tokenTransferService.getTokenTransferProperties(tokenIdentifier); - if (!properties) { - throw new Error('Properties not defined'); - } - - expect(properties.type).toBeDefined; - expect(properties.name).toBeDefined; - expect(properties.token).toBeDefined; - expect(properties.decimals).toBeDefined; - }); - }); - - describe('Get Token Transfer Properties Raw', () => { - it('should return token transfer properties raw based on identifier', async () => { - const properties = await tokenTransferService.getTokenTransferPropertiesRaw(tokenDetails.identifier); - if (!properties) { - throw new Error('Properties not defined'); - } - - expect(properties.name).toBe(tokenDetails.name); - expect(properties.type).toBe(tokenDetails.type); - expect(properties.token).toBe(tokenDetails.identifier); - expect(properties.decimals).toBe(tokenDetails.decimals); - }); - }); - }); -}); - diff --git a/src/test/integration/services/transaction.get.e2e-spec.ts b/src/test/integration/services/transaction.get.e2e-spec.ts deleted file mode 100644 index 499e715b7..000000000 --- a/src/test/integration/services/transaction.get.e2e-spec.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { PublicAppModule } from "src/public.app.module"; -import { Test } from "@nestjs/testing"; -import { TransactionGetService } from "src/endpoints/transactions/transaction.get.service"; -import { IndexerService } from "src/common/indexer/indexer.service"; -import { HttpException, HttpStatus } from "@nestjs/common"; - -describe('Transaction Get Service', () => { - let transactionGetService: TransactionGetService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - transactionGetService = moduleRef.get(TransactionGetService); - }); - - beforeEach(() => { - jest.restoreAllMocks(); - }); - - describe("Get Transactions", () => { - it("should return logs transactions from elastic", async () => { - const hashes: string[] = [ - "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d", - "52408e723d6324f27ad1feae0a67610c8f3409e9a7c08cbc0832e9b1b242feae", - "a406faee819911b772aad2d428acea3f6f933e403e4347db281271ccb83d7655", - ]; - - const results = await transactionGetService.getTransactionLogsFromElastic(hashes); - - for (const result of results) { - expect(result).toHaveProperty("id"); - } - }); - - it("should return transaction sc results details from elastic", async () => { - const txHash: string = "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"; - const results = await transactionGetService.getTransactionScResultsFromElastic(txHash); - - for (const result of results) { - expect(result.hasOwnProperty("hash")).toBeTruthy(); - expect(result.hasOwnProperty("timestamp")).toBeTruthy(); - expect(result.hasOwnProperty("nonce")).toBeTruthy(); - expect(result.hasOwnProperty("gasLimit")).toBeTruthy(); - expect(result.hasOwnProperty("gasPrice")).toBeTruthy(); - expect(result.hasOwnProperty("value")).toBeTruthy(); - expect(result.hasOwnProperty("sender")).toBeTruthy(); - expect(result.hasOwnProperty("receiver")).toBeTruthy(); - expect(result.hasOwnProperty("data")).toBeTruthy(); - expect(result.hasOwnProperty("prevTxHash")).toBeTruthy(); - expect(result.hasOwnProperty("originalTxHash")).toBeTruthy(); - expect(result.hasOwnProperty("callType")).toBeTruthy(); - expect(result.hasOwnProperty("miniBlockHash")).toBeTruthy(); - expect(result.hasOwnProperty("logs")).toBeTruthy(); - expect(result.hasOwnProperty("returnMessage")).toBeTruthy(); - } - }); - - it("should return null because transaction is not found in elastic", async () => { - const hash: string = "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"; - jest - .spyOn(IndexerService.prototype, "getTransaction") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (txHash: string) => { - if (txHash == hash) { - return null; - } - - throw new HttpException({ status: HttpStatus.BAD_GATEWAY, message: "BAD GATEWAY" }, HttpStatus.BAD_GATEWAY); - })); - - const transaction = await transactionGetService.tryGetTransactionFromElastic(hash); - - expect(transaction).toBeNull(); - }); - - it("should throw error because indexer timed out", async () => { - const hash: string = "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"; - jest - .spyOn(IndexerService.prototype, "getTransaction") - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_: string) => { - throw new HttpException({ status: HttpStatus.BAD_GATEWAY, message: "BAD GATEWAY" }, HttpStatus.BAD_GATEWAY); - })); - - jest.spyOn(transactionGetService['logger'], 'error').mockImplementation(() => - "Unexpected error when getting transaction from elastic, hash '51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d'"); - - await expect(transactionGetService.tryGetTransactionFromElastic(hash)).rejects.toThrow(Error); - }); - - it("should return transaction from gateway with queryInElastic = true", async () => { - const txHash: string = "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"; - const results = await transactionGetService.tryGetTransactionFromGateway(txHash, true); - - if (!results) { - throw new Error("Properties are not defined"); - } - - expect(results.txHash).toStrictEqual("51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"); - expect(results.receiver).toStrictEqual("erd1qqqqqqqqqqqqqpgqy47ztjxnnqzwg6urd7qqn0ctx579h9kg0y8qn8gpxw"); - expect(results.sender).toStrictEqual("erd1ragf2tu8rkz3mme3m2yx6f33huy8hkwnknm82eg8s2zdpgy7mwas4d52hm"); - - - expect(results.logs).toBeDefined(); - expect(results.logs?.address).toStrictEqual("erd1qqqqqqqqqqqqqpgqy47ztjxnnqzwg6urd7qqn0ctx579h9kg0y8qn8gpxw"); - }); - - it("should return transaction from gateway with queryInElastic = false", async () => { - const txHash: string = "51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"; - const results = await transactionGetService.tryGetTransactionFromGateway(txHash, false); - - if (!results) { - throw new Error("Properties are not defined"); - } - - expect(results.txHash).toStrictEqual("51ffbf3d27e06fd509c510ef0ff1ea7329359dba89c05aeec333de52a405664d"); - expect(results.receiver).toStrictEqual("erd1qqqqqqqqqqqqqpgqy47ztjxnnqzwg6urd7qqn0ctx579h9kg0y8qn8gpxw"); - expect(results.sender).toStrictEqual("erd1ragf2tu8rkz3mme3m2yx6f33huy8hkwnknm82eg8s2zdpgy7mwas4d52hm"); - - - expect(results.logs).toBeDefined(); - expect(results.logs?.address).toStrictEqual("erd1qqqqqqqqqqqqqpgqy47ztjxnnqzwg6urd7qqn0ctx579h9kg0y8qn8gpxw"); - }); - }); -}); diff --git a/src/test/integration/services/transactions.e2e-spec.ts b/src/test/integration/services/transactions.e2e-spec.ts deleted file mode 100644 index 892d92123..000000000 --- a/src/test/integration/services/transactions.e2e-spec.ts +++ /dev/null @@ -1,291 +0,0 @@ -import { Test } from '@nestjs/testing'; -import { TransactionService } from 'src/endpoints/transactions/transaction.service'; -import { PublicAppModule } from 'src/public.app.module'; -import { IndexerService } from 'src/common/indexer/indexer.service'; -import { TransactionFilter } from 'src/endpoints/transactions/entities/transaction.filter'; -import { TransactionUtils } from 'src/endpoints/transactions/transaction.utils'; -import { QueryPagination } from 'src/common/entities/query.pagination'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/array.extensions'; -import { TransactionQueryOptions } from 'src/endpoints/transactions/entities/transactions.query.options'; -import { TransactionDetailed } from 'src/endpoints/transactions/entities/transaction.detailed'; -import { TransactionOptionalFieldOption } from 'src/endpoints/transactions/entities/transaction.optional.field.options'; - -describe.skip('Transaction Service', () => { - let transactionService: TransactionService; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - transactionService = moduleRef.get(TransactionService); - }); - beforeEach(() => { jest.restoreAllMocks(); }); - - describe('getTransactionCountForAddress', () => { - it('should return total transactions count for a specific address', async () => { - jest - .spyOn(IndexerService.prototype, 'getTransactionCountForAddress') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_address: string) => 41)); - - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const results = await transactionService.getTransactionCountForAddress(address); - - expect(results).toStrictEqual(41); - }); - }); - - describe('getTransactionCount', () => { - it('should return total transactions count with transactions filter applied', async () => { - jest - .spyOn(IndexerService.prototype, 'getTransactionCount') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_filter: TransactionFilter, _address?: string) => 41)); - - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const filter = new TransactionFilter(); - filter.sender = address; - - const results = await transactionService.getTransactionCount(filter); - expect(results).toStrictEqual(41); - }); - - it('should return total transactions count with transactions filter applied and address', async () => { - const mock = jest.spyOn(TransactionUtils, 'isTransactionCountQueryWithAddressOnly'); - mock.mockImplementation((_filter: TransactionFilter, _address?: string) => true); - - jest - .spyOn(TransactionService.prototype, 'getTransactionCountForAddress') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_address: string) => 32)); - - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const filter = new TransactionFilter(); - filter.token = "MEX-455c57"; - - const results = await transactionService.getTransactionCount(filter, address); - expect(results).toStrictEqual(32); - }); - - it('should return total transactions count with transactions filter applied and sender/receiver', async () => { - const mock = jest.spyOn(TransactionUtils, 'isTransactionCountQueryWithSenderAndReceiver'); - mock.mockImplementation((_filter: TransactionFilter) => true); - - jest - .spyOn(TransactionService.prototype, 'getTransactionCountForAddress') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_address: string) => 24)); - - const address: string = "erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"; - const filter = new TransactionFilter(); - filter.receivers = ["erd1qga7ze0l03chfgru0a32wxqf2226nzrxnyhzer9lmudqhjgy7ycqjjyknz"]; - - const results = await transactionService.getTransactionCount(filter, address); - expect(results).toStrictEqual(24); - }); - }); - - describe('getTransactions', () => { - it('should return an array of 5 transactions and verify if results have structure of TransactionDetailed', async () => { - const results = await transactionService.getTransactions( - new TransactionFilter(), - new QueryPagination({ size: 5 })); - - for (const result of results) { - expect(result).toHaveStructure(Object.keys(new TransactionDetailed())); - } - expect(results).toHaveLength(5); - }); - - it('should return an array of 2 transactions when hashes filter is applied', async () => { - const txFilters = new TransactionFilter(); - txFilters.hashes = [ - "29a2bed2543197e69c9bf16b30c4b0196f5e7a59584aba2e1a2127bf06cdfd2d", - "0cbaeb61cd2d901e7363b83e35750d0cbf2045ed853ef8f7af7cefdef622671e"]; - - const queryOptions = new TransactionQueryOptions(); - queryOptions.withScResults = true; - - const results = await transactionService.getTransactions( - txFilters, - new QueryPagination({ size: 2 })); - - for (const result of results) { - expect(result).toHaveStructure(Object.keys(new TransactionDetailed())); - } - }); - - it('should return 2 transactions with hashes filter applied and withScResults', async () => { - const txFilters = new TransactionFilter(); - txFilters.hashes = [ - "29a2bed2543197e69c9bf16b30c4b0196f5e7a59584aba2e1a2127bf06cdfd2d", - "0cbaeb61cd2d901e7363b83e35750d0cbf2045ed853ef8f7af7cefdef622671e"]; - - const queryOptions = new TransactionQueryOptions(); - queryOptions.withScResults = true; - - const results = await transactionService.getTransactions( - txFilters, - new QueryPagination({ size: 2 }), - queryOptions); - - const txResults = results.map((result) => result.txHash); - - expect(results).toHaveLength(2); - expect(txResults.includes("29a2bed2543197e69c9bf16b30c4b0196f5e7a59584aba2e1a2127bf06cdfd2d")).toBeTruthy(); - expect(txResults.includes("0cbaeb61cd2d901e7363b83e35750d0cbf2045ed853ef8f7af7cefdef622671e")).toBeTruthy(); - }); - - it('should return an array of transactions only with EGLD', async () => { - const filter = new TransactionFilter(); - filter.token = "EGLD"; - - const results = await transactionService.getTransactions(filter, new QueryPagination()); - - expect(results).toHaveLength(25); - - for (const result of results) { - expect(result.value).not.toEqual('0'); - } - }); - }); - - describe('getTransaction', () => { - it('should return transaction details', async () => { - const txHash: string = "4302d0af550e47a21e5d183f0918af7dbc015f1e7dea6d2ab2025ee675bf8517"; - const result = await transactionService.getTransaction(txHash); - - expect(result).toHaveStructure(Object.keys(new TransactionDetailed())); - }); - - it('should return operations attribute for a given transaction', async () => { - const txHash: string = "4302d0af550e47a21e5d183f0918af7dbc015f1e7dea6d2ab2025ee675bf8517"; - const result = await transactionService.getTransaction(txHash, [TransactionOptionalFieldOption.operations]); - - expect(result?.operations).toBeDefined(); - expect(result?.operations[0].id).toStrictEqual(txHash); - expect(result?.operations[0].action).toStrictEqual("transfer"); - }); - - it(`should return "action" key for ESDTNFTBurn transaction`, async () => { - const txHash: string = "1a9176f5e3be9b2bff237e9fc6da34589d1cd9a8f3499354df26c5efd7a8a5a8"; - const result = await transactionService.getTransaction(txHash); - - - if (result?.action?.arguments) { - expect(result.action.name).toStrictEqual('burn'); - expect(result.action.arguments.token.value).toStrictEqual(1); - } - }); - - it(`should return "action" key for ESDTNFTTransfer transaction`, async () => { - const txHash: string = "01e30ddf688f72aace6eea1df650945d89ccb7057c77a8298ff0cc2a1aec84a7"; - const result = await transactionService.getTransaction(txHash); - - expect(result?.action?.name).toStrictEqual('transfer'); - }); - - it(`should return "action" key for Freeze transaction`, async () => { - const txHash: string = "f6f4db3260248d2ace15d5dd4cb22c566a33900efbad68e6b9a97e77cf6eab88"; - const result = await transactionService.getTransaction(txHash); - - expect(result?.action?.name).toStrictEqual('freeze'); - }); - - it('should return logs attribute for a given transaction', async () => { - const txHash: string = "4302d0af550e47a21e5d183f0918af7dbc015f1e7dea6d2ab2025ee675bf8517"; - const results = await transactionService.getTransaction(txHash, [TransactionOptionalFieldOption.logs]); - - if (!results) { - throw new Error("Properties are not defined"); - } - - expect(results.logs).toEqual(expect.objectContaining({ - id: '4302d0af550e47a21e5d183f0918af7dbc015f1e7dea6d2ab2025ee675bf8517', - address: 'erd1qqqqqqqqqqqqqpgqmuk0q2saj0mgutxm4teywre6dl8wqf58xamqdrukln', - events: expect.arrayContaining([ - expect.objectContaining({ - identifier: 'ESDTTransfer', - address: 'erd10pccteep4cvw3vcjgrrfdn774qm8znvvxy7dpm75z8l0hrsauulqx082y9', - }), - ]), - })); - }); - }); - - it(`should return a list of transfers between two accounts (first address is always sender and seconds adress is always receiver)`, async () => { - const sender = 'erd18kmncel8a32yd94ktzlqag9etdrpdnyph8wus2nqyd4lp865gncq40znww'; - const receiver = 'erd1sdslvlxvfnnflzj42l8czrcngq3xjjzkjp3rgul4ttk6hntr4qdsv6sets'; - const transactionFilter = new TransactionFilter(); - transactionFilter.sender = sender; - transactionFilter.receivers = [receiver]; - - const transfers = await transactionService.getTransactions(transactionFilter, { from: 0, size: 25 }, new TransactionQueryOptions()); - expect(transfers.length).toBeGreaterThan(0); - - for (const transfer of transfers) { - expect(transfer.sender).toBe(sender); - expect([sender, receiver].includes(transfer.receiver)).toBe(true); //it can be an ESDNFTTransfer which is a self transaction - } - }); - - it('should return an array of transactions and if withBlockInfo is set to true, block extra fields should be defined', async () => { - const transactions = await transactionService.getTransactions( - new TransactionFilter(), - new QueryPagination(), - new TransactionQueryOptions({ withBlockInfo: true })); - - const extraFields = transactions.every(transaction => - 'senderBlockHash' in transaction && - 'senderBlockNonce' in transaction && - 'receiverBlockHash' in transaction && - 'receiverBlockNonce' in transaction - ); - - expect(extraFields).toBeTruthy(); - }); - - it('should return an array of transactions and if withBlockInfo is set to false, block extra fields should not be defined', async () => { - const transactions = await transactionService.getTransactions( - new TransactionFilter(), - new QueryPagination(), - new TransactionQueryOptions({ withBlockInfo: false })); - - expect(transactions).not.toEqual(expect.objectContaining({ - senderBlockHash: expect.anything(), - senderBlockNonce: expect.anything(), - receiverBlockHash: expect.anything(), - receiverBlockNonce: expect.anything(), - })); - }); - - it('should return an array of relayed transactions and isRelayed key should be true', async () => { - const transactionFilter = new TransactionFilter(); - transactionFilter.isRelayed = true; - - const transactions = await transactionService.getTransactions( - transactionFilter, - new QueryPagination(), - ); - - for (const transaction of transactions) { - expect(transaction.isRelayed).toBeDefined(); - } - }); - - it('should not return isRelayed key if isRelayed filter is not defined', async () => { - const transactionFilter = new TransactionFilter(); - transactionFilter.isRelayed = false; - - const transactions = await transactionService.getTransactions( - transactionFilter, - new QueryPagination(), - ); - - for (const transaction of transactions) { - expect(transaction.isRelayed).not.toBeDefined(); - } - }); -}); diff --git a/src/test/integration/services/waiting.list.e2e-spec.ts b/src/test/integration/services/waiting.list.e2e-spec.ts deleted file mode 100644 index 8e214a452..000000000 --- a/src/test/integration/services/waiting.list.e2e-spec.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Test } from "@nestjs/testing"; -import '@multiversx/sdk-nestjs-common/lib/utils/extensions/jest.extensions'; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { WaitingListService } from "src/endpoints/waiting-list/waiting.list.service"; -import { WaitingList } from "src/endpoints/waiting-list/entities/waiting.list"; -import { QueryPagination } from "src/common/entities/query.pagination"; -import { PublicAppModule } from "src/public.app.module"; - -describe('Waiting List Service', () => { - let waitingListService: WaitingListService; - const waitingList = [{ - address: 'erd1wcat0qk32u5xquuds9etauayqs29tqrzs5x3plc6djy54rmatdpsejg6qx', - value: '270000000000000000001', - nonce: 8859612, - rank: 60, - }, - ]; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - waitingListService = moduleRef.get(WaitingListService); - }); - - beforeEach(() => { - jest.restoreAllMocks(); - }); - - describe("getWaitingList", () => { - it("should return waiting list", async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, promise: any) => promise())); - - const results = await waitingListService.getWaitingList(new QueryPagination()); - - for (const result of results) { - expect(result).toHaveProperties(['address', 'value', 'nonce', 'rank']); - expect(result).toHaveStructure(Object.keys(new WaitingList())); - } - }); - }); - - describe('getWaitingListForAddress', () => { - it('should return a list of waitings for a specified address ', async () => { - jest.spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(async () => waitingList); - - const results = await waitingListService.getWaitingListForAddress("erd1wcat0qk32u5xquuds9etauayqs29tqrzs5x3plc6djy54rmatdpsejg6qx"); - - expect(results).toHaveLength(1); - expect(results).toEqual(expect.arrayContaining([ - expect.objectContaining({ - address: "erd1wcat0qk32u5xquuds9etauayqs29tqrzs5x3plc6djy54rmatdpsejg6qx", - value: '270000000000000000001', - nonce: 8859612, - rank: 60, - }), - ])); - }); - }); - - describe('getWaitingListCount', () => { - it('should return total count of waiting list ', async () => { - jest - .spyOn(CacheService.prototype, 'getOrSet') - // eslint-disable-next-line require-await - .mockImplementation(jest.fn(async (_key: string, _promise: any) => waitingList)); - - const result = await waitingListService.getWaitingListCount(); - expect(result).toStrictEqual(1); - }); - }); -}); diff --git a/src/test/integration/services/warm.e2e-warm-spec.ts b/src/test/integration/services/warm.e2e-warm-spec.ts deleted file mode 100644 index ca5dc8f92..000000000 --- a/src/test/integration/services/warm.e2e-warm-spec.ts +++ /dev/null @@ -1,34 +0,0 @@ - -import { Constants } from "@multiversx/sdk-nestjs-common"; -import { CacheService } from "@multiversx/sdk-nestjs-cache"; -import { Test } from "@nestjs/testing"; -import { ApiConfigModule } from "src/common/api-config/api.config.module"; -import { DynamicModuleUtils } from "src/utils/dynamic.module.utils"; -import Initializer from "./e2e-init"; - -describe('Warm for tests', () => { - let cachingService: CacheService; - - beforeAll(async () => { - await Initializer.initialize(); - - const module = await Test.createTestingModule({ - imports: [ - ApiConfigModule, - DynamicModuleUtils.getCacheModule(), - ], - }).compile(); - - cachingService = module.get(CacheService); - - }, Constants.oneHour() * 1000); - - describe('Warm', () => { - it('test for warm', async () => { - const isInitialized = - await cachingService.getRemote('isInitialized'); - - expect(isInitialized).toBe(true); - }); - }); -}); From d84779e07b6436513804619ffb224060ab316717 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:13:46 +0200 Subject: [PATCH 08/30] remove api checker --- src/test/integration/api/accounts.api-spec.ts | 52 ------------------ src/test/integration/api/blocks.api-spec.ts | 54 ------------------- .../integration/api/collections.api-spec.ts | 41 -------------- src/test/integration/api/nfts.api-spec.ts | 46 ---------------- src/test/integration/api/nodes.api-spec.ts | 41 -------------- .../integration/api/providers.api-spec.ts | 41 -------------- src/test/integration/api/results.api-spec.ts | 36 ------------- src/test/integration/api/rounds.api-spec.ts | 36 ------------- src/test/integration/api/shards.api-spec.ts | 36 ------------- src/test/integration/api/tags.api-spec.ts | 37 ------------- src/test/integration/api/tokens.api-spec.ts | 46 ---------------- .../integration/api/transactions.api-spec.ts | 36 ------------- 12 files changed, 502 deletions(-) delete mode 100644 src/test/integration/api/accounts.api-spec.ts delete mode 100644 src/test/integration/api/blocks.api-spec.ts delete mode 100644 src/test/integration/api/collections.api-spec.ts delete mode 100644 src/test/integration/api/nfts.api-spec.ts delete mode 100644 src/test/integration/api/nodes.api-spec.ts delete mode 100644 src/test/integration/api/providers.api-spec.ts delete mode 100644 src/test/integration/api/results.api-spec.ts delete mode 100644 src/test/integration/api/rounds.api-spec.ts delete mode 100644 src/test/integration/api/shards.api-spec.ts delete mode 100644 src/test/integration/api/tags.api-spec.ts delete mode 100644 src/test/integration/api/tokens.api-spec.ts delete mode 100644 src/test/integration/api/transactions.api-spec.ts diff --git a/src/test/integration/api/accounts.api-spec.ts b/src/test/integration/api/accounts.api-spec.ts deleted file mode 100644 index aadca2d6b..000000000 --- a/src/test/integration/api/accounts.api-spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - const skipedFields = ['balance', 'nonce', 'timestamp']; - - afterAll(async () => { - await app.close(); - }); - - it("should check accounts pagination", async () => { - const checker = new ApiChecker('accounts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkPagination(); - }); - - it('should check accounts status response code', async () => { - const checker = new ApiChecker('accounts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkStatus(); - }); - - it('should check accounts count', async () => { - const checker = new ApiChecker('accounts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkAlternativeCount(); - }); - - it('should check accounts details', async () => { - const checker = new ApiChecker('accounts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkDetails(); - }); -}); diff --git a/src/test/integration/api/blocks.api-spec.ts b/src/test/integration/api/blocks.api-spec.ts deleted file mode 100644 index adf4605be..000000000 --- a/src/test/integration/api/blocks.api-spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - const skipedFields = ['scheduledRootHash']; - const randomShard = Math.floor(Math.random() * 3); - - afterAll(async () => { - await app.close(); - }); - - it("should check blocks pagination", async () => { - const checker = new ApiChecker('blocks', app.getHttpServer()); - - checker.defaultParams = { epoch: 500, shard: randomShard }; - checker.skipFields = skipedFields; - - await checker.checkPagination(); - }); - - it('should check blocks status response code', async () => { - const checker = new ApiChecker('blocks', app.getHttpServer()); - - checker.defaultParams = { epoch: 500, shard: randomShard }; - checker.skipFields = skipedFields; - await checker.checkStatus(); - }); - - it('should check blocks count', async () => { - const checker = new ApiChecker('blocks', app.getHttpServer()); - - checker.defaultParams = { epoch: 500, shard: randomShard }; - checker.skipFields = skipedFields; - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/collections.api-spec.ts b/src/test/integration/api/collections.api-spec.ts deleted file mode 100644 index a88c462e1..000000000 --- a/src/test/integration/api/collections.api-spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it("should check collections pagination", async () => { - const checker = new ApiChecker('collections', app.getHttpServer()); - await checker.checkPagination(); - }); - - it('should check collections status response code', async () => { - const checker = new ApiChecker('collections', app.getHttpServer()); - await checker.checkStatus(); - }); - - it('should check collections count', async () => { - const checker = new ApiChecker('collections', app.getHttpServer()); - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/nfts.api-spec.ts b/src/test/integration/api/nfts.api-spec.ts deleted file mode 100644 index f835e9ed1..000000000 --- a/src/test/integration/api/nfts.api-spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - const skipedFields = ['message', 'statusCode']; - - afterAll(async () => { - await app.close(); - }); - - it("should check nfts pagination", async () => { - const checker = new ApiChecker('nfts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkPagination(); - }); - - it('should check nfts status response code', async () => { - const checker = new ApiChecker('nfts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkStatus(); - }); - - it('should check nfts count', async () => { - const checker = new ApiChecker('nfts', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/nodes.api-spec.ts b/src/test/integration/api/nodes.api-spec.ts deleted file mode 100644 index 5c1866f81..000000000 --- a/src/test/integration/api/nodes.api-spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it("should check nodes pagination", async () => { - const checker = new ApiChecker('nodes', app.getHttpServer()); - await checker.checkPagination(); - }); - - it('should check nodes status response code', async () => { - const checker = new ApiChecker('nodes', app.getHttpServer()); - await checker.checkStatus(); - }); - - it('should check nodes count', async () => { - const checker = new ApiChecker('nodes', app.getHttpServer()); - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/providers.api-spec.ts b/src/test/integration/api/providers.api-spec.ts deleted file mode 100644 index fee03fa8b..000000000 --- a/src/test/integration/api/providers.api-spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it('should check providers status response code', async () => { - const checker = new ApiChecker('providers', app.getHttpServer()); - await checker.checkStatus(); - }); - - it('should check providers count', async () => { - const checker = new ApiChecker('providers', app.getHttpServer()); - await checker.checkAlternativeCount(); - }); - - it('should check providers details', async () => { - const checker = new ApiChecker('providers', app.getHttpServer()); - await checker.checkDetails('provider'); - }); -}); diff --git a/src/test/integration/api/results.api-spec.ts b/src/test/integration/api/results.api-spec.ts deleted file mode 100644 index 706dcea49..000000000 --- a/src/test/integration/api/results.api-spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it("should check results pagination", async () => { - const checker = new ApiChecker('results', app.getHttpServer()); - await checker.checkPagination(); - }); - - it('should check results status response code', async () => { - const checker = new ApiChecker('results', app.getHttpServer()); - await checker.checkStatus(); - }); -}); diff --git a/src/test/integration/api/rounds.api-spec.ts b/src/test/integration/api/rounds.api-spec.ts deleted file mode 100644 index 4514fab7c..000000000 --- a/src/test/integration/api/rounds.api-spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it('should check rounds status response code', async () => { - const checker = new ApiChecker('rounds', app.getHttpServer()); - await checker.checkStatus(); - }); - - it('should check rounds count', async () => { - const checker = new ApiChecker('rounds', app.getHttpServer()); - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/shards.api-spec.ts b/src/test/integration/api/shards.api-spec.ts deleted file mode 100644 index 2d547171d..000000000 --- a/src/test/integration/api/shards.api-spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it("should check shards pagination", async () => { - const checker = new ApiChecker('shards', app.getHttpServer()); - await checker.checkPagination(); - }); - - it('should check shards status response code', async () => { - const checker = new ApiChecker('shards', app.getHttpServer()); - await checker.checkStatus(); - }); -}); diff --git a/src/test/integration/api/tags.api-spec.ts b/src/test/integration/api/tags.api-spec.ts deleted file mode 100644 index 8e1ce9330..000000000 --- a/src/test/integration/api/tags.api-spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - // @ts-ignore - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it("should check tags pagination", async () => { - const checker = new ApiChecker('tags', app.getHttpServer()); - await checker.checkPagination(); - }); - - it('should check tags status response code', async () => { - const checker = new ApiChecker('tags', app.getHttpServer()); - await checker.checkStatus(); - }); -}); diff --git a/src/test/integration/api/tokens.api-spec.ts b/src/test/integration/api/tokens.api-spec.ts deleted file mode 100644 index 5b28c33cd..000000000 --- a/src/test/integration/api/tokens.api-spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - const skipedFields = ['error', 'message', 'statusCode']; - - afterAll(async () => { - await app.close(); - }); - - it("should check tokens pagination", async () => { - const checker = new ApiChecker('tokens', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkPagination(); - }); - - it('should check tokens status response code', async () => { - const checker = new ApiChecker('tokens', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkStatus(); - }); - - it('should check tokens count', async () => { - const checker = new ApiChecker('tokens', app.getHttpServer()); - checker.skipFields = skipedFields; - await checker.checkAlternativeCount(); - }); -}); diff --git a/src/test/integration/api/transactions.api-spec.ts b/src/test/integration/api/transactions.api-spec.ts deleted file mode 100644 index a985a9139..000000000 --- a/src/test/integration/api/transactions.api-spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CleanupInterceptor, FieldsInterceptor } from '@multiversx/sdk-nestjs-http'; -import { INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { PublicAppModule } from 'src/public.app.module'; -import { ApiChecker } from 'src/utils/api.checker'; - -describe.skip("API Testing", () => { - let app: INestApplication; - - beforeAll(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [PublicAppModule], - }).compile(); - - app = moduleRef.createNestApplication(); - app.useGlobalInterceptors( - new FieldsInterceptor(), - new CleanupInterceptor(), - ); - await app.init(); - }); - - afterAll(async () => { - await app.close(); - }); - - it('should check transactions status response code', async () => { - const checker = new ApiChecker('transactions', app.getHttpServer()); - await checker.checkStatus(); - }); - - it('should check transactions count', async () => { - const checker = new ApiChecker('transactions', app.getHttpServer()); - await checker.checkAlternativeCount(); - }); -}); From 196e433f4ff05413c009efc8cad733fea7f1c244 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 12:25:39 +0200 Subject: [PATCH 09/30] include Pipes Verification --- .../controllers/tags.controller.e2e-spec.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/test/integration/controllers/tags.controller.e2e-spec.ts b/src/test/integration/controllers/tags.controller.e2e-spec.ts index 0e60e9537..ca78ba2a3 100644 --- a/src/test/integration/controllers/tags.controller.e2e-spec.ts +++ b/src/test/integration/controllers/tags.controller.e2e-spec.ts @@ -70,6 +70,16 @@ describe('TagController', () => { .expect(404); }); + it('/GET tags with invalid integer parameters', async () => { + const params = new URLSearchParams({ from: 'invalid', size: '1' }).toString(); + await request(app.getHttpServer()) + .get(`${path}?${params}`) + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'from' (optional number is expected)"); + }); + }); + afterAll(async () => { await app.close(); }); From b909f2634f915b49b278c6d7bc4690f9c9db90eb Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 14:50:53 +0200 Subject: [PATCH 10/30] add accounts controller e2e tests --- .../accounts.controller.e2e-spec.ts | 136 ++++++++++++++++++ .../services.mock/account.services.mock.ts | 82 +++++++++++ 2 files changed, 218 insertions(+) create mode 100644 src/test/integration/controllers/accounts.controller.e2e-spec.ts create mode 100644 src/test/integration/controllers/services.mock/account.services.mock.ts diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts new file mode 100644 index 000000000..43a924936 --- /dev/null +++ b/src/test/integration/controllers/accounts.controller.e2e-spec.ts @@ -0,0 +1,136 @@ +import { INestApplication } from "@nestjs/common"; +import { TestingModule, Test } from "@nestjs/testing"; +import { ApiConfigService } from "src/common/api-config/api.config.service"; +import { AccountService } from "src/endpoints/accounts/account.service"; +import { CollectionService } from "src/endpoints/collections/collection.service"; +import { DelegationLegacyService } from "src/endpoints/delegation.legacy/delegation.legacy.service"; +import { DelegationService } from "src/endpoints/delegation/delegation.service"; +import { NftService } from "src/endpoints/nfts/nft.service"; +import { SmartContractResultService } from "src/endpoints/sc-results/scresult.service"; +import { StakeService } from "src/endpoints/stake/stake.service"; +import { TokenService } from "src/endpoints/tokens/token.service"; +import { TransactionService } from "src/endpoints/transactions/transaction.service"; +import { TransferService } from "src/endpoints/transfers/transfer.service"; +import { WaitingListService } from "src/endpoints/waiting-list/waiting.list.service"; +import { mockAccountService, mockTokenService, mockNftService, mockDelegationLegacyService, mockWaitingListService, mockStakeService, mockTransactionService, mockSmartContractResultService, mockCollectionService, mockTransferService, mockApiConfigService, mockDelegationService } from "./services.mock/account.services.mock"; +import { AccountController } from "src/endpoints/accounts/account.controller"; +import { AccountModule } from "src/endpoints/accounts/account.module"; +import { TokenModule } from "src/endpoints/tokens/token.module"; +import { NftModule } from "src/endpoints/nfts/nft.module"; +import { DelegationLegacyModule } from "src/endpoints/delegation.legacy/delegation.legacy.module"; +import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.module"; +import { StakeModule } from "src/endpoints/stake/stake.module"; +import { TransactionModule } from "src/endpoints/transactions/transaction.module"; +import { SmartContractResultModule } from "src/endpoints/sc-results/scresult.module"; +import { CollectionModule } from "src/endpoints/collections/collection.module"; +import { TransferModule } from "src/endpoints/transfers/transfer.module"; +import { ApiConfigModule } from "src/common/api-config/api.config.module"; +import { DelegationModule } from "src/endpoints/delegation/delegation.module"; +import request = require('supertest'); + +describe('AccountController (e2e)', () => { + let app: INestApplication; + const path = "/accounts"; + + const accountServiceMocks = mockAccountService(); + + beforeEach(async () => { + jest.resetAllMocks(); + const moduleFixture: TestingModule = await Test.createTestingModule({ + controllers: [AccountController], + imports: [ + AccountModule, + TokenModule, + NftModule, + DelegationLegacyModule, + WaitingListModule, + StakeModule, + TransactionModule, + SmartContractResultModule, + CollectionModule, + TransferModule, + ApiConfigModule, + DelegationModule, + ], + }) + .overrideProvider(AccountService).useValue(accountServiceMocks) + .overrideProvider(TokenService).useValue(mockTokenService()) + .overrideProvider(NftService).useValue(mockNftService()) + .overrideProvider(DelegationLegacyService).useValue(mockDelegationLegacyService()) + .overrideProvider(WaitingListService).useValue(mockWaitingListService()) + .overrideProvider(StakeService).useValue(mockStakeService()) + .overrideProvider(TransactionService).useValue(mockTransactionService()) + .overrideProvider(SmartContractResultService).useValue(mockSmartContractResultService()) + .overrideProvider(CollectionService).useValue(mockCollectionService()) + .overrideProvider(TransferService).useValue(mockTransferService()) + .overrideProvider(ApiConfigService).useValue(mockApiConfigService()) + .overrideProvider(DelegationService).useValue(mockDelegationService()) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe("GET /accounts/count", () => { + it('should return total accounts count', async () => { + accountServiceMocks.getAccountsCount.mockReturnValue(100); + + await request(app.getHttpServer()) + .get(`${path}/count`) + .expect(200) + .expect(response => { + expect(+response.text).toStrictEqual(100); + }); + }); + + it('should return total smart contracts count', async () => { + const params = new URLSearchParams({ isSmartContract: "true" }).toString(); + accountServiceMocks.getAccountsCount.mockReturnValue(25); + + await request(app.getHttpServer()) + .get(`${path}/count?${params}`) + .expect(200) + .expect(response => { + expect(+response.text).toStrictEqual(25); + }); + }); + + it('should return accounts details for a given owner address', async () => { + const ownerAddress: string = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqplllst77y4l"; + const params = new URLSearchParams({ ownerAddress: ownerAddress }).toString(); + accountServiceMocks.getAccountsCount.mockReturnValue(25); + + await request(app.getHttpServer()) + .get(`${path}/count?${params}`) + .expect(200) + .expect(response => { + expect(+response.text).toStrictEqual(25); + }); + }); + + it('should throw 400 Bad Request for a given invalid Bech32 owner address', async () => { + const ownerAddress: string = "invalidBech32Address"; + const params = new URLSearchParams({ ownerAddress: ownerAddress }).toString(); + accountServiceMocks.getAccountsCount.mockReturnValue(25); + + await request(app.getHttpServer()) + .get(`${path}/count?${params}`) + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'ownerAddress' (a bech32 address is expected)"); + }); + }); + + it('should throw 400 Bad Request for a given isSmartContract value', async () => { + const params = new URLSearchParams({ isSmartContract: "invalidBoolean" }).toString(); + accountServiceMocks.getAccountsCount.mockReturnValue(25); + + await request(app.getHttpServer()) + .get(`${path}/count?${params}`) + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'isSmartContract' (optional boolean string is expected)"); + }); + }); + }); +}); diff --git a/src/test/integration/controllers/services.mock/account.services.mock.ts b/src/test/integration/controllers/services.mock/account.services.mock.ts new file mode 100644 index 000000000..da4118d29 --- /dev/null +++ b/src/test/integration/controllers/services.mock/account.services.mock.ts @@ -0,0 +1,82 @@ +export const mockAccountService = () => ({ + getAccounts: jest.fn().mockResolvedValue([]), + getAccountsCount: jest.fn().mockResolvedValue(0), + getAccount: jest.fn().mockResolvedValue({}), + getDeferredAccount: jest.fn().mockResolvedValue([]), + getAccountVerification: jest.fn().mockResolvedValue(null), + getAccountContracts: jest.fn().mockResolvedValue([]), + getAccountContractsCount: jest.fn().mockResolvedValue(0), + getKeys: jest.fn().mockResolvedValue([]), + getWaitingListForAddress: jest.fn().mockResolvedValue([]), +}); + +export const mockTokenService = () => ({ + isToken: jest.fn().mockResolvedValue(false), + getTokensForAddress: jest.fn().mockResolvedValue([]), + getTokenCountForAddress: jest.fn().mockResolvedValue(0), + getTokenForAddress: jest.fn().mockResolvedValue({}), + getTokensWithRolesForAddress: jest.fn().mockResolvedValue([]), + getTokensWithRolesForAddressCount: jest.fn().mockResolvedValue(0), + getTokenWithRolesForAddress: jest.fn().mockResolvedValue(0), +}); + +export const mockNftService = () => ({ + getNftsForAddress: jest.fn().mockResolvedValue([]), + getNftCountForAddress: jest.fn().mockResolvedValue(0), + getNftForAddress: jest.fn().mockResolvedValue({}), + isNft: jest.fn().mockResolvedValue(true), +}); + +export const mockDelegationLegacyService = () => ({ + getDelegationForAddress: jest.fn().mockResolvedValue({}), +}); + +export const mockWaitingListService = () => ({ + getWaitingListForAddress: jest.fn().mockResolvedValue([]), +}); + +export const mockStakeService = () => ({ + getStakeForAddress: jest.fn().mockResolvedValue({}), +}); + +export const mockTransactionService = () => ({ + getTransactions: jest.fn().mockResolvedValue([]), + getTransactionCount: jest.fn().mockResolvedValue(0), +}); + +export const mockSmartContractResultService = () => ({ + getAccountScResults: jest.fn().mockResolvedValue([]), + getAccountScResultsCount: jest.fn().mockResolvedValue(0), + getScResult: jest.fn().mockResolvedValue({}), +}); + +export const mockCollectionService = () => ({ + getCollectionsForAddress: jest.fn().mockResolvedValue([]), + getCollectionCountForAddress: jest.fn().mockResolvedValue(0), + getCollectionForAddress: jest.fn().mockResolvedValue({}), + getCollectionsWithRolesForAddress: jest.fn().mockResolvedValue([]), + getCollectionCountForAddressWithRoles: jest.fn().mockResolvedValue(0), + isCollection: jest.fn().mockResolvedValue(true), +}); + +export const mockTransferService = () => ({ + getTransfers: jest.fn().mockResolvedValue([]), + getTransfersCount: jest.fn().mockResolvedValue(0), +}); + +export const mockApiConfigService = () => ({ + getIsIndexerV3FlagActive: jest.fn().mockReturnValue(false), + getAxiosTimeout: jest.fn().mockReturnValue(0), + getRateLimiterSecret: jest.fn().mockReturnValue(0), + getServerTimeout: jest.fn().mockReturnValue(0), + getUseKeepAliveAgentFlag: jest.fn().mockReturnValue(false), + getElasticUrl: jest.fn().mockReturnValue(''), + getRedisUrl: jest.fn().mockReturnValue(''), + getPoolLimit: jest.fn().mockReturnValue(''), + getProcessTtl: jest.fn().mockReturnValue(''), + getExternalMediaUrl: jest.fn().mockReturnValue(''), +}); + +export const mockDelegationService = () => ({ + getDelegationForAddress: jest.fn().mockResolvedValue([]), +}); From edec9553f3d60f7cc7bea027135ec9fdb4286b58 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 14:58:55 +0200 Subject: [PATCH 11/30] update path --- .../integration/controllers/accounts.controller.e2e-spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts index 43a924936..86d99233d 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.e2e-spec.ts @@ -12,7 +12,6 @@ import { TokenService } from "src/endpoints/tokens/token.service"; import { TransactionService } from "src/endpoints/transactions/transaction.service"; import { TransferService } from "src/endpoints/transfers/transfer.service"; import { WaitingListService } from "src/endpoints/waiting-list/waiting.list.service"; -import { mockAccountService, mockTokenService, mockNftService, mockDelegationLegacyService, mockWaitingListService, mockStakeService, mockTransactionService, mockSmartContractResultService, mockCollectionService, mockTransferService, mockApiConfigService, mockDelegationService } from "./services.mock/account.services.mock"; import { AccountController } from "src/endpoints/accounts/account.controller"; import { AccountModule } from "src/endpoints/accounts/account.module"; import { TokenModule } from "src/endpoints/tokens/token.module"; @@ -26,9 +25,10 @@ import { CollectionModule } from "src/endpoints/collections/collection.module"; import { TransferModule } from "src/endpoints/transfers/transfer.module"; import { ApiConfigModule } from "src/common/api-config/api.config.module"; import { DelegationModule } from "src/endpoints/delegation/delegation.module"; +import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; import request = require('supertest'); -describe('AccountController (e2e)', () => { +describe('AccountController', () => { let app: INestApplication; const path = "/accounts"; From fd39a3367156231daa46a2aebf18a954aecd8dfa Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:06:57 +0200 Subject: [PATCH 12/30] check dependencies --- .../accounts.controller.e2e-spec.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts index 86d99233d..a7a1d5707 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.e2e-spec.ts @@ -25,13 +25,25 @@ import { CollectionModule } from "src/endpoints/collections/collection.module"; import { TransferModule } from "src/endpoints/transfers/transfer.module"; import { ApiConfigModule } from "src/common/api-config/api.config.module"; import { DelegationModule } from "src/endpoints/delegation/delegation.module"; -import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; +import { mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; import request = require('supertest'); describe('AccountController', () => { let app: INestApplication; const path = "/accounts"; + const mockAccountService = () => ({ + getAccounts: jest.fn().mockResolvedValue([]), + getAccountsCount: jest.fn().mockResolvedValue(0), + getAccount: jest.fn().mockResolvedValue({}), + getDeferredAccount: jest.fn().mockResolvedValue([]), + getAccountVerification: jest.fn().mockResolvedValue(null), + getAccountContracts: jest.fn().mockResolvedValue([]), + getAccountContractsCount: jest.fn().mockResolvedValue(0), + getKeys: jest.fn().mockResolvedValue([]), + getWaitingListForAddress: jest.fn().mockResolvedValue([]), + }); + const accountServiceMocks = mockAccountService(); beforeEach(async () => { @@ -133,4 +145,8 @@ describe('AccountController', () => { }); }); }); + + }); + + From 4f2f29435d90af0028627531d4f898243041389f Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:08:31 +0200 Subject: [PATCH 13/30] revert --- .../controllers/accounts.controller.e2e-spec.ts | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts index a7a1d5707..a998b5d4d 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.e2e-spec.ts @@ -25,25 +25,13 @@ import { CollectionModule } from "src/endpoints/collections/collection.module"; import { TransferModule } from "src/endpoints/transfers/transfer.module"; import { ApiConfigModule } from "src/common/api-config/api.config.module"; import { DelegationModule } from "src/endpoints/delegation/delegation.module"; -import { mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; +import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; import request = require('supertest'); describe('AccountController', () => { let app: INestApplication; const path = "/accounts"; - const mockAccountService = () => ({ - getAccounts: jest.fn().mockResolvedValue([]), - getAccountsCount: jest.fn().mockResolvedValue(0), - getAccount: jest.fn().mockResolvedValue({}), - getDeferredAccount: jest.fn().mockResolvedValue([]), - getAccountVerification: jest.fn().mockResolvedValue(null), - getAccountContracts: jest.fn().mockResolvedValue([]), - getAccountContractsCount: jest.fn().mockResolvedValue(0), - getKeys: jest.fn().mockResolvedValue([]), - getWaitingListForAddress: jest.fn().mockResolvedValue([]), - }); - const accountServiceMocks = mockAccountService(); beforeEach(async () => { @@ -145,8 +133,6 @@ describe('AccountController', () => { }); }); }); - - }); From 5cf23631a2d946a9cb2799bc47528b922267d378 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:15:11 +0200 Subject: [PATCH 14/30] add configModule --- .../accounts.controller.e2e-spec.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts index a998b5d4d..95957dcdc 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.e2e-spec.ts @@ -13,20 +13,21 @@ import { TransactionService } from "src/endpoints/transactions/transaction.servi import { TransferService } from "src/endpoints/transfers/transfer.service"; import { WaitingListService } from "src/endpoints/waiting-list/waiting.list.service"; import { AccountController } from "src/endpoints/accounts/account.controller"; +import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; +import { ApiConfigModule } from "src/common/api-config/api.config.module"; import { AccountModule } from "src/endpoints/accounts/account.module"; -import { TokenModule } from "src/endpoints/tokens/token.module"; -import { NftModule } from "src/endpoints/nfts/nft.module"; +import { CollectionModule } from "src/endpoints/collections/collection.module"; import { DelegationLegacyModule } from "src/endpoints/delegation.legacy/delegation.legacy.module"; -import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.module"; +import { DelegationModule } from "src/endpoints/delegation/delegation.module"; +import { NftModule } from "src/endpoints/nfts/nft.module"; +import { SmartContractResultModule } from "src/endpoints/sc-results/scresult.module"; import { StakeModule } from "src/endpoints/stake/stake.module"; +import { TokenModule } from "src/endpoints/tokens/token.module"; import { TransactionModule } from "src/endpoints/transactions/transaction.module"; -import { SmartContractResultModule } from "src/endpoints/sc-results/scresult.module"; -import { CollectionModule } from "src/endpoints/collections/collection.module"; import { TransferModule } from "src/endpoints/transfers/transfer.module"; -import { ApiConfigModule } from "src/common/api-config/api.config.module"; -import { DelegationModule } from "src/endpoints/delegation/delegation.module"; -import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; +import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.module"; import request = require('supertest'); +import { ConfigModule } from "@nestjs/config"; describe('AccountController', () => { let app: INestApplication; @@ -51,6 +52,7 @@ describe('AccountController', () => { TransferModule, ApiConfigModule, DelegationModule, + ConfigModule.forRoot({}), ], }) .overrideProvider(AccountService).useValue(accountServiceMocks) From b5651b0dd2eeff29c17d4cb93c1b7d4ea6f390f4 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:19:57 +0200 Subject: [PATCH 15/30] logs --- .github/workflows/integration.tests.yml | 7 +++++++ config/configuration.ts | 17 +++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml index 0b7d1382d..94c74ede0 100644 --- a/.github/workflows/integration.tests.yml +++ b/.github/workflows/integration.tests.yml @@ -27,6 +27,13 @@ jobs: cache: 'npm' - run: npm ci - run: npm run init + + - name: List working directory contents + run: ls -la + + - name: List config directory contents + run: ls -la config/ + - run: npm run test:e2e - name: Collect code coverage run: npm run test:e2e:cov diff --git a/config/configuration.ts b/config/configuration.ts index 73ba5178a..4e920e805 100644 --- a/config/configuration.ts +++ b/config/configuration.ts @@ -1,11 +1,20 @@ import { readFileSync } from 'fs'; -import * as yaml from 'js-yaml'; import { join } from 'path'; +import * as yaml from 'js-yaml'; const YAML_CONFIG_FILENAME = 'config.yaml'; export default () => { - return yaml.load( - readFileSync(join(__dirname, YAML_CONFIG_FILENAME), 'utf8'), - ) as Record; + const filePath = join(__dirname, YAML_CONFIG_FILENAME); + console.log('Trying to load config file from:', filePath); + console.log('__dirname:', __dirname); + console.log('process.cwd():', process.cwd()); + + try { + const config = yaml.load(readFileSync(filePath, 'utf8')); + return config as Record; + } catch (error) { + console.error('Error loading the config file:', error); + throw error; + } }; From 51d5e79910324672358b5f02aa4a35b83bd7bb08 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:24:38 +0200 Subject: [PATCH 16/30] fix_2 --- .github/workflows/integration.tests.yml | 7 ------- config/configuration.ts | 17 ++++------------- ....e2e-spec.ts => accounts.controller.spec.ts} | 6 +++++- 3 files changed, 9 insertions(+), 21 deletions(-) rename src/test/integration/controllers/{accounts.controller.e2e-spec.ts => accounts.controller.spec.ts} (98%) diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml index 94c74ede0..0b7d1382d 100644 --- a/.github/workflows/integration.tests.yml +++ b/.github/workflows/integration.tests.yml @@ -27,13 +27,6 @@ jobs: cache: 'npm' - run: npm ci - run: npm run init - - - name: List working directory contents - run: ls -la - - - name: List config directory contents - run: ls -la config/ - - run: npm run test:e2e - name: Collect code coverage run: npm run test:e2e:cov diff --git a/config/configuration.ts b/config/configuration.ts index 4e920e805..73ba5178a 100644 --- a/config/configuration.ts +++ b/config/configuration.ts @@ -1,20 +1,11 @@ import { readFileSync } from 'fs'; -import { join } from 'path'; import * as yaml from 'js-yaml'; +import { join } from 'path'; const YAML_CONFIG_FILENAME = 'config.yaml'; export default () => { - const filePath = join(__dirname, YAML_CONFIG_FILENAME); - console.log('Trying to load config file from:', filePath); - console.log('__dirname:', __dirname); - console.log('process.cwd():', process.cwd()); - - try { - const config = yaml.load(readFileSync(filePath, 'utf8')); - return config as Record; - } catch (error) { - console.error('Error loading the config file:', error); - throw error; - } + return yaml.load( + readFileSync(join(__dirname, YAML_CONFIG_FILENAME), 'utf8'), + ) as Record; }; diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.spec.ts similarity index 98% rename from src/test/integration/controllers/accounts.controller.e2e-spec.ts rename to src/test/integration/controllers/accounts.controller.spec.ts index 95957dcdc..528874600 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.spec.ts @@ -29,7 +29,7 @@ import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.modul import request = require('supertest'); import { ConfigModule } from "@nestjs/config"; -describe('AccountController', () => { +describe.only('AccountController', () => { let app: INestApplication; const path = "/accounts"; @@ -135,6 +135,10 @@ describe('AccountController', () => { }); }); }); + + afterAll(async () => { + await app.close(); + }); }); From 26379beb92d908180f9c911caaacae5cdfa7f6a5 Mon Sep 17 00:00:00 2001 From: cfaur Date: Fri, 23 Feb 2024 15:29:07 +0200 Subject: [PATCH 17/30] fix_3 --- ...counts.controller.spec.ts => accounts.controller.e2e-spec.ts} | 0 .../controllers/services.mock/account.services.mock.ts | 1 + 2 files changed, 1 insertion(+) rename src/test/integration/controllers/{accounts.controller.spec.ts => accounts.controller.e2e-spec.ts} (100%) diff --git a/src/test/integration/controllers/accounts.controller.spec.ts b/src/test/integration/controllers/accounts.controller.e2e-spec.ts similarity index 100% rename from src/test/integration/controllers/accounts.controller.spec.ts rename to src/test/integration/controllers/accounts.controller.e2e-spec.ts diff --git a/src/test/integration/controllers/services.mock/account.services.mock.ts b/src/test/integration/controllers/services.mock/account.services.mock.ts index da4118d29..954062ae2 100644 --- a/src/test/integration/controllers/services.mock/account.services.mock.ts +++ b/src/test/integration/controllers/services.mock/account.services.mock.ts @@ -75,6 +75,7 @@ export const mockApiConfigService = () => ({ getPoolLimit: jest.fn().mockReturnValue(''), getProcessTtl: jest.fn().mockReturnValue(''), getExternalMediaUrl: jest.fn().mockReturnValue(''), + getConfig: jest.fn(), }); export const mockDelegationService = () => ({ From a36d5b3445e334ba6633afb29141df728dadb1d4 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 11:11:59 +0200 Subject: [PATCH 18/30] add jest-unit-config file --- package-lock.json | 71 +++++++++++++++++++ package.json | 4 +- ...2e-spec.ts => accounts.controller.spec.ts} | 2 +- ...er.e2e-spec.ts => tags.controller.spec.ts} | 0 src/test/jest-unit-config.json | 26 +++++++ 5 files changed, 101 insertions(+), 2 deletions(-) rename src/test/integration/controllers/{accounts.controller.e2e-spec.ts => accounts.controller.spec.ts} (99%) rename src/test/integration/controllers/{tags.controller.e2e-spec.ts => tags.controller.spec.ts} (100%) create mode 100644 src/test/jest-unit-config.json diff --git a/package-lock.json b/package-lock.json index a7cfdc2d7..7b89f7294 100644 --- a/package-lock.json +++ b/package-lock.json @@ -79,6 +79,8 @@ "yup": "^0.32.11" }, "devDependencies": { + "@automock/adapters.nestjs": "^2.1.0", + "@automock/jest": "^2.1.0", "@nestjs/cli": "10.1.17", "@nestjs/schematics": "10.0.2", "@nestjs/testing": "10.2.4", @@ -539,6 +541,69 @@ "xss": "^1.0.8" } }, + "node_modules/@automock/adapters.nestjs": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@automock/adapters.nestjs/-/adapters.nestjs-2.1.0.tgz", + "integrity": "sha512-cwolpTMF+frIm6idLC/zD0obgG/Wf5wP6I8FKJBcRy+Cuc9Pyy/E7200zafYlOVzUlZUP16VqchgGWpUyb1U3Q==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "@automock/common": "^3.1.0", + "@automock/types": "^2.0.1", + "reflect-metadata": "^0.1.13" + }, + "engines": { + "node": "^16.10.0 || ^18.12.0 || >=20.0.0" + } + }, + "node_modules/@automock/common": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@automock/common/-/common-3.1.0.tgz", + "integrity": "sha512-Y7N4YnSZRuSIfGV4/PdG2JyURa9PK1maqGZBYUG2/sIW+H/Mlhc/3NpegnlUyQFRBexEJtgmUsvfzzI1/lm0JA==", + "dev": true, + "dependencies": { + "@automock/types": "^2.0.1" + }, + "engines": { + "node": "^16.10.0 || ^18.12.0 || >=20.0.0" + } + }, + "node_modules/@automock/core": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@automock/core/-/core-2.1.0.tgz", + "integrity": "sha512-VIaY2woE7nWXhXKlNzk4+xzCuaVBXfGYwowrzdI+MmJBKqi2z0lUjNVix74hZRWhJpkOW+PR3UThFvThgyqIqQ==", + "dev": true, + "dependencies": { + "@automock/common": "^3.1.0", + "@automock/types": "^2.0.1", + "lodash.isequal": "^4.5.0" + }, + "engines": { + "node": "^16.10.0 || ^18.12.0 || >=20.0.0" + } + }, + "node_modules/@automock/jest": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@automock/jest/-/jest-2.1.0.tgz", + "integrity": "sha512-kJuTu/a5bbG8SICIfITgESpIrVbBfbMykDdICmPvJkeI51Ldq+tqiLS2Ded16vLWS9WeFKeTw/+2b/DO8QyV0Q==", + "dev": true, + "dependencies": { + "@automock/core": "^2.1.0", + "@automock/types": "^2.0.1" + }, + "engines": { + "node": "^16.10.0 || ^18.12.0 || >=20.0.0" + }, + "peerDependencies": { + "jest": "^26 || ^27 || ^28 || ^29" + } + }, + "node_modules/@automock/types": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@automock/types/-/types-2.0.1.tgz", + "integrity": "sha512-ue35e4im3n7l+Eqq3kCA2nNs8jzJbjYLni+vlPdgJ+9KfsEykJjA1OpnNN/PG1tDaM0iyR2p/uZg27MOC/qiTg==", + "dev": true + }, "node_modules/@aws-crypto/crc32": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-3.0.0.tgz", @@ -11300,6 +11365,12 @@ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "dev": true + }, "node_modules/lodash.isinteger": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", diff --git a/package.json b/package.json index d79d38964..f3a7c8650 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "npm run copy-mainnet-config & nest build & jest", "test:watch": "jest --watch", - "test:cov": "jest --coverage --forceExit --detectOpenHandles", + "test:cov": "jest --coverage --forceExit --detectOpenHandles --config ./src/test/jest-unit-config.json", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./src/test/jest-e2e.json --forceExit --maxWorkers=4", "test:e2e:warm": "npm run copy-e2e-mainnet-config & nest build & jest --config ./src/test/jest-e2e-warm.json --forceExit", @@ -146,6 +146,8 @@ "yup": "^0.32.11" }, "devDependencies": { + "@automock/adapters.nestjs": "^2.1.0", + "@automock/jest": "^2.1.0", "@nestjs/cli": "10.1.17", "@nestjs/schematics": "10.0.2", "@nestjs/testing": "10.2.4", diff --git a/src/test/integration/controllers/accounts.controller.e2e-spec.ts b/src/test/integration/controllers/accounts.controller.spec.ts similarity index 99% rename from src/test/integration/controllers/accounts.controller.e2e-spec.ts rename to src/test/integration/controllers/accounts.controller.spec.ts index 528874600..333830524 100644 --- a/src/test/integration/controllers/accounts.controller.e2e-spec.ts +++ b/src/test/integration/controllers/accounts.controller.spec.ts @@ -29,7 +29,7 @@ import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.modul import request = require('supertest'); import { ConfigModule } from "@nestjs/config"; -describe.only('AccountController', () => { +describe('AccountController', () => { let app: INestApplication; const path = "/accounts"; diff --git a/src/test/integration/controllers/tags.controller.e2e-spec.ts b/src/test/integration/controllers/tags.controller.spec.ts similarity index 100% rename from src/test/integration/controllers/tags.controller.e2e-spec.ts rename to src/test/integration/controllers/tags.controller.spec.ts diff --git a/src/test/jest-unit-config.json b/src/test/jest-unit-config.json new file mode 100644 index 000000000..c17b4cf56 --- /dev/null +++ b/src/test/jest-unit-config.json @@ -0,0 +1,26 @@ +{ + "moduleFileExtensions": [ + "js", + "json", + "ts" + ], + "rootDir": "../../", + "testEnvironment": "node", + "testRegex": ".spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + }, + "modulePaths": [ + "" + ], + "collectCoverageFrom": [ + "./src/**/*.(t|j)s", + "!./src/crons/**", + "!./src/decorators/**", + "!./src/interceptors/**", + "!./src/test/**", + "!./src/websockets/**" + ], + "coverageDirectory": "./coverage/unit", + "testTimeout": 180000 +} \ No newline at end of file From bac6b72378843d7207fe6b4a655f788afbda4e8c Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 11:13:27 +0200 Subject: [PATCH 19/30] remove integration action --- .github/workflows/integration.tests.yml | 39 ------------------------- 1 file changed, 39 deletions(-) delete mode 100644 .github/workflows/integration.tests.yml diff --git a/.github/workflows/integration.tests.yml b/.github/workflows/integration.tests.yml deleted file mode 100644 index 0b7d1382d..000000000 --- a/.github/workflows/integration.tests.yml +++ /dev/null @@ -1,39 +0,0 @@ -# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions - -name: E2E tests - -on: - push: - branches: [main, development] - pull_request: - branches: [main, development] - -jobs: - build: - runs-on: ubuntu-latest - - strategy: - matrix: - node-version: [16.x] - # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ - - steps: - - uses: actions/checkout@v3 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node-version }} - cache: 'npm' - - run: npm ci - - run: npm run init - - run: npm run test:e2e - - name: Collect code coverage - run: npm run test:e2e:cov - - uses: codecov/codecov-action@v3 - with: - files: ./coverage/e2e/clover.xml - flags: e2etests - name: codecov-umbrella - fail_ci_if_error: true - verbose: true From e0bfa547d41259dad906939834b94bf9f3c1ef8d Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 12:01:58 +0200 Subject: [PATCH 20/30] update accounts controller --- .../controllers/accounts.controller.spec.ts | 119 +++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-) diff --git a/src/test/integration/controllers/accounts.controller.spec.ts b/src/test/integration/controllers/accounts.controller.spec.ts index 333830524..0c668b843 100644 --- a/src/test/integration/controllers/accounts.controller.spec.ts +++ b/src/test/integration/controllers/accounts.controller.spec.ts @@ -26,8 +26,10 @@ import { TokenModule } from "src/endpoints/tokens/token.module"; import { TransactionModule } from "src/endpoints/transactions/transaction.module"; import { TransferModule } from "src/endpoints/transfers/transfer.module"; import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.module"; -import request = require('supertest'); +import { QueryPagination } from "src/common/entities/query.pagination"; import { ConfigModule } from "@nestjs/config"; +import request = require('supertest'); + describe('AccountController', () => { let app: INestApplication; @@ -73,6 +75,61 @@ describe('AccountController', () => { await app.init(); }); + describe("GET /accounts", () => { + it('should return the default list of 25 accounts', async () => { + const defaultAccountsList = createMockAccountsList(25); + accountServiceMocks.getAccounts.mockReturnValue(defaultAccountsList); + + await request(app.getHttpServer()) + .get(`${path}`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(25); + expect(response.body).toEqual(defaultAccountsList); + }); + }); + + it('should return a paginated list of accounts when "from" and "size" query parameters are provided', async () => { + const paginatedAccountsList = createMockAccountsList(10); + accountServiceMocks.getAccounts.mockReturnValue(paginatedAccountsList); + + const queryPagination = new QueryPagination({ from: 5, size: 10 }); + await request(app.getHttpServer()) + .get(`${path}?from=${queryPagination.from}&size=${queryPagination.size}`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(10); + expect(response.body).toEqual(paginatedAccountsList); + }); + }); + + it('should sort accounts by balance when "sort" query parameter is set to "balance"', async () => { + const sortedAccountsList = createMockAccountsList(10).sort((a, b) => parseInt(a.balance) - parseInt(b.balance)); + accountServiceMocks.getAccounts.mockReturnValue(sortedAccountsList); + + const sort = 'balance'; + await request(app.getHttpServer()) + .get(`${path}?sort=${sort}`) + .expect(200) + .expect(response => { + const isSortedByBalance = response.body.every( + (account: { balance: string; }, i: number, arr: { balance: string; }[]) => i === 0 || parseInt(arr[i - 1].balance) <= parseInt(account.balance)); + expect(isSortedByBalance).toBeTruthy(); + }); + }); + + it('should return only smart contracts when "isSmartContract" query parameter is set to true', async () => { + const smartContractsList = createMockAccountsList(5, undefined, true); + accountServiceMocks.getAccounts.mockReturnValue(smartContractsList); + await request(app.getHttpServer()) + .get(`${path}?isSmartContract=true`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(5); + }); + }); + }); + describe("GET /accounts/count", () => { it('should return total accounts count', async () => { accountServiceMocks.getAccountsCount.mockReturnValue(100); @@ -136,9 +193,69 @@ describe('AccountController', () => { }); }); + describe("GET /accounts/c", () => { + it('should return total alternative accounts count', async () => { + accountServiceMocks.getAccountsCount.mockReturnValue(100); + + await request(app.getHttpServer()) + .get(`${path}/c`) + .expect(200) + .expect(response => { + expect(+response.text).toStrictEqual(100); + }); + }); + }); + afterAll(async () => { await app.close(); }); + + function createMockAccountsList(numberOfAccounts: number, ownerAddress = null, includeSmartContracts = false) { + return Array.from({ length: numberOfAccounts }, (_, index) => { + const isSmartContractAddress = includeSmartContracts && Math.random() < 0.5; + + return { + address: ownerAddress || (isSmartContractAddress ? generateMockSmartContractAddress() : generateMockAddress()), + balance: generateRandomBalance(), + nonce: Math.floor(Math.random() * 100), + timestamp: Math.floor(Date.now() / 1000) - index * 1000, + shard: Math.floor(Math.random() * 4), + ownerAddress: ownerAddress || generateMockAddress(), + ownerAssets: undefined, + assets: undefined, + }; + }); + } + + function generateMockSmartContractAddress() { + const prefix = 'erd1'; + const middle = 'q'.repeat(38); + const suffixLength = 62 - prefix.length - middle.length; + let suffix = ''; + + while (suffix.length < suffixLength) { + suffix += Math.random().toString(36).substr(2); + } + + suffix = suffix.substring(0, suffixLength); + + return `${prefix}${middle}${suffix}`; + } + + function generateRandomBalance() { + return (Math.floor(Math.random() * 1000000) + 100000).toString(); + } + + function generateMockAddress() { + const desiredLength = 62 - 'erd1'.length; + let address = 'erd1'; + + while (address.length < desiredLength + 'erd1'.length) { + address += Math.random().toString(36).substring(2); + } + + return address.substring(0, desiredLength + 'erd1'.length); + } }); From 4f14a8dbe93bfd8795a4903f7b402e32dc40361b Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 13:49:59 +0200 Subject: [PATCH 21/30] add more tests --- .../controllers/accounts.controller.spec.ts | 123 +++++++++++++++++- 1 file changed, 122 insertions(+), 1 deletion(-) diff --git a/src/test/integration/controllers/accounts.controller.spec.ts b/src/test/integration/controllers/accounts.controller.spec.ts index 0c668b843..413735a37 100644 --- a/src/test/integration/controllers/accounts.controller.spec.ts +++ b/src/test/integration/controllers/accounts.controller.spec.ts @@ -28,6 +28,7 @@ import { TransferModule } from "src/endpoints/transfers/transfer.module"; import { WaitingListModule } from "src/endpoints/waiting-list/waiting.list.module"; import { QueryPagination } from "src/common/entities/query.pagination"; import { ConfigModule } from "@nestjs/config"; +import { AccountDeferred } from "src/endpoints/accounts/entities/account.deferred"; import request = require('supertest'); @@ -206,6 +207,126 @@ describe('AccountController', () => { }); }); + describe("GET /accounts/:address", () => { + const mockAccount = { + address: 'erd1vtlpm6sxxvmgt43ldsrpswjrfcsudmradylpxn9jkp66ra3rkz4qruzvfw', + balance: '707809', + nonce: 46, + timestamp: 1708946805, + shard: 3, + ownerAddress: 'erd1vtlpm6sxxvmgt43ldsrpswjrfcsudmradylpxn9jkp66ra3rkz4qruzvfw', + ownerAssets: undefined, + assets: undefined, + }; + + it('should return account details for a given address', async () => { + accountServiceMocks.getAccount.mockReturnValue(mockAccount); + + await request(app.getHttpServer()) + .get(`${path}/${mockAccount.address}`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockAccount); + }); + }); + + it('should throw 400 Bad Request for a given invalid address value', async () => { + await request(app.getHttpServer()) + .get(`${path}/erd1...`) + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'address' (a bech32 address is expected)"); + }); + }); + + it('should return account details including guardian info when withGuardianInfo is true', async () => { + const mockAddressList = createMockAccountsList(1); + const accountDetails = mockAddressList[0]; + const address = "erd1rf4hv70arudgzus0ymnnsnc4pml0jkywg2xjvzslg0mz4nn2tg7q7k0t6p"; + const mockAccountWithGuardianInfo = { + ...accountDetails, + isGuarded: true, + activeGuardianActivationEpoch: 496, + activeGuardianAddress: "erd1x5d4p63uwcns8cvyrl4g3qgvwwa2nkt5jdp0vwetc7csqzpjzz0qec58k0", + activeGuardianServiceUid: "MultiversXTCSService", + }; + + accountServiceMocks.getAccount.mockResolvedValue(mockAccountWithGuardianInfo); + + await request(app.getHttpServer()) + .get(`/accounts/${address}?withGuardianInfo=true`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockAccountWithGuardianInfo); + expect(response.body.isGuarded).toStrictEqual(true); + }); + }); + + it('should return account details filtered by fields', async () => { + const address = "erd1s6uspvcnwr254ag8urs62m8e554hkf8yqpegwrgtxvzw3ddksjcs66g0u2"; + const fields = ['balance', 'nonce']; + const mockAccountFilteredFields = { + balance: "1000", + nonce: 1, + }; + + accountServiceMocks.getAccount.mockResolvedValue(mockAccountFilteredFields); + + await request(app.getHttpServer()) + .get(`/accounts/${address}?fields=${fields.join(',')}`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockAccountFilteredFields); + expect(Object.keys(response.body).sort()).toEqual(fields.sort()); + }); + }); + }); + + describe("GET /accounts/:address/deferred", () => { + const address = "erd1s6uspvcnwr254ag8urs62m8e554hkf8yqpegwrgtxvzw3ddksjcs66g0u2"; + + it('should return deferred payments from legacy staking', async () => { + const mockDeferred: AccountDeferred[] = [ + { + deferredPayment: "1", + secondsLeft: 2, + }, + ]; + + accountServiceMocks.getDeferredAccount.mockResolvedValue(mockDeferred); + + await request(app.getHttpServer()) + .get(`/accounts/${address}/deferred`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockDeferred); + }); + }); + + it('should return an empty array when there are no deferred payments', async () => { + accountServiceMocks.getDeferredAccount.mockResolvedValue([]); + + await request(app.getHttpServer()) + .get(`/accounts/${address}/deferred`) + .expect(200) + .expect(response => { + expect(response.body).toEqual([]); + }); + }); + + it('should return 400 Bad Request for an invalid address format', async () => { + const invalidAddress = "invalid_address"; + + await request(app.getHttpServer()) + .get(`/accounts/${invalidAddress}/deferred`) + .expect(400) + .expect(response => { + expect(response.body.message).toContain("Validation failed for argument 'address' (a bech32 address is expected)"); + }); + }); + + }); + afterAll(async () => { await app.close(); }); @@ -234,7 +355,7 @@ describe('AccountController', () => { let suffix = ''; while (suffix.length < suffixLength) { - suffix += Math.random().toString(36).substr(2); + suffix += Math.random().toString(36).substring(2); } suffix = suffix.substring(0, suffixLength); From a976ea20140a489048eae7e4aceb42a73570ea23 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 14:57:41 +0200 Subject: [PATCH 22/30] add blocks.controller.spec.ts --- .../controllers/blocks.controller.spec.ts | 314 ++++++++++++++++++ .../services.mock/block.services.mock.ts | 6 + 2 files changed, 320 insertions(+) create mode 100644 src/test/integration/controllers/blocks.controller.spec.ts create mode 100644 src/test/integration/controllers/services.mock/block.services.mock.ts diff --git a/src/test/integration/controllers/blocks.controller.spec.ts b/src/test/integration/controllers/blocks.controller.spec.ts new file mode 100644 index 000000000..691c4a172 --- /dev/null +++ b/src/test/integration/controllers/blocks.controller.spec.ts @@ -0,0 +1,314 @@ +import { HttpException, HttpStatus, INestApplication } from "@nestjs/common"; +import { mockBlockService } from "./services.mock/block.services.mock"; +import { Test, TestingModule } from "@nestjs/testing"; +import { BlockController } from "src/endpoints/blocks/block.controller"; +import { BlockService } from "src/endpoints/blocks/block.service"; +import request = require('supertest'); +import { PublicAppModule } from "src/public.app.module"; +import { QueryPagination } from "src/common/entities/query.pagination"; + +describe("BlockController", () => { + let app: INestApplication; + const path = "/blocks"; + const blockServiceMock = mockBlockService(); + + beforeEach(async () => { + jest.resetAllMocks(); + const moduleFixture: TestingModule = await Test.createTestingModule({ + controllers: [BlockController], + imports: [PublicAppModule], + }) + .overrideProvider(BlockService) + .useValue(blockServiceMock) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe('GET /blocks', () => { + it('should return a list of blocks', async () => { + const mockBlocksList = createMockBlocksList(10); + blockServiceMock.getBlocks.mockResolvedValue(mockBlocksList); + + await request(app.getHttpServer()) + .get(`${path}`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(10); + expect(response.body).toEqual(mockBlocksList); + }); + }); + + it('should filter blocks by shard', async () => { + const shard = 1; + const filteredBlocksList = createMockBlocksList(5).map(block => ({ ...block, shard })); + blockServiceMock.getBlocks.mockResolvedValue(filteredBlocksList); + + await request(app.getHttpServer()) + .get(`${path}?shard=${shard}`) + .expect(200) + .expect(response => { + expect(response.body.every((block: { shard: number; }) => block.shard === shard)).toBeTruthy(); + }); + }); + + it('should paginate the blocks list', async () => { + const queryPagination = new QueryPagination({ from: 0, size: 5 }); + const paginatedBlocksList = createMockBlocksList(queryPagination.size); + blockServiceMock.getBlocks.mockResolvedValue(paginatedBlocksList); + + await request(app.getHttpServer()) + .get(`${path}?from=${queryPagination.from}&size=${queryPagination.size}`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(queryPagination.size); + }); + }); + + it('should filter blocks by epoch', async () => { + const epoch = 100; + const filteredBlocksList = createMockBlocksList(3).map(block => ({ ...block, epoch })); + blockServiceMock.getBlocks.mockResolvedValue(filteredBlocksList); + + await request(app.getHttpServer()) + .get(`${path}?epoch=${epoch}`) + .expect(200) + .expect(response => { + expect(response.body.every((block: { epoch: number; }) => block.epoch === epoch)).toBeTruthy(); + }); + }); + }); + + describe('GET /blocks/count', () => { + it('should return the total count of all blocks', async () => { + const totalBlocksCount = 12345; + blockServiceMock.getBlocksCount.mockResolvedValue(totalBlocksCount); + + const response = await request(app.getHttpServer()) + .get(`${path}/count`) + .expect(200); + + expect(+response.text).toEqual(totalBlocksCount); + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({}); + }); + + it('should return the count of blocks for a specific shard', async () => { + const shardBlocksCount = 2345; + blockServiceMock.getBlocksCount.mockResolvedValue(shardBlocksCount); + + await request(app.getHttpServer()) + .get(`${path}/count?shard=1`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(shardBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ shard: 1 }); + }); + + it('should return the count of blocks filtered by proposer', async () => { + const proposerBlocksCount = 345; + blockServiceMock.getBlocksCount.mockResolvedValue(proposerBlocksCount); + const proposer = 'f0403707977aed967d5ecca08b5a17aa98b2f714499cc41c07763d5d3552efa9067e0de794559eaa1bde7a1183ccbf014faefd43a588596f737357aeb8e35debc373f719c7ecd06f9d434ca90dd6576bd2040ce91b224b7ba26f8ea70932b58c'; + + await request(app.getHttpServer()) + .get(`${path}/count?proposer=${proposer}`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(proposerBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ proposer }); + }); + + it('should return the count of blocks filtered by multiple parameters', async () => { + const filteredBlocksCount = 45; + blockServiceMock.getBlocksCount.mockResolvedValue(filteredBlocksCount); + const shard = 1; + const epoch = 10; + + await request(app.getHttpServer()) + .get(`${path}/count?shard=${shard}&epoch=${epoch}`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(filteredBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ shard, epoch }); + }); + + it('should handle invalid query parameters gracefully', async () => { + await request(app.getHttpServer()) + .get('/blocks/count?shard=invalidShard') + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'shard' (optional number is expected)"); + }); + }); + }); + + describe('GET /blocks/c', () => { + it('should return the total count of all blocks', async () => { + const totalBlocksCount = 12345; + blockServiceMock.getBlocksCount.mockResolvedValue(totalBlocksCount); + + const response = await request(app.getHttpServer()) + .get(`${path}/c`) + .expect(200); + + expect(+response.text).toEqual(totalBlocksCount); + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({}); + }); + + it('should return the count of blocks for a specific shard', async () => { + const shardBlocksCount = 2345; + blockServiceMock.getBlocksCount.mockResolvedValue(shardBlocksCount); + + await request(app.getHttpServer()) + .get(`${path}/c?shard=1`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(shardBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ shard: 1 }); + }); + + it('should return the count of blocks filtered by proposer', async () => { + const proposerBlocksCount = 345; + blockServiceMock.getBlocksCount.mockResolvedValue(proposerBlocksCount); + const proposer = 'f0403707977aed967d5ecca08b5a17aa98b2f714499cc41c07763d5d3552efa9067e0de794559eaa1bde7a1183ccbf014faefd43a588596f737357aeb8e35debc373f719c7ecd06f9d434ca90dd6576bd2040ce91b224b7ba26f8ea70932b58c'; + + await request(app.getHttpServer()) + .get(`${path}/c?proposer=${proposer}`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(proposerBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ proposer }); + }); + + it('should return the count of blocks filtered by multiple parameters', async () => { + const filteredBlocksCount = 45; + blockServiceMock.getBlocksCount.mockResolvedValue(filteredBlocksCount); + const shard = 1; + const epoch = 10; + + await request(app.getHttpServer()) + .get(`${path}/c?shard=${shard}&epoch=${epoch}`) + .expect(200) + .expect(response => { + expect(+response.text).toEqual(filteredBlocksCount); + }); + + expect(blockServiceMock.getBlocksCount).toHaveBeenCalledWith({ shard, epoch }); + }); + + it('should handle invalid query parameters gracefully', async () => { + await request(app.getHttpServer()) + .get('/blocks/c?shard=invalidShard') + .expect(400) + .expect(response => { + expect(response.body.message).toStrictEqual("Validation failed for argument 'shard' (optional number is expected)"); + }); + }); + }); + + describe('GET /blocks/latest', () => { + it('should return the latest block details', async () => { + const mockLatestBlock = createMockBlocksList(1)[0]; + blockServiceMock.getLatestBlock.mockResolvedValue(mockLatestBlock); + + await request(app.getHttpServer()) + .get(`${path}/latest`) + .expect(200) + .expect(response => { + expect(response.body).toMatchObject(mockLatestBlock); + }); + }); + + it('should return 404 Not Found when no block is found', async () => { + blockServiceMock.getLatestBlock.mockResolvedValue(null); + await request(app.getHttpServer()) + .get(`${path}/latest`) + .expect(404) + .expect(response => { + expect(response.body.message).toEqual("Block not found"); + }); + }); + + it('should calculate the nonce frequency based on ttl value', async () => { + const mockBlockWithTTL = createMockBlocksList(1)[0]; + blockServiceMock.getLatestBlock.mockResolvedValue(mockBlockWithTTL); + + const ttl = 3600; + await request(app.getHttpServer()) + .get(`${path}/latest?ttl=${ttl}`) + .expect(200) + .expect(response => { + expect(response.body).toMatchObject(mockBlockWithTTL); + }); + }); + }); + + + describe("GET /blocks/:hash", () => { + it('should return block information details for a given hash', async () => { + const mockBlockDetailed = createMockBlocksList(1)[0]; + const blockHash = mockBlockDetailed.hash; + blockServiceMock.getBlock.mockResolvedValue(mockBlockDetailed); + + await request(app.getHttpServer()) + .get(`${path}/${blockHash}`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockBlockDetailed); + }); + }); + + it('should return a 404 Not Found when the block does not exist', async () => { + const blockHash = '7ecdb6028565f92851170c70443a5c2099af1f740f0560d60429194bac14b521'; + blockServiceMock.getBlock.mockRejectedValue(new HttpException('Block not found', HttpStatus.NOT_FOUND)); + + await request(app.getHttpServer()) + .get(`${path}/${blockHash}`) + .expect(404) + .expect(response => { + expect(response.body.message).toEqual('Block not found'); + }); + }); + }); + + function generateRandomHash() { + return [...Array(64)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); + } + + function generateRandomProposer() { + return [...Array(128)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); + } + + function createMockBlocksList(numberOfBlocks: any) { + return Array.from({ length: numberOfBlocks }, () => ({ + hash: generateRandomHash(), + epoch: Math.floor(Math.random() * 1000), + nonce: Math.floor(Math.random() * 10000), + prevHash: generateRandomHash(), + proposer: generateRandomProposer(), + pubKeyBitmap: 'ffffffffffffff7f', + round: Math.floor(Math.random() * 100000), + shard: Math.floor(Math.random() * 3), + size: Math.floor(Math.random() * 1000) + 500, + sizeTxs: Math.floor(Math.random() * 6000), + stateRootHash: generateRandomHash(), + timestamp: Date.now() / 1000 - Math.floor(Math.random() * 100000), + txCount: Math.floor(Math.random() * 100), + gasConsumed: Math.floor(Math.random() * 1000000), + gasRefunded: Math.floor(Math.random() * 100000), + gasPenalized: Math.floor(Math.random() * 10000), + maxGasLimit: Math.floor(Math.random() * 10000000), + scheduledRootHash: generateRandomHash(), + })); + } +}); diff --git a/src/test/integration/controllers/services.mock/block.services.mock.ts b/src/test/integration/controllers/services.mock/block.services.mock.ts new file mode 100644 index 000000000..53a477a12 --- /dev/null +++ b/src/test/integration/controllers/services.mock/block.services.mock.ts @@ -0,0 +1,6 @@ +export const mockBlockService = () => ({ + getBlocks: jest.fn().mockResolvedValue([]), + getBlocksCount: jest.fn().mockResolvedValue(0), + getLatestBlock: jest.fn().mockResolvedValue({}), + getBlock: jest.fn().mockResolvedValue({}), +}); From 6901cac3629566e6fb66492632fb466a87af2dad Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 15:10:58 +0200 Subject: [PATCH 23/30] change directory --- .../{integration => unit}/controllers/accounts.controller.spec.ts | 0 .../{integration => unit}/controllers/blocks.controller.spec.ts | 0 .../controllers/services.mock/account.services.mock.ts | 0 .../controllers/services.mock/block.services.mock.ts | 0 .../{integration => unit}/controllers/tags.controller.spec.ts | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename src/test/{integration => unit}/controllers/accounts.controller.spec.ts (100%) rename src/test/{integration => unit}/controllers/blocks.controller.spec.ts (100%) rename src/test/{integration => unit}/controllers/services.mock/account.services.mock.ts (100%) rename src/test/{integration => unit}/controllers/services.mock/block.services.mock.ts (100%) rename src/test/{integration => unit}/controllers/tags.controller.spec.ts (100%) diff --git a/src/test/integration/controllers/accounts.controller.spec.ts b/src/test/unit/controllers/accounts.controller.spec.ts similarity index 100% rename from src/test/integration/controllers/accounts.controller.spec.ts rename to src/test/unit/controllers/accounts.controller.spec.ts diff --git a/src/test/integration/controllers/blocks.controller.spec.ts b/src/test/unit/controllers/blocks.controller.spec.ts similarity index 100% rename from src/test/integration/controllers/blocks.controller.spec.ts rename to src/test/unit/controllers/blocks.controller.spec.ts diff --git a/src/test/integration/controllers/services.mock/account.services.mock.ts b/src/test/unit/controllers/services.mock/account.services.mock.ts similarity index 100% rename from src/test/integration/controllers/services.mock/account.services.mock.ts rename to src/test/unit/controllers/services.mock/account.services.mock.ts diff --git a/src/test/integration/controllers/services.mock/block.services.mock.ts b/src/test/unit/controllers/services.mock/block.services.mock.ts similarity index 100% rename from src/test/integration/controllers/services.mock/block.services.mock.ts rename to src/test/unit/controllers/services.mock/block.services.mock.ts diff --git a/src/test/integration/controllers/tags.controller.spec.ts b/src/test/unit/controllers/tags.controller.spec.ts similarity index 100% rename from src/test/integration/controllers/tags.controller.spec.ts rename to src/test/unit/controllers/tags.controller.spec.ts From 5a0f7f45be3ab4a60a95c53e63d1d49a21aadeda Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 15:18:15 +0200 Subject: [PATCH 24/30] add delegation.controller.spec.ts --- .../controllers/blocks.controller.spec.ts | 4 ++ .../controllers/delegation.controller.spec.ts | 50 +++++++++++++++++++ .../services.mock/delegation.services.mock.ts | 3 ++ 3 files changed, 57 insertions(+) create mode 100644 src/test/unit/controllers/delegation.controller.spec.ts create mode 100644 src/test/unit/controllers/services.mock/delegation.services.mock.ts diff --git a/src/test/unit/controllers/blocks.controller.spec.ts b/src/test/unit/controllers/blocks.controller.spec.ts index 691c4a172..9469551ad 100644 --- a/src/test/unit/controllers/blocks.controller.spec.ts +++ b/src/test/unit/controllers/blocks.controller.spec.ts @@ -281,6 +281,10 @@ describe("BlockController", () => { }); }); + afterAll(async () => { + await app.close(); + }); + function generateRandomHash() { return [...Array(64)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); } diff --git a/src/test/unit/controllers/delegation.controller.spec.ts b/src/test/unit/controllers/delegation.controller.spec.ts new file mode 100644 index 000000000..9b7c85b26 --- /dev/null +++ b/src/test/unit/controllers/delegation.controller.spec.ts @@ -0,0 +1,50 @@ +import { INestApplication } from "@nestjs/common"; +import { Test } from "@nestjs/testing"; +import request = require('supertest'); +import { mockDelegationService } from "./services.mock/delegation.services.mock"; +import { DelegationController } from "src/endpoints/delegation/delegation.controller"; +import { DelegationModule } from "src/endpoints/delegation/delegation.module"; +import { DelegationService } from "src/endpoints/delegation/delegation.service"; + +describe('DelegationController', () => { + let app: INestApplication; + const path: string = "/delegation"; + const delegationServiceMocks = mockDelegationService(); + + beforeAll(async () => { + jest.resetAllMocks(); + const moduleFixture = await Test.createTestingModule({ + controllers: [DelegationController], + imports: [DelegationModule], + }) + .overrideProvider(DelegationService) + .useValue(delegationServiceMocks) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe("GET /delegation", () => { + it('should return delegation staking contract information', async () => { + const mockDelegationDetails = { + stake: '1000000000000000000000', + topUp: '500000000000000000000', + locked: '0', + minDelegation: '25000000000000000000', + }; + delegationServiceMocks.getDelegation.mockResolvedValue(mockDelegationDetails); + + await request(app.getHttpServer()) + .get(`${path}`) + .expect(200) + .expect(response => { + expect(response.body).toMatchObject(mockDelegationDetails); + }); + }); + }); + + afterAll(async () => { + await app.close(); + }); +}); diff --git a/src/test/unit/controllers/services.mock/delegation.services.mock.ts b/src/test/unit/controllers/services.mock/delegation.services.mock.ts new file mode 100644 index 000000000..73f275a4d --- /dev/null +++ b/src/test/unit/controllers/services.mock/delegation.services.mock.ts @@ -0,0 +1,3 @@ +export const mockDelegationService = () => ({ + getDelegation: jest.fn().mockResolvedValue({}), +}); From 9a92eae6a9422869461ab99fb34237b6bae07ba8 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 15:19:33 +0200 Subject: [PATCH 25/30] remap import --- src/test/unit/controllers/accounts.controller.spec.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/unit/controllers/accounts.controller.spec.ts b/src/test/unit/controllers/accounts.controller.spec.ts index 413735a37..bd132dbbe 100644 --- a/src/test/unit/controllers/accounts.controller.spec.ts +++ b/src/test/unit/controllers/accounts.controller.spec.ts @@ -13,7 +13,6 @@ import { TransactionService } from "src/endpoints/transactions/transaction.servi import { TransferService } from "src/endpoints/transfers/transfer.service"; import { WaitingListService } from "src/endpoints/waiting-list/waiting.list.service"; import { AccountController } from "src/endpoints/accounts/account.controller"; -import { mockAccountService, mockApiConfigService, mockCollectionService, mockDelegationLegacyService, mockDelegationService, mockNftService, mockSmartContractResultService, mockStakeService, mockTokenService, mockTransactionService, mockTransferService, mockWaitingListService } from "src/test/integration/controllers/services.mock/account.services.mock"; import { ApiConfigModule } from "src/common/api-config/api.config.module"; import { AccountModule } from "src/endpoints/accounts/account.module"; import { CollectionModule } from "src/endpoints/collections/collection.module"; @@ -30,7 +29,7 @@ import { QueryPagination } from "src/common/entities/query.pagination"; import { ConfigModule } from "@nestjs/config"; import { AccountDeferred } from "src/endpoints/accounts/entities/account.deferred"; import request = require('supertest'); - +import { mockAccountService, mockTokenService, mockNftService, mockDelegationLegacyService, mockWaitingListService, mockStakeService, mockTransactionService, mockSmartContractResultService, mockCollectionService, mockTransferService, mockApiConfigService, mockDelegationService } from "./services.mock/account.services.mock"; describe('AccountController', () => { let app: INestApplication; From d4f8fe3c167e5b81cbe4bdfa5bf3b74b8df994e2 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 15:57:21 +0200 Subject: [PATCH 26/30] add identities.controller.spec.ts --- package.json | 2 +- .../controllers/identities.controller.spec.ts | 119 ++++++++++++++++++ .../services.mock/identity.services.mock.ts | 5 + 3 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 src/test/unit/controllers/identities.controller.spec.ts create mode 100644 src/test/unit/controllers/services.mock/identity.services.mock.ts diff --git a/package.json b/package.json index f3a7c8650..094d414b6 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "start:mainnet:debug": "npm run copy-mainnet-config & nest start --watch --debug", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\"", "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", - "test": "npm run copy-mainnet-config & nest build & jest", + "test": "npm run copy-mainnet-config & nest build & jest --detectOpenHandles", "test:watch": "jest --watch", "test:cov": "jest --coverage --forceExit --detectOpenHandles --config ./src/test/jest-unit-config.json", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", diff --git a/src/test/unit/controllers/identities.controller.spec.ts b/src/test/unit/controllers/identities.controller.spec.ts new file mode 100644 index 000000000..b159977b1 --- /dev/null +++ b/src/test/unit/controllers/identities.controller.spec.ts @@ -0,0 +1,119 @@ +import { INestApplication } from "@nestjs/common"; +import { Test } from "@nestjs/testing"; +import request = require('supertest'); +import { mockIdentityService } from "./services.mock/identity.services.mock"; +import { IdentitiesController } from "src/endpoints/identities/identities.controller"; +import { PublicAppModule } from "src/public.app.module"; +import { IdentitiesService } from "src/endpoints/identities/identities.service"; + +describe('IdentityController', () => { + let app: INestApplication; + const path: string = "/identities"; + const identitiesServiceMocks = mockIdentityService(); + + beforeAll(async () => { + jest.resetAllMocks(); + const moduleFixture = await Test.createTestingModule({ + controllers: [IdentitiesController], + imports: [PublicAppModule], + }) + .overrideProvider(IdentitiesService) + .useValue(identitiesServiceMocks) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe("GET /identities", () => { + it('should return a list of all node identities', async () => { + const mockIdentitiesList = createMockIdentitiesList(5); + identitiesServiceMocks.getIdentities.mockResolvedValue(mockIdentitiesList); + + await request(app.getHttpServer()) + .get(`${path}`) + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockIdentitiesList); + expect(response.body.length).toBe(5); + }); + }); + }); + + describe("GET /identities/:identifier", () => { + it('should return the details of a single identity when found', async () => { + const mockIdentity = createMockIdentitiesList(1)[0]; + identitiesServiceMocks.getIdentity.mockResolvedValue(mockIdentity); + + await request(app.getHttpServer()) + .get(`${path}/${mockIdentity.identity}`) + .expect(200) + .expect(response => { + expect(response.body).toMatchObject(mockIdentity); + }); + }); + + it('should return a 404 Not Found when the identity does not exist', async () => { + const identifier = 'nonexistent'; + identitiesServiceMocks.getIdentity.mockResolvedValue(undefined); + + await request(app.getHttpServer()) + .get(`${path}/${identifier}`) + .expect(404) + .expect(response => { + expect(response.body.message).toEqual('Identity not found'); + }); + }); + }); + + describe('GET /identities/:identifier/avatar', () => { + it('should redirect to the avatar of a specific identity when found', async () => { + const identifier = 'multiversx'; + const avatarUrl = 'http://example.com/avatar.png'; + identitiesServiceMocks.getIdentityAvatar.mockResolvedValue(avatarUrl); + + await request(app.getHttpServer()) + .get(`/identities/${identifier}/avatar`) + .expect(302) + .expect('Location', avatarUrl); + }); + + it('should return a 404 Not Found when the avatar does not exist', async () => { + const identifier = 'nonexistent'; + identitiesServiceMocks.getIdentityAvatar.mockResolvedValue(null); + + await request(app.getHttpServer()) + .get(`/identities/${identifier}/avatar`) + .expect(404) + .expect(response => { + expect(response.body.message).toEqual('Identity avatar not found'); + }); + }); + }); + + afterAll(async () => { + await app.close(); + }); + + function createMockIdentitiesList(numberOfIdentities: number) { + return Array.from({ length: numberOfIdentities }, (_, index) => ({ + identity: "multiversx" + (index ? `_${index}` : ''), + name: `Name ${index}`, + description: `Description for identity ${index}`, + avatar: "https://raw.githubusercontent.com/multiversx/mx-assets/master/identities/multiversx/logo.png", + website: "http://multiversx.com", + twitter: `@identity${index} `, + location: `Location ${index} `, + score: 636.0000000000013, + validators: 530, + stake: "1325000000000000000000000", + topUp: "1709999999999999983222620", + locked: "3034999999999999983222620", + distribution: { 'direct': 1 }, + providers: [`provider${index} `], + stakePercent: 17.83, + rank: index + 1, + apr: 7.54, + })); + } +}); diff --git a/src/test/unit/controllers/services.mock/identity.services.mock.ts b/src/test/unit/controllers/services.mock/identity.services.mock.ts new file mode 100644 index 000000000..6b48947b7 --- /dev/null +++ b/src/test/unit/controllers/services.mock/identity.services.mock.ts @@ -0,0 +1,5 @@ +export const mockIdentityService = () => ({ + getIdentities: jest.fn().mockResolvedValue([]), + getIdentity: jest.fn().mockResolvedValue({}), + getIdentityAvatar: jest.fn().mockResolvedValue(undefined), +}); From a4c280ca8ce2eed111878ef5157defb63ca70ea7 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 16:03:21 +0200 Subject: [PATCH 27/30] remove openHandles --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 094d414b6..f3a7c8650 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "start:mainnet:debug": "npm run copy-mainnet-config & nest start --watch --debug", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\"", "lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", - "test": "npm run copy-mainnet-config & nest build & jest --detectOpenHandles", + "test": "npm run copy-mainnet-config & nest build & jest", "test:watch": "jest --watch", "test:cov": "jest --coverage --forceExit --detectOpenHandles --config ./src/test/jest-unit-config.json", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", From db179b26f65a9eb032e7bc927f9ec2f6b25ddf34 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 17:34:30 +0200 Subject: [PATCH 28/30] add miniblocks.controller.spec.ts --- .../controllers/mini.block.controller.spec.ts | 110 ++++++++++++++++++ .../services.mock/mini.block.service.mock.ts | 4 + 2 files changed, 114 insertions(+) create mode 100644 src/test/unit/controllers/mini.block.controller.spec.ts create mode 100644 src/test/unit/controllers/services.mock/mini.block.service.mock.ts diff --git a/src/test/unit/controllers/mini.block.controller.spec.ts b/src/test/unit/controllers/mini.block.controller.spec.ts new file mode 100644 index 000000000..280dbe358 --- /dev/null +++ b/src/test/unit/controllers/mini.block.controller.spec.ts @@ -0,0 +1,110 @@ +import { HttpException, HttpStatus, INestApplication } from "@nestjs/common"; +import { Test, TestingModule } from "@nestjs/testing"; +import { MiniBlockController } from "src/endpoints/miniblocks/mini.block.controller"; +import { MiniBlockService } from "src/endpoints/miniblocks/mini.block.service"; +import { MiniBlockModule } from "src/endpoints/miniblocks/miniblock.module"; +import { mockMiniBlockService } from "./services.mock/mini.block.service.mock"; +import request = require('supertest'); +import { QueryPagination } from "src/common/entities/query.pagination"; + +describe("MiniBlockController", () => { + let app: INestApplication; + const path = "/miniblocks"; + const miniBlockServiceMock = mockMiniBlockService(); + + beforeEach(async () => { + jest.resetAllMocks(); + const moduleFixture: TestingModule = await Test.createTestingModule({ + controllers: [MiniBlockController], + imports: [MiniBlockModule], + }) + .overrideProvider(MiniBlockService) + .useValue(miniBlockServiceMock) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe("GET /miniblocks", () => { + it('should return an array of miniblocks', async () => { + const mockMiniBlocks = createMockMiniBlocksList(10); + miniBlockServiceMock.getMiniBlocks.mockResolvedValue(mockMiniBlocks); + + await request(app.getHttpServer()) + .get(`${path}`) + .expect(200) + .expect(response => { + expect(response.body.length).toBe(10); + expect(response.body).toEqual(mockMiniBlocks); + }); + }); + + it('GET /miniblocks - should paginate miniblocks', async () => { + const mockMiniBlocks = createMockMiniBlocksList(50); + const queryPagination = new QueryPagination({ from: 10, size: 5 }); + miniBlockServiceMock.getMiniBlocks.mockResolvedValue( + mockMiniBlocks.slice(queryPagination.from, queryPagination.from + queryPagination.size)); + + await request(app.getHttpServer()) + .get(`${path}?from=${queryPagination.from}&size=${queryPagination.size}`) + .expect(200) + .expect((response) => { + expect(response.body.length).toBe(queryPagination.size); + }); + }); + }); + + describe("GET /miniblocks/:miniBlockHash", () => { + it('should return miniblock details for a given hash', async () => { + const mockMiniBlock = createMockMiniBlocksList(1)[0]; + miniBlockServiceMock.getMiniBlock.mockResolvedValue(mockMiniBlock); + + await request(app.getHttpServer()) + .get(`${path}/${mockMiniBlock.miniBlockHash}`) + .expect(200) + .expect((response) => { + expect(response.body).toEqual(mockMiniBlock); + }); + }); + + it('should return 404 Not Found when miniblock is not found', async () => { + const nonExistentMiniBlockHash = '0a60659a3ab7384a097e55fa9450b31f88a10faafd6d32a1cec10c69100079bs'; + miniBlockServiceMock.getMiniBlock.mockRejectedValue(new HttpException('Miniblock not found', HttpStatus.NOT_FOUND)); + + await request(app.getHttpServer()) + .get(`${path}/${nonExistentMiniBlockHash}`) + .expect(404) + .expect((response) => { + expect(response.body.message).toEqual('Miniblock not found'); + }); + }); + }); + + afterAll(async () => { + await app.close(); + }); +}); + + +function createMockMiniBlocksList(numberOfMiniBlocks: number) { + const miniBlocks = []; + + for (let i = 0; i < numberOfMiniBlocks; i++) { + miniBlocks.push({ + miniBlockHash: generateRandomHash(), + receiverBlockHash: generateRandomHash(), + receiverShard: Math.floor(Math.random() * 3), + senderBlockHash: generateRandomHash(), + senderShard: Math.floor(Math.random() * 3), + timestamp: Math.floor(Date.now() / 1000) - Math.floor(Math.random() * 100000), + type: 'TxBlock', + }); + } + + return miniBlocks; +} + +function generateRandomHash() { + return [...Array(64)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); +} diff --git a/src/test/unit/controllers/services.mock/mini.block.service.mock.ts b/src/test/unit/controllers/services.mock/mini.block.service.mock.ts new file mode 100644 index 000000000..cbfb4328f --- /dev/null +++ b/src/test/unit/controllers/services.mock/mini.block.service.mock.ts @@ -0,0 +1,4 @@ +export const mockMiniBlockService = () => ({ + getMiniBlocks: jest.fn().mockResolvedValue([]), + getMiniBlock: jest.fn().mockResolvedValue({}), +}); From af9a8fc4988816eb2490c4b115b6695c92f15838 Mon Sep 17 00:00:00 2001 From: cfaur Date: Mon, 26 Feb 2024 17:47:58 +0200 Subject: [PATCH 29/30] add network.controller.spec.ts --- .../controllers/network.controller.spec.ts | 120 ++++++++++++++++++ .../services.mock/network.service.mock.ts | 6 + 2 files changed, 126 insertions(+) create mode 100644 src/test/unit/controllers/network.controller.spec.ts create mode 100644 src/test/unit/controllers/services.mock/network.service.mock.ts diff --git a/src/test/unit/controllers/network.controller.spec.ts b/src/test/unit/controllers/network.controller.spec.ts new file mode 100644 index 000000000..2665e4e15 --- /dev/null +++ b/src/test/unit/controllers/network.controller.spec.ts @@ -0,0 +1,120 @@ +import { INestApplication } from "@nestjs/common"; +import { Test } from "@nestjs/testing"; +import { NetworkController } from "src/endpoints/network/network.controller"; +import { NetworkModule } from "src/endpoints/network/network.module"; +import { NetworkService } from "src/endpoints/network/network.service"; +import { mockNetworkService } from "./services.mock/network.service.mock"; +import { NetworkConstants } from "src/endpoints/network/entities/constants"; +import request = require('supertest'); +import { Economics } from "src/endpoints/network/entities/economics"; +import { Stats } from "src/endpoints/network/entities/stats"; +import { About } from "src/endpoints/network/entities/about"; + +describe("NetworkController", () => { + let app: INestApplication; + const networkServiceMocks = mockNetworkService(); + + beforeAll(async () => { + jest.resetAllMocks(); + const moduleFixture = await Test.createTestingModule({ + controllers: [NetworkController], + imports: [NetworkModule], + }) + .overrideProvider(NetworkService) + .useValue(networkServiceMocks) + .compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + describe("GET /network", () => { + it('should return network constants details', async () => { + const mockConstants: NetworkConstants = { + chainId: "1", + gasPerDataByte: 1500, + minGasLimit: 50000, + minGasPrice: 1000000000, + minTransactionVersion: 1, + }; + networkServiceMocks.getConstants.mockResolvedValue(mockConstants); + + await request(app.getHttpServer()) + .get('/constants') + .expect(200) + .expect(response => { + expect(response.body).toMatchObject(mockConstants); + }); + }); + + it('should return network economics details', async () => { + const mockEconomics: Economics = { + totalSupply: 26625892, + circulatingSupply: 26620740, + staked: 17516922, + price: 58.84, + marketCap: 1566364342, + apr: 0.076523, + topUpApr: 0.052561, + baseApr: 0.104972, + tokenMarketCap: 552829990, + minimumAuctionTopUp: undefined, + }; + networkServiceMocks.getEconomics.mockResolvedValue(mockEconomics); + + await request(app.getHttpServer()) + .get('/economics') + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockEconomics); + }); + }); + + it('should return network stats details', async () => { + const mockStats: Stats = { + shards: 3, + blocks: 75177896, + accounts: 2837831, + transactions: 388115542, + scResults: 292978375, + refreshRate: 6000, + epoch: 1305, + roundsPassed: 14136, + roundsPerEpoch: 14400, + }; + networkServiceMocks.getStats.mockResolvedValue(mockStats); + + await request(app.getHttpServer()) + .get('/stats') + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockStats); + }); + }); + + it('should return network about details', async () => { + const mockAbout: About = { + appVersion: "93a9abd0033050e46242836c6cf12e7b396e294c", + pluginsVersion: "ad95f80e544b10accf56d8ae5deb0299d6a6a5de", + network: "mainnet", + cluster: "mainnet-aws-fra", + version: "v1.3.0-hotfix2-next", + scamEngineVersion: "1.0.0", + features: { + updateCollectionExtraDetails: true, + marketplace: true, + exchange: true, + dataApi: true, + }, + }; + networkServiceMocks.getAbout.mockResolvedValue(mockAbout); + + await request(app.getHttpServer()) + .get('/about') + .expect(200) + .expect(response => { + expect(response.body).toEqual(mockAbout); + }); + }); + }); +}); diff --git a/src/test/unit/controllers/services.mock/network.service.mock.ts b/src/test/unit/controllers/services.mock/network.service.mock.ts new file mode 100644 index 000000000..7aaddc335 --- /dev/null +++ b/src/test/unit/controllers/services.mock/network.service.mock.ts @@ -0,0 +1,6 @@ +export const mockNetworkService = () => ({ + getConstants: jest.fn().mockResolvedValue({}), + getEconomics: jest.fn().mockResolvedValue({}), + getStats: jest.fn().mockResolvedValue({}), + getAbout: jest.fn().mockResolvedValue({}), +}); From c1d290a50cd3006405505e24e34bbeca06a57a9d Mon Sep 17 00:00:00 2001 From: cfaur Date: Wed, 28 Feb 2024 22:27:06 +0200 Subject: [PATCH 30/30] fix after review --- .../controllers/accounts.controller.spec.ts | 28 +++++++++++-------- .../controllers/blocks.controller.spec.ts | 13 +++++---- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/test/unit/controllers/accounts.controller.spec.ts b/src/test/unit/controllers/accounts.controller.spec.ts index bd132dbbe..0ba47fec3 100644 --- a/src/test/unit/controllers/accounts.controller.spec.ts +++ b/src/test/unit/controllers/accounts.controller.spec.ts @@ -103,22 +103,24 @@ describe('AccountController', () => { }); }); - it('should sort accounts by balance when "sort" query parameter is set to "balance"', async () => { + it('should sort accounts by balance when sort query parameter is set to balance', async () => { const sortedAccountsList = createMockAccountsList(10).sort((a, b) => parseInt(a.balance) - parseInt(b.balance)); accountServiceMocks.getAccounts.mockReturnValue(sortedAccountsList); const sort = 'balance'; await request(app.getHttpServer()) - .get(`${path}?sort=${sort}`) - .expect(200) - .expect(response => { - const isSortedByBalance = response.body.every( - (account: { balance: string; }, i: number, arr: { balance: string; }[]) => i === 0 || parseInt(arr[i - 1].balance) <= parseInt(account.balance)); - expect(isSortedByBalance).toBeTruthy(); - }); + .get(`/accounts?sort=${sort}`) + .expect(200); + + expect(accountServiceMocks.getAccounts).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + sort: 'balance', + }) + ); }); - it('should return only smart contracts when "isSmartContract" query parameter is set to true', async () => { + it('should return only smart contracts when isSmartContract query parameter is set to true', async () => { const smartContractsList = createMockAccountsList(5, undefined, true); accountServiceMocks.getAccounts.mockReturnValue(smartContractsList); await request(app.getHttpServer()) @@ -130,7 +132,7 @@ describe('AccountController', () => { }); }); - describe("GET /accounts/count", () => { + describe('GET /accounts/count', () => { it('should return total accounts count', async () => { accountServiceMocks.getAccountsCount.mockReturnValue(100); @@ -193,7 +195,7 @@ describe('AccountController', () => { }); }); - describe("GET /accounts/c", () => { + describe('GET /accounts/c', () => { it('should return total alternative accounts count', async () => { accountServiceMocks.getAccountsCount.mockReturnValue(100); @@ -206,7 +208,7 @@ describe('AccountController', () => { }); }); - describe("GET /accounts/:address", () => { + describe('GET /accounts/:address', () => { const mockAccount = { address: 'erd1vtlpm6sxxvmgt43ldsrpswjrfcsudmradylpxn9jkp66ra3rkz4qruzvfw', balance: '707809', @@ -258,6 +260,8 @@ describe('AccountController', () => { .expect(response => { expect(response.body).toEqual(mockAccountWithGuardianInfo); expect(response.body.isGuarded).toStrictEqual(true); + expect(accountServiceMocks.getAccount).toHaveBeenCalledWith( + expect.any(String), undefined, true); }); }); diff --git a/src/test/unit/controllers/blocks.controller.spec.ts b/src/test/unit/controllers/blocks.controller.spec.ts index 9469551ad..67cf0a281 100644 --- a/src/test/unit/controllers/blocks.controller.spec.ts +++ b/src/test/unit/controllers/blocks.controller.spec.ts @@ -42,15 +42,18 @@ describe("BlockController", () => { it('should filter blocks by shard', async () => { const shard = 1; - const filteredBlocksList = createMockBlocksList(5).map(block => ({ ...block, shard })); + const filteredBlocksList = createMockBlocksList(5); blockServiceMock.getBlocks.mockResolvedValue(filteredBlocksList); await request(app.getHttpServer()) .get(`${path}?shard=${shard}`) - .expect(200) - .expect(response => { - expect(response.body.every((block: { shard: number; }) => block.shard === shard)).toBeTruthy(); - }); + .expect(200); + + expect(blockServiceMock.getBlocks).toHaveBeenCalledWith( + expect.objectContaining({ shard: 1 }), + expect.objectContaining({ from: 0, size: 25 }), + undefined + ); }); it('should paginate the blocks list', async () => {