Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change test setup to use account helper if available #285

Merged
merged 11 commits into from
Jun 25, 2020
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ node_js: 10
env:
- NODE_ENV=ci
- NODE_ENV=ci-betanet
# - NODE_ENV=devnet
- NODE_ENV=betanet
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure whether this is a good idea. If betanet is down, near-api-js development would be blocked.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree with Bowen here, I think it's too early have to have CI check betanet. In time, perhaps

cache: yarn
script:
- yarn lint
Expand Down
5 changes: 1 addition & 4 deletions test/account.access_key.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const BN = require('bn.js');
const nearApi = require('../lib/index');
const testUtils = require('./test-utils');

let nearjs;
let testAccount;
let workingAccount;
let contractId;
let contract;
Expand All @@ -12,12 +10,11 @@ jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;

beforeAll(async () => {
nearjs = await testUtils.setUpTestConnection();
testAccount = await testUtils.createAccount(await nearjs.account(testUtils.testAccountName), { amount: testUtils.INITIAL_BALANCE.mul(new BN(100)) });
});

beforeEach(async () => {
contractId = testUtils.generateUniqueString('test');
workingAccount = await testUtils.createAccount(testAccount);
workingAccount = await testUtils.createAccount(nearjs);
contract = await testUtils.deployContract(workingAccount, contractId);
});

Expand Down
28 changes: 16 additions & 12 deletions test/account.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@ let nearjs;
let workingAccount;
let startFromVersion;

const HELLO_WASM_PATH = process.env.HELLO_WASM_PATH || 'node_modules/near-hello/dist/main.wasm';
const { HELLO_WASM_PATH, HELLO_WASM_BALANCE } = testUtils;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;

beforeAll(async () => {
nearjs = await testUtils.setUpTestConnection();
workingAccount = await testUtils.createAccount(await nearjs.account(testUtils.testAccountName), { amount: testUtils.INITIAL_BALANCE.mul(new BN(100)) });
workingAccount = await testUtils.createAccount(nearjs);
let nodeStatus = await nearjs.connection.provider.status();
startFromVersion = (version) => semver.gte(nodeStatus.version.version, version);
});

afterAll(async () => {
await testUtils.deleteAccount(workingAccount);
await workingAccount.deleteAccount(workingAccount.accountId);
});

test('view pre-defined account works and returns correct name', async () => {
Expand All @@ -32,24 +32,28 @@ test('view pre-defined account works and returns correct name', async () => {
test('create account and then view account returns the created account', async () => {
const newAccountName = testUtils.generateUniqueString('test');
const newAccountPublicKey = '9AhWenZ3JddamBoyMqnTbp7yVbRuvqAv3zwfrWgfVRJE';
await workingAccount.createAccount(newAccountName, newAccountPublicKey, testUtils.INITIAL_BALANCE);
const { amount } = await workingAccount.state();
const newAmount = new BN(amount).div(new BN(10));
await workingAccount.createAccount(newAccountName, newAccountPublicKey, newAmount);
const newAccount = new nearApi.Account(nearjs.connection, newAccountName);
const state = await newAccount.state();
expect(state.amount).toEqual(testUtils.INITIAL_BALANCE.toString());
expect(state.amount).toEqual(newAmount.toString());
});

test('send money', async() => {
const sender = await testUtils.createAccount(workingAccount);
const receiver = await testUtils.createAccount(workingAccount);
const sender = await testUtils.createAccount(nearjs);
const receiver = await testUtils.createAccount(nearjs);
const { amount: receiverAmount } = await receiver.state();
await sender.sendMoney(receiver.accountId, new BN(10000));
await receiver.fetchState();
// TODO: Why `.state()` is not fetching state?
const state = await receiver.state();
expect(state.amount).toEqual(testUtils.INITIAL_BALANCE.add(new BN(10000)).toString());
expect(state.amount).toEqual(new BN(receiverAmount).add(new BN(10000)).toString());
});

test('delete account', async() => {
const sender = await testUtils.createAccount(workingAccount);
const receiver = await testUtils.createAccount(workingAccount);
const sender = await testUtils.createAccount(nearjs);
const receiver = await testUtils.createAccount(nearjs);
await sender.deleteAccount(receiver.accountId);
const reloaded = new nearApi.Account(sender.connection, sender);
await expect(reloaded.state()).rejects.toThrow();
Expand All @@ -61,7 +65,7 @@ describe('errors', () => {

beforeEach(async () => {
oldLog = console.log;
logs =[];
logs = [];
console.log = function () {
logs.push(Array.from(arguments).join(' '));
};
Expand Down Expand Up @@ -92,7 +96,7 @@ describe('with deploy contract', () => {
beforeAll(async () => {
const newPublicKey = await nearjs.connection.signer.createKey(contractId, testUtils.networkId);
const data = [...fs.readFileSync(HELLO_WASM_PATH)];
await workingAccount.createAndDeployContract(contractId, newPublicKey, data, testUtils.INITIAL_BALANCE);
await workingAccount.createAndDeployContract(contractId, newPublicKey, data, HELLO_WASM_BALANCE);
contract = new nearApi.Contract(workingAccount, contractId, {
viewMethods: ['hello', 'getValue', 'returnHiWithLogs'],
changeMethods: ['setValue', 'generateLogs', 'triggerAssert', 'testSetRemove', 'crossContract']
Expand Down
2 changes: 1 addition & 1 deletion test/promise.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const CONTRACT_CALL_GAS = new BN(300000000000000);

beforeAll(async () => {
nearjs = await testUtils.setUpTestConnection();
workingAccount = await testUtils.createAccount(await nearjs.account(testUtils.testAccountName), { amount: testUtils.INITIAL_BALANCE.mul(new BN(100)) });
workingAccount = await testUtils.createAccount(nearjs);
});

describe('with promises', () => {
Expand Down
17 changes: 10 additions & 7 deletions test/providers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const nearApi = require('../lib/index');
const testUtils = require('./test-utils');
const BN = require('bn.js');

jest.setTimeout(20000);

const withProvider = (fn) => {
const config = Object.assign(require('./config')(process.env.NODE_ENV || 'test'));
const provider = new nearApi.providers.JsonRpcProvider(config.nodeUrl);
Expand Down Expand Up @@ -48,11 +50,13 @@ test('json rpc fetch chunk info', withProvider(async (provider) => {

test('json rpc fetch validators info', withProvider(async (provider) => {
let validators = await provider.validators(null);
expect(validators.current_validators.length).toEqual(1);
expect(validators.current_validators.length).toBeGreaterThanOrEqual(1);
}));

test('json rpc query account', withProvider(async (provider) => {
let response = await provider.query('account/test.near', '');
const near = await testUtils.setUpTestConnection();
const account = await testUtils.createAccount(near);
let response = await provider.query(`account/${account.accountId}`, '');
expect(response.code_hash).toEqual('11111111111111111111111111111111');
}));

Expand Down Expand Up @@ -81,11 +85,10 @@ test('final tx result with null', async() => {
});

test('json rpc light client proof', async() => {
jest.setTimeout(30000);
const nearjs = await testUtils.setUpTestConnection();
const workingAccount = await testUtils.createAccount(await nearjs.account(testUtils.testAccountName), { amount: testUtils.INITIAL_BALANCE.mul(new BN(100)) });
const executionOutcome = await workingAccount.sendMoney(testUtils.testAccountName, new BN(10000));
const provider = nearjs.connection.provider;
const near = await testUtils.setUpTestConnection();
const workingAccount = await testUtils.createAccount(near);
const executionOutcome = await workingAccount.sendMoney(workingAccount.accountId, new BN(10000));
const provider = near.connection.provider;

async function waitForStatusMatching(isMatching) {
const MAX_ATTEMPTS = 10;
Expand Down
41 changes: 24 additions & 17 deletions test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,41 @@ const BN = require('bn.js');
const nearApi = require('../lib/index');

const networkId = 'unittest';
const testAccountName = 'test.near';

const INITIAL_BALANCE = new BN('100000000000000000000000000');
const HELLO_WASM_PATH = process.env.HELLO_WASM_PATH || 'node_modules/near-hello/dist/main.wasm';
const HELLO_WASM_BALANCE = new BN('10000000000000000000000000');

async function setUpTestConnection() {
const keyStore = new nearApi.keyStores.InMemoryKeyStore();
await keyStore.setKey(networkId, testAccountName, nearApi.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw'));
const config = Object.assign(require('./config')(process.env.NODE_ENV || 'test'), {
networkId: networkId,
deps: { keyStore },
});

if (config.masterAccount) {
await keyStore.setKey(networkId, config.masterAccount, nearApi.utils.KeyPair.fromString('ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw'));
}

return nearApi.connect(config);
}

// Generate some unique string with a given prefix using the alice nonce.
function generateUniqueString(prefix) {
return prefix + Date.now() + Math.round(Math.random() * 1000);
return `${prefix}-${Date.now()}-${Math.round(Math.random() * 1000000)}`;
}

async function createAccount(masterAccount, options = { amount: INITIAL_BALANCE, trials: 5 }) {
await masterAccount.fetchState();
async function createAccount(near) {
const newAccountName = generateUniqueString('test');
const newPublicKey = await masterAccount.connection.signer.createKey(newAccountName, networkId);
await masterAccount.createAccount(newAccountName, newPublicKey, options.amount);
return new nearApi.Account(masterAccount.connection, newAccountName);
}

async function deleteAccount(testAccount) {
await testAccount.deleteAccount(testAccountName);
const newPublicKey = await near.connection.signer.createKey(newAccountName, networkId);
await near.createAccount(newAccountName, newPublicKey);
const account = new nearApi.Account(near.connection, newAccountName);
return account;
}

async function deployContract(workingAccount, contractId, options = { amount: INITIAL_BALANCE.div(new BN(10)) }) {
async function deployContract(workingAccount, contractId) {
const newPublicKey = await workingAccount.connection.signer.createKey(contractId, networkId);
const data = [...(await fs.readFile(HELLO_WASM_PATH))];
await workingAccount.createAndDeployContract(contractId, newPublicKey, data, options.amount);
await workingAccount.createAndDeployContract(contractId, newPublicKey, data, HELLO_WASM_BALANCE);
return new nearApi.Contract(workingAccount, contractId, {
viewMethods: ['getValue', 'getLastResult'],
changeMethods: ['setValue', 'callPromise']
Expand All @@ -61,5 +59,14 @@ async function ensureDir(dirpath) {
}
}

module.exports = { setUpTestConnection, networkId, testAccountName, INITIAL_BALANCE,
generateUniqueString, createAccount, deleteAccount, deployContract, sleep, ensureDir };
module.exports = {
setUpTestConnection,
networkId,
generateUniqueString,
createAccount,
deployContract,
sleep,
ensureDir,
HELLO_WASM_PATH,
HELLO_WASM_BALANCE,
};