git.delta.rocks / unique-network / refs/commits / 876e077a7bb7

difftreelog

Some template code for integration testing + createCollection tests

Greg Zaitsev2020-12-18parent: #c5b165d.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
before · Cargo.lock
694 packageslockfile v1
modifiednode/src/chain_spec.rsdiffbeforeafterboth
--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -180,8 +180,8 @@
             fungible_item_id: vec![],
             refungible_item_id: vec![],
             chain_limit: ChainLimits {
-                collection_numbers_limit: 10,
-                account_token_ownership_limit: 10,
+                collection_numbers_limit: 100000,
+                account_token_ownership_limit: 1000000,
                 collections_admins_limit: 5,
                 custom_data_limit: 2048,
                 nft_sponsor_transfer_timeout: 15,
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -1,90 +1,67 @@
-import { assert } from 'chai';
-import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
-import waitNewBlocks from './substrate/wait-new-blocks';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from "./substrate/substrate-api";
+import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
 
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
 describe('integration test: ext. createCollection():', () => {
   it('Create new NFT collection', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', '1', '1', 'NFT')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount === AcollectionCount) {assert.fail('Error: NFT collection NOT created.'); }
-    });
+    await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+  });
+  it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
+    await createCollectionExpectSuccess(
+      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCD',
+      '1', '1', 'NFT');
   });
+  it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
+    await createCollectionExpectSuccess(
+      'A', 
+      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdef',
+      '1', 'NFT');
+  });
+  it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
+    await createCollectionExpectSuccess(
+      '1', 
+      '1',
+      'ABCDEFGHIJABCDEF', 'NFT');
+  });
   it('Create new Fungible collection', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', '1', '1', 'Fungible')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount === AcollectionCount) {assert.fail('Error: Fungible collection NOT created.'); }    });
+    await createCollectionExpectSuccess('1', '1', '1', 'Fungible');
   });
   it('Create new ReFungible collection', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', '1', '1', 'ReFungible')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount === AcollectionCount) {assert.fail('Error: ReFungible collection NOT created.'); }    });
+    await createCollectionExpectSuccess('1', '1', '1', 'ReFungible');
   });
 });
 
 describe('(!negative test!) integration test: ext. createCollection():', () => {
   it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
     await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', '1', '1', 'BadMode')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount > AcollectionCount) {assert.fail('Error: Incorrect collection created.'); }
-    });
-  });
-  it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', '1', '0x999', 'NFT')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount > AcollectionCount) {assert.fail('Incorrect data (token_prefix) created.'); }
+      const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+
+      const badTransaction = async function () { 
+        await createCollectionExpectSuccess('1', '1', '1', 'BadMode');
+      };
+      expect(badTransaction()).to.be.rejected;
+
+      const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+      expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
     });
   });
   it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('BadName', '1', '1', 'NFT')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount > AcollectionCount) {assert.fail('Incorrect data (collection_name) created.'); }    });
+    await createCollectionExpectFailure(
+      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDE', 
+      '1', '1', 'NFT');
   });
   it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
-    await usingApi(async (api) => {
-      const alicePrivateKey = privateKey('//Alice');
-      const AcollectionCount = await api.query.nft.collectionCount();
-      await api.tx.nft
-            .createCollection('1', 'BadDesk', '1', 'NFT')
-            .signAndSend(alicePrivateKey);
-      await waitNewBlocks(api);
-      const BcollectionCount = await api.query.nft.collectionCount();
-      if (BcollectionCount > AcollectionCount) {assert.fail('Incorrect data (collection_desc) created.'); }    });
+    await createCollectionExpectFailure('1',
+      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdefg',
+      '1', 'NFT');
+  });
+  it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
+    await createCollectionExpectFailure('1', '1', 
+    'ABCDEFGHIJABCDEFG',
+    'NFT');
   });
 });
addedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/createMultipleItems.test.ts
@@ -0,0 +1,64 @@
+import { assert } from 'chai';
+import { alicesPublicKey } from './accounts';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import waitNewBlocks from './substrate/wait-new-blocks';
+
+const idCollection = 12;
+
+describe('integration test: ext. createMultipleItems():', () => {
+  it('Create two NFT tokens in active NFT collection', async () => {
+    await usingApi(async (api) => {
+      const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (before): ${AitemListIndex}`);
+      const args = ['NFT', 'NFT'];
+      const alicePrivateKey = privateKey('//Alice');
+      const createMultipleItems = await api.tx.nft
+      .createMultipleItems(idCollection, alicesPublicKey, args)
+      .signAndSend(alicePrivateKey);
+      // tslint:disable-next-line: no-unused-expression
+      assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
+      console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
+      await waitNewBlocks(api);
+      const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (after): ${BitemListIndex}`);
+      if (BitemListIndex === AitemListIndex) { assert.fail('Corret token not added in collection!'); }
+    });
+  });
+  it('(!negative test!) Create two Fungible tokens in active NFT collection', async () => {
+    await usingApi(async (api) => {
+      const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (before): ${AitemListIndex}`);
+      const args = ['Fungible', 'Fungible'];
+      const alicePrivateKey = privateKey('//Alice');
+      const createMultipleItems = await api.tx.nft
+      .createMultipleItems(idCollection, alicesPublicKey, args)
+      .signAndSend(alicePrivateKey);
+      // tslint:disable-next-line: no-unused-expression
+      assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
+      console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
+      await waitNewBlocks(api);
+      const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (after): ${BitemListIndex}`);
+      if (BitemListIndex > AitemListIndex) { assert.fail('Incorrect token added in collection!'); }
+    });
+  });
+  it('(!negative test!) Create two ReFungible tokens in active NFT collection', async () => {
+    await usingApi(async (api) => {
+      const AitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (before): ${AitemListIndex}`);
+      const args = ['ReFungible', 'ReFungible'];
+      const alicePrivateKey = privateKey('//Alice');
+      const createMultipleItems = await api.tx.nft
+      .createMultipleItems(idCollection, alicesPublicKey, args)
+      .signAndSend(alicePrivateKey);
+      // tslint:disable-next-line: no-unused-expression
+      assert.exists(createMultipleItems, 'createMultipleItems is neither `null` or `undefined`');
+      console.log(`Ext. createMultipleItems submitted with hash: ${createMultipleItems}`);
+      await waitNewBlocks(api);
+      const BitemListIndex = await api.query.nft.itemListIndex(idCollection);
+      console.log(`itemListIndex count (after): ${BitemListIndex}`);
+      if (BitemListIndex > AitemListIndex) { assert.fail('Incorrect token added in collection!'); }
+    });
+  });
+});
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -1,7 +1,10 @@
 import { WsProvider, ApiPromise } from "@polkadot/api";
+import type { AccountId, Address, ApplyExtrinsicResult, DispatchError, DispatchInfo, EventRecord, Extrinsic, ExtrinsicStatus, Hash, RuntimeDispatchInfo } from '@polkadot/types/interfaces';
+import { IKeyringPair } from "@polkadot/types/types";
+
 import config from "../config";
 import promisifySubstrate from "./promisify-substrate";
-import { ApiOptions } from "@polkadot/api/types";
+import { ApiOptions, SubmittableExtrinsic, ApiTypes } from "@polkadot/api/types";
 import rtt from "../../../runtime_types.json";
 
 function defaultApiOptions(): ApiOptions {
@@ -23,4 +26,28 @@
   } finally {
     await api.disconnect();
   }
-}
\ No newline at end of file
+}
+
+export function submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
+  return new Promise(async function(resolve, reject) {
+    try {
+      await transaction.signAndSend(sender, ({ events = [], status }) => {
+        if (status.isReady) {
+          // nothing to do
+          // console.log(`Current tx status is Ready`);
+        } else if (status.isBroadcast) {
+          // nothing to do
+          // console.log(`Current tx status is Broadcast`);
+        } else if (status.isInBlock || status.isFinalized) {
+          resolve(events);
+        } else {
+          console.log(`Something went wrong with transaction. Status: ${status}`);
+          reject("Transaction failed");
+        }
+      });
+    } catch (e) {
+      console.log("Error: ", e);
+      reject(e);
+    }
+  });
+}
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -1,7 +1,5 @@
 import { expect } from "chai";
-import usingApi from "./substrate/substrate-api";
-import promisifySubstrate from "./substrate/promisify-substrate";
-import waitNewBlocks from "./substrate/wait-new-blocks";
+import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
 import { alicesPublicKey, bobsPublicKey } from "./accounts";
 import privateKey from "./substrate/privateKey";
 import getBalance from "./substrate/get-balance";
@@ -14,11 +12,8 @@
       const alicePrivateKey = privateKey('//Alice');
       
       const transfer = api.tx.balances.transfer(bobsPublicKey, 1n);
-      
-      await promisifySubstrate(api, () => transfer.signAndSend(alicePrivateKey))();
+      const result = await submitTransactionAsync(alicePrivateKey, transfer);
 
-      await waitNewBlocks(api);
-  
       const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
 
       expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
addedtests/src/util/helpers.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/util/helpers.ts
@@ -0,0 +1,83 @@
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import type { EventRecord } from '@polkadot/types/interfaces';
+import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";
+import privateKey from '../substrate/privateKey';
+import { alicesPublicKey } from "../accounts";
+import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+type CreateCollectionResult = {
+  success: boolean,
+  collectionId: number
+};
+
+function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
+  let success = false;
+  let collectionId: number = 0;
+  events.forEach(({ phase, event: { data, method, section } }) => {
+    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);
+    if (method == 'ExtrinsicSuccess') {
+      success = true;
+    } else if ((section == 'nft') && (method == 'Created')) {
+      collectionId = parseInt(data[0].toString());
+    }
+  });
+  let result: CreateCollectionResult = {
+    success,
+    collectionId
+  }
+  return result;
+}
+
+export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string) {
+  await usingApi(async (api) => {
+    // Get number of collections before the transaction
+    const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+
+    // Run the CreateCollection transaction
+    const alicePrivateKey = privateKey('//Alice');
+    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);
+    const events = await submitTransactionAsync(alicePrivateKey, tx);
+    const result = getCreateCollectionResult(events);
+
+    // Get number of collections after the transaction
+    const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+
+    // Get the collection 
+    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();
+
+    // What to expect
+    expect(result.success).to.be.true;
+    expect(result.collectionId).to.be.equal(BcollectionCount);
+    expect(collection).to.be.not.null;
+    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');
+    expect(collection.Owner).to.be.equal(alicesPublicKey);
+    expect(utf16ToStr(collection.Name)).to.be.equal(name);
+    expect(utf16ToStr(collection.Description)).to.be.equal(description);
+    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);
+  });
+}
+  
+export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {
+  await usingApi(async (api) => {
+    // Get number of collections before the transaction
+    const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+
+    // Run the CreateCollection transaction
+    const alicePrivateKey = privateKey('//Alice');
+    const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);
+    const events = await submitTransactionAsync(alicePrivateKey, tx);
+    const result = getCreateCollectionResult(events);
+
+    // Get number of collections after the transaction
+    const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
+
+    // What to expect
+    expect(result.success).to.be.false;
+    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');
+  });
+}
+  
\ No newline at end of file
addedtests/src/util/util.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/util/util.ts
@@ -0,0 +1,30 @@
+export function strToUTF16(str: string): any {
+  let buf: number[] = [];
+  for (let i=0, strLen=str.length; i < strLen; i++) {
+    buf.push(str.charCodeAt(i));
+  }
+  return buf;
+}
+
+export function utf16ToStr(buf: number[]): string {
+  let str: string = "";
+  for (let i=0, strLen=buf.length; i < strLen; i++) {
+    if (buf[i] != 0) str += String.fromCharCode(buf[i]);
+    else break;
+  }
+  return str;
+}
+
+export function hexToStr(buf: string): string {
+  let str: string = "";
+  let hexStart = buf.indexOf("0x");
+  if (hexStart < 0) hexStart = 0;
+  else hexStart = 2;  
+  for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
+    let ch = buf[i] + buf[i+1];
+    let num = parseInt(ch, 16);
+    if (num != 0) str += String.fromCharCode(num);
+    else break;
+  }
+  return str;
+}