difftreelog
setSchema test scenarios
in: master
4 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -17,7 +17,10 @@
},
"scripts": {
"test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",
- "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts"
+ "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",
+ "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
+ "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
+ "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts"
},
"author": "",
"license": "Apache 2.0",
tests/src/setSchemaVersion.test.tsdiffbeforeafterboth--- a/tests/src/setSchemaVersion.test.ts
+++ b/tests/src/setSchemaVersion.test.ts
@@ -1,47 +1,142 @@
-import { BigNumber } from 'bignumber.js';
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise, Keyring } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import BN from 'bn.js';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import promisifySubstrate from './substrate/promisify-substrate';
import usingApi, { submitTransactionAsync } from './substrate/substrate-api';
+import { ICollectionInterface } from './types';
+import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, getCreateItemResult } from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
-describe('setSchemaVersion positive', () => {
- it('execute setSchemaVersion with image url and unique json ', async () => {
- await usingApi(async api => {
+let alice: IKeyringPair;
+let collectionIdForTesting: number;
+
+/*
+1. We create collection.
+2. Save just created collection id.
+3. Use this id for setSchemaVersion.
+*/
+
+async function getDetailedCollectionInfo(api: ApiPromise, collectionId: number)
+ : Promise<ICollectionInterface | null> {
+ return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;
+}
+async function getCollectionCount(api: ApiPromise): Promise<number> {
+ // set global object - collectionsCount
+ return (await api.query.nft.collectionCount() as unknown as BN).toNumber();
+}
+
+function utf8Decoder(name: [Uint8Array]) {
+ const collectionNameArr = Array.prototype.slice.call(name);
+ return String.fromCharCode(...collectionNameArr);
+}
+
+describe('hooks', () => {
+ before(async () => {
+ await usingApi(async (api) => {
+ const keyring = new Keyring({ type: 'sr25519' });
+ alice = keyring.addFromUri('//Alice');
});
});
+ it('choose or create collection for testing', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const newCollectionId = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+ console.log('newCollectionId', newCollectionId);
+ collectionIdForTesting = newCollectionId;
+ });
+ });
+});
- it('validate schema version with just entered data', async () => {
- await usingApi(async api => {
+describe('setSchemaVersion positive', () => {
+ let tx;
+ before(async () => {
+ await usingApi(async (api) => {
+ const keyring = new Keyring({ type: 'sr25519' });
+ alice = keyring.addFromUri('//Alice');
+ });
+ });
+ it('execute setSchemaVersion with image url and unique ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Unique');
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemResult(events);
+ const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ // tslint:disable-next-line:no-unused-expression
+ expect(collectionInfo).to.be.exist;
+ // tslint:disable-next-line:no-unused-expression
+ expect(collectionInfo ? collectionInfo.SchemaVersion.toString() : '').to.be.equal('Unique');
+ });
+ });
+ it('validate schema version with just entered data', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'ImageURL');
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemResult(events);
+ const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ // tslint:disable-next-line:no-unused-expression
+ expect(collectionInfo).to.be.exist;
+ // tslint:disable-next-line:no-unused-expression
+ expect(collectionInfo ? collectionInfo.SchemaVersion.toString() : '').to.be.equal('ImageURL');
});
});
});
describe('setSchemaVersion negative', () => {
- it('execute setSchemaVersion for not exists collection', async () => {
- await usingApi(async api => {
-
+ let tx;
+ before(async () => {
+ await usingApi(async (api) => {
+ const keyring = new Keyring({ type: 'sr25519' });
+ alice = keyring.addFromUri('//Alice');
});
});
-
- it('execute setSchemaVersion for deleted collection', async () => {
- await usingApi(async api => {
-
+ it('execute setSchemaVersion for not exists collection', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionCount = await getCollectionCount(api);
+ const nonExistedCollectionId = collectionCount + 1;
+ tx = api.tx.nft.setSchemaVersion(nonExistedCollectionId, 'ImageURL');
+ try {
+ await submitTransactionAsync(alice, tx);
+ } catch (e) {
+ // tslint:disable-next-line:no-unused-expression
+ expect(e).to.be.exist;
+ }
});
});
- it('execute setSchemaVersion with not correct image url', async () => {
- await usingApi(async api => {
-
+ it('execute setSchemaVersion with not correct schema version', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ try {
+ tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Test');
+ await submitTransactionAsync(alice, tx);
+ } catch (e) {
+ // tslint:disable-next-line:no-unused-expression
+ expect(e).to.be.exist;
+ }
});
});
- it('execute setSchemaVersion with not correct unique', async () => {
- await usingApi(async api => {
-
+ it('execute setSchemaVersion for deleted collection', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionCount = await getCollectionCount(api);
+ await destroyCollectionExpectSuccess(collectionCount);
+ try {
+ tx = api.tx.nft.setSchemaVersion(collectionCount, 'ImageURL');
+ await submitTransactionAsync(alice, tx);
+ } catch (e) {
+ // tslint:disable-next-line:no-unused-expression
+ expect(e).to.be.exist;
+ }
});
});
});
tests/src/types.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/types.ts
@@ -0,0 +1,23 @@
+import BN from 'bn.js';
+
+export interface ICollectionInterface {
+ Access: string;
+ id: number;
+ DecimalPoints: BN;
+ // constOnChainSchema
+ Description: [BN, BN]; // utf16
+ isReFungible: boolean;
+ MintMode: boolean;
+ Mode: {
+ Nft: null;
+ };
+ Name: [BN, BN]; // utf16
+ OffchainSchema: [Uint8Array];
+ SchemaVersion: string;
+ Owner: [Uint8Array];
+ // prefix
+ // sponsor
+ // tokenPrefix
+ // unconfirmedSponsor
+ // variableOnChainSchema
+}
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122type GenericResult = {23 success: boolean,24};2526type CreateCollectionResult = {27 success: boolean,28 collectionId: number29};3031type CreateItemResult = {32 success: boolean,33 collectionId: number,34 itemId: number35};3637export function getGenericResult(events: EventRecord[]): GenericResult {38 let result: GenericResult = {39 success: false40 }41 events.forEach(({ phase, event: { data, method, section } }) => {42 // console.log(` ${phase}: ${section}.${method}:: ${data}`);43 if (method == 'ExtrinsicSuccess') {44 result.success = true;45 }46 });47 return result;48}4950function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {51 let success = false;52 let collectionId: number = 0;53 events.forEach(({ phase, event: { data, method, section } }) => {54 // console.log(` ${phase}: ${section}.${method}:: ${data}`);55 if (method == 'ExtrinsicSuccess') {56 success = true;57 } else if ((section == 'nft') && (method == 'Created')) {58 collectionId = parseInt(data[0].toString());59 }60 });61 let result: CreateCollectionResult = {62 success,63 collectionId64 }65 return result;66}6768function getCreateItemResult(events: EventRecord[]): CreateItemResult {69 let success = false;70 let collectionId: number = 0;71 let itemId: number = 0;72 events.forEach(({ phase, event: { data, method, section } }) => {73 // console.log(` ${phase}: ${section}.${method}:: ${data}`);74 if (method == 'ExtrinsicSuccess') {75 success = true;76 } else if ((section == 'nft') && (method == 'ItemCreated')) {77 collectionId = parseInt(data[0].toString());78 itemId = parseInt(data[1].toString());79 }80 });81 let result: CreateItemResult = {82 success,83 collectionId,84 itemId85 }86 return result;87}8889export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';90export type CreateCollectionParams = {91 mode: CollectionMode,92 name: string,93 description: string,94 tokenPrefix: string95};9697const defaultCreateCollectionParams: CreateCollectionParams = {98 name: 'name',99 description: 'description',100 mode: 'NFT',101 tokenPrefix: 'prefix'102}103104export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {105 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};106107 let collectionId: number = 0;108 await usingApi(async (api) => {109 // Get number of collections before the transaction110 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());111112 // Run the CreateCollection transaction113 const alicePrivateKey = privateKey('//Alice');114 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);115 const events = await submitTransactionAsync(alicePrivateKey, tx);116 const result = getCreateCollectionResult(events);117118 // Get number of collections after the transaction119 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());120121 // Get the collection 122 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();123124 // What to expect125 expect(result.success).to.be.true;126 expect(result.collectionId).to.be.equal(BcollectionCount);127 expect(collection).to.be.not.null;128 expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');129 expect(collection.Owner).to.be.equal(alicesPublicKey);130 expect(utf16ToStr(collection.Name)).to.be.equal(name);131 expect(utf16ToStr(collection.Description)).to.be.equal(description);132 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);133134 collectionId = result.collectionId;135 });136137 return collectionId;138}139 140export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {141 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};142143 await usingApi(async (api) => {144 // Get number of collections before the transaction145 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());146147 // Run the CreateCollection transaction148 const alicePrivateKey = privateKey('//Alice');149 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);150 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;151 const result = getCreateCollectionResult(events);152153 // Get number of collections after the transaction154 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());155156 // What to expect157 expect(result.success).to.be.false;158 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');159 });160}161 162export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {163 let bal = new BigNumber(0);164 let unused;165 do {166 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));167 const keyring = new Keyring({ type: 'sr25519' });168 unused = keyring.addFromUri(`//${randomSeed}`);169 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());170 } while (bal.toFixed() != '0');171 return unused; 172}173174function getDestroyResult(events: EventRecord[]): boolean {175 let success: boolean = false;176 events.forEach(({ phase, event: { data, method, section } }) => {177 // console.log(` ${phase}: ${section}.${method}:: ${data}`);178 if (method == 'ExtrinsicSuccess') {179 success = true;180 }181 });182 return success;183}184185export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {186 await usingApi(async (api) => {187 // Run the DestroyCollection transaction188 const alicePrivateKey = privateKey(senderSeed);189 const tx = api.tx.nft.destroyCollection(collectionId);190 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;191 });192}193194export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {195 await usingApi(async (api) => {196 // Run the DestroyCollection transaction197 const alicePrivateKey = privateKey(senderSeed);198 const tx = api.tx.nft.destroyCollection(collectionId);199 const events = await submitTransactionAsync(alicePrivateKey, tx);200 const result = getDestroyResult(events);201202 // Get the collection 203 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();204205 // What to expect206 expect(result).to.be.true;207 expect(collection).to.be.not.null;208 expect(collection.Owner).to.be.equal(nullPublicKey);209 });210}211212export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {213 await usingApi(async (api) => {214215 // Run the transaction216 const alicePrivateKey = privateKey('//Alice');217 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);218 const events = await submitTransactionAsync(alicePrivateKey, tx);219 const result = getGenericResult(events);220221 // Get the collection 222 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();223224 // What to expect225 expect(result.success).to.be.true;226 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());227 expect(collection.SponsorConfirmed).to.be.false;228 });229}230231export async function removeCollectionSponsorExpectSuccess(collectionId: number) {232 await usingApi(async (api) => {233234 // Run the transaction235 const alicePrivateKey = privateKey('//Alice');236 const tx = api.tx.nft.removeCollectionSponsor(collectionId);237 const events = await submitTransactionAsync(alicePrivateKey, tx);238 const result = getGenericResult(events);239240 // Get the collection 241 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();242243 // What to expect244 expect(result.success).to.be.true;245 expect(collection.Sponsor).to.be.equal(nullPublicKey);246 expect(collection.SponsorConfirmed).to.be.false;247 });248}249250export async function removeCollectionSponsorExpectFailure(collectionId: number) {251 await usingApi(async (api) => {252253 // Run the transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.removeCollectionSponsor(collectionId);256 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 });258}259260export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {261 await usingApi(async (api) => {262263 // Run the transaction264 const alicePrivateKey = privateKey(senderSeed);265 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);266 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;267 });268}269270export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {271 await usingApi(async (api) => {272273 // Run the transaction274 const sender = privateKey(senderSeed);275 const tx = api.tx.nft.confirmSponsorship(collectionId);276 const events = await submitTransactionAsync(sender, tx);277 const result = getGenericResult(events);278279 // Get the collection 280 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();281282 // What to expect283 expect(result.success).to.be.true;284 expect(collection.Sponsor).to.be.equal(sender.address);285 expect(collection.SponsorConfirmed).to.be.true;286 });287}288289export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {290 await usingApi(async (api) => {291292 // Run the transaction293 const sender = privateKey(senderSeed);294 const tx = api.tx.nft.confirmSponsorship(collectionId);295 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;296 });297}298299export interface CreateFungibleData extends Struct {300 readonly value: u128;301};302303export interface CreateReFungibleData extends Struct {};304export interface CreateNftData extends Struct {};305306export interface CreateItemData extends Enum {307 NFT: CreateNftData,308 Fungible: CreateFungibleData,309 ReFungible: CreateReFungibleData310};311312export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {313 let newItemId: number = 0;314 await usingApi(async (api) => {315 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());316 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON(); 317 const AItemBalance = new BigNumber(Aitem.Value);318319 if (owner === '') owner = sender.address;320321 let tx;322 if (createMode == 'Fungible') {323 let createData = {fungible: {value: 10}};324 tx = api.tx.nft.createItem(collectionId, owner, createData);325 }326 else {327 tx = api.tx.nft.createItem(collectionId, owner, createMode);328 }329 const events = await submitTransactionAsync(sender, tx);330 const result = getCreateItemResult(events);331332 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());333 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON(); 334 const BItemBalance = new BigNumber(Bitem.Value);335336 // What to expect337 expect(result.success).to.be.true;338 if (createMode == 'Fungible') {339 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);340 }341 else {342 expect(BItemCount).to.be.equal(AItemCount+1);343 }344 expect(collectionId).to.be.equal(result.collectionId);345 expect(BItemCount).to.be.equal(result.itemId);346 newItemId = result.itemId;347 });348 return newItemId;349}350351export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {352 await usingApi(async (api) => {353354 // Run the transaction355 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');356 const events = await submitTransactionAsync(sender, tx);357 const result = getGenericResult(events);358359 // Get the collection 360 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();361362 // What to expect363 expect(result.success).to.be.true;364 expect(collection.Access).to.be.equal('WhiteList');365 });366}367368export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {369 await usingApi(async (api) => {370371 // Run the transaction372 const tx = api.tx.nft.setMintPermission(collectionId, true);373 const events = await submitTransactionAsync(sender, tx);374 const result = getGenericResult(events);375376 // Get the collection 377 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();378379 // What to expect380 expect(result.success).to.be.true;381 expect(collection.MintMode).to.be.equal(true);382 });383}384385export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {386 await usingApi(async (api) => {387388 // Run the transaction389 const tx = api.tx.nft.addToWhiteList(collectionId, address);390 const events = await submitTransactionAsync(sender, tx);391 const result = getGenericResult(events);392393 // Get the collection 394 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();395396 // What to expect397 expect(result.success).to.be.true;398 expect(collection.MintMode).to.be.equal(true);399 });400}401