chai#assert TypeScript Examples

The following examples show how to use chai#assert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.test.ts    From context-mod with MIT License 7 votes vote down vote up
describe('Parsing Reddit Entity strings', function () {
    it('should recognize entity name regardless of prefix', function () {
        for(const text of ['/r/anEntity', 'r/anEntity', '/u/anEntity', 'u/anEntity']) {
            assert.equal(parseRedditEntity(text).name, 'anEntity');
        }
    })

    it('should distinguish between subreddit and user prefixes', function () {
        assert.equal(parseRedditEntity('r/mySubreddit').type, 'subreddit');
        assert.equal(parseRedditEntity('u/aUser').type, 'user');
    })

    it('should recognize user based on u_ prefix', function () {
        assert.equal(parseRedditEntity(' u_aUser ').type, 'user');
    })

    it('should handle whitespace', function () {
        assert.equal(parseRedditEntity(' /r/mySubreddit ').name, 'mySubreddit');
    })

    it('should handle dashes in the entity name', function () {
        assert.equal(parseRedditEntity(' /u/a-user ').name, 'a-user');
    })
})
Example #2
Source File: utils.spec.ts    From atorch-console with MIT License 7 votes vote down vote up
describe('Parser', () => {
  it('readPacket: Wrong block', () => {
    const packet = readPacket(Buffer.alloc(10));
    assert.isUndefined(packet);
  });
  const packets: Record<string, NewableFunction> = {
    FF55010100090400000E0000040000000000006401F40085002F00000A093C0000000039: ACMeterPacket,
    FF55010200011A0000000004D40000002000006400000000002A00590E343C000000003F: DCMeterPacket,
    FF5501030001F3000000000638000003110007000A000000122E333C000000000000004E: USBMeterPacket,
    FF55020000000046: ReplyPacket,
  };
  for (const [packet, Type] of Object.entries(packets)) {
    it(`readPacket: ${Type.name}`, () => {
      const parsed = readPacket(Buffer.from(packet, 'hex'));
      assert.instanceOf(parsed, Type);
    });
  }
});
Example #3
Source File: backing.test.ts    From persistent-merkle-tree with Apache License 2.0 6 votes vote down vote up
describe("set", () => {
  it("should return the right node", () => {
    const n = subtreeFillToDepth(new LeafNode(Buffer.alloc(32, 1)), 3);
    const n2 = new LeafNode(Buffer.alloc(32, 2));
    const backing = new Tree(n);
    backing.setNode(15n, n2, true);
    assert.deepEqual(backing.getRoot(15n), Buffer.alloc(32, 2));
  });
});
Example #4
Source File: utils.test.ts    From context-mod with MIT License 6 votes vote down vote up
describe('Non-temporal Comparison Operations', function () {
    it('should throw if no operator sign', function () {
        const shouldThrow = () => parseGenericValueComparison('just 3');
        assert.throws(shouldThrow)
    });
    it('should parse greater-than with a numeric value', function () {
        const res = parseGenericValueComparison('> 3');
        assert.equal(res.operator, '>')
        assert.equal(res.value, 3);
    });
    it('should parse greater-than-or-equal-to with a numeric value', function () {
        const res = parseGenericValueComparison('>= 3');
        assert.equal(res.operator, '>=')
        assert.equal(res.value, 3)
    })
    it('should parse less-than with a numeric value', function () {
        const res = parseGenericValueComparison('< 3');
        assert.equal(res.operator, '<')
        assert.equal(res.value, 3)
    })
    it('should parse less-than-or-equal-to with a numeric value', function () {
        const res = parseGenericValueComparison('<= 3');
        assert.equal(res.operator, '<=')
        assert.equal(res.value, 3)
    })
    it('should parse extra content', function () {
        const res = parseGenericValueComparison('<= 3 foobars');
        assert.equal(res.extra, ' foobars')

        const noExtra = parseGenericValueComparison('<= 3');
        assert.isUndefined(noExtra.extra)
    })
    it('should parse percentage', function () {
        const withPercent = parseGenericValueOrPercentComparison('<= 3%');
        assert.isTrue(withPercent.isPercent)

        const withoutPercent = parseGenericValueOrPercentComparison('<= 3');
        assert.isFalse(withoutPercent.isPercent)
    })
});
Example #5
Source File: asserts.spec.ts    From atorch-console with MIT License 6 votes vote down vote up
describe('Asserts', () => {
  it('assertMeterPacket', () => {
    const packet = Buffer.from('00000000', 'hex');
    const fn = () => {
      assertMeterPacket(packet, 0x03, 'Test Meter');
    };
    assert.throws(fn, 'this is not a Test Meter data packet');
  });

  const packets: Record<string, Buffer | null> = {
    'block not is Buffer object': null,
    'magic header not found': Buffer.from('FF000000000000000000', 'hex'),
    'message type unexpected': Buffer.from('FF550000000000000000', 'hex'),
    'command packet size error': Buffer.from('FF55110301000000005100', 'hex'),
    'checksum unexpected': Buffer.from('FF551103010000000052', 'hex'),
  };
  for (const [message, packet] of Object.entries(packets)) {
    it(`assertPacket: ${message}`, () => {
      const fn = () => {
        assertPacket(packet, MessageType.Command);
      };
      assert.throw(fn, message);
    });
  }
});
Example #6
Source File: commands.spec.ts    From mops-vida-pm-watchdog with MIT License 6 votes vote down vote up
describe('Commands', () => {
  const cases: Record<string, Buffer> = {
    AA01AB: cmds.shutdown(),
    AA080005B7: cmds.setMeasurementInterval(5),
    AA0800782A: cmds.setMeasurementInterval(120),
    AA095F492A981D: cmds.setRTC(new Date('2020-08-28T16:02:32.000Z')),
    AA0AB4: cmds.readHistory(),
    AA0BB5: cmds.nextHistory(),
    AA1600C0: cmds.setMeasurementEnable(false),
    AA1601C1: cmds.setMeasurementEnable(true),
  };
  for (const [expected, packet] of Object.entries(cases)) {
    it(expected, () => {
      assert.equalBytes(packet, expected);
    });
  }
});
Example #7
Source File: constructUrl.test.ts    From paystring with Apache License 2.0 6 votes vote down vote up
describe('Parsing - URLs - constructUrl()', function (): void {
  it('returns a url from components', function (): void {
    // GIVEN a set of URL components
    const protocol = 'https'
    const hostname = 'example.com'
    const path = '/alice'
    const expectedUrl = 'https://example.com/alice'

    // WHEN we attempt converting them to a URL
    const actualUrl = constructUrl(protocol, hostname, path)

    // THEN we get our expected URL
    assert.strictEqual(actualUrl, expectedUrl)
  })

  it('returns a url with a port from components', function (): void {
    // GIVEN a set of URL components w/ a port
    const protocol = 'https'
    const hostname = 'example.com'
    const path = '/alice'
    const port = '8080'
    const expectedUrl = 'https://example.com:8080/alice'

    // WHEN we attempt converting them to a URL
    const actualUrl = constructUrl(protocol, hostname, path, port)

    // THEN we get our expected URL w/ a port
    assert.strictEqual(actualUrl, expectedUrl)
  })
})
Example #8
Source File: action-on-google-test-manager.ts    From assistant-conversation-testing-nodejs with Apache License 2.0 6 votes vote down vote up
/** Send an interaction object to your action  */
  async sendInteraction(
    interactionParams: protos.google.actions.sdk.v2.ISendInteractionRequest
  ): Promise<protos.google.actions.sdk.v2.ISendInteractionResponse> {
    const interactionMergeParams = getDeepMerge(
      this.getTestInteractionMergedDefaults(),
      interactionParams
    );
    // Set the conversation token - if not the first query
    if (this.latestResponse) {
      assert.isFalse(
        this.getIsConversationEnded(),
        'Conversation ended unexpectedly in previous query.'
      );
      interactionMergeParams[constants.TOKEN_FIELD_NAME] = this.latestResponse[
        constants.TOKEN_FIELD_NAME
      ];
    }
    this.lastUserQuery = interactionMergeParams.input!['query'];
    this.latestResponse = await this.actionsApiHelper.sendInteraction(
      interactionMergeParams
    );
    this.validateSendInteractionResponse(this.latestResponse);
    return this.latestResponse!;
  }
Example #9
Source File: clean.ts    From polar with MIT License 6 votes vote down vote up
describe("Clean task", () => {
  useFixtureProject("testproject");
  useEnvironment();

  afterEach(() => {
    fs.removeSync(`./${ARTIFACTS_DIR}`);
  });

  it("When contract name is not specified", async function () {
    await compile(false, [], false, false);
    await this.env.run(TASK_CLEAN, {});

    assert.isFalse(fs.existsSync(`./${ARTIFACTS_DIR}`));
  }).timeout(200000);

  it("When there is no Artifacts directory and contract name is specified", async function () {
    await expectPolarErrorAsync(
      async () => await this.env.run(TASK_CLEAN, { contractName: "sample-project" }),
      ERRORS.GENERAL.ARTIFACTS_NOT_FOUND
    );
  }).timeout(200000);

  it("When contract name specified is incorrect", async function () {
    await compile(false, [], false, false);

    await expectPolarErrorAsync(
      async () => await this.env.run(TASK_CLEAN, { contractName: "sample-project1" }),
      ERRORS.GENERAL.INCORRECT_CONTRACT_NAME
    );
  }).timeout(200000);

  it("When contract name is specified", async function () {
    await compile(false, [], false, false);
    await this.env.run(TASK_CLEAN, { contractName: "sample-project" });
    assert.isFalse(fs.existsSync(`./${ARTIFACTS_DIR}/contracts/sample-project.wasm`));
    assert.isFalse(fs.existsSync(`./${ARTIFACTS_DIR}/schema/sample-project`));
    assert.isFalse(fs.existsSync(`./${ARTIFACTS_DIR}/checkpoints/sample-project.yaml`));
  }).timeout(200000);
});
Example #10
Source File: index.test.ts    From ethers-multicall with MIT License 6 votes vote down vote up
it('human readable abi', async () => {
  const abi = ['function totalSupply() public view returns (uint256)'];
  const addresses = [
    '0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e',
    '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'
  ];

  const yfiContract = new Contract(addresses[0], abi);
  const uniContract = new Contract(addresses[1], abi);

  const calls = [yfiContract.totalSupply(), uniContract.totalSupply()];
  const [yfiSupply, uniSupply] = await ethcallProvider.all(calls);

  assert.equal(yfiSupply.toString(), '36666000000000000000000');
  assert.equal(uniSupply.toString(), '1000000000000000000000000000');
});
Example #11
Source File: balancedAmounts.test.ts    From curve-js with MIT License 6 votes vote down vote up
balancedAmountsTest = (name: string) => {
    describe(`${name} balanced amounts`, function () {
        let pool: Pool;

        before(async function () {
            pool = new Pool(name);
        });

        it('underlying', async function () {
            const balancedAmounts = (await pool.balancedAmounts()).map(Number);

            assert.equal(balancedAmounts.length, pool.underlyingCoins.length);
            for (const amount of balancedAmounts) {
                assert.isAbove(amount, 0);
            }
        });

        it('wrapped', async function () {
            const balancedWrappedAmounts = (await pool.balancedWrappedAmounts()).map(Number);

            assert.equal(balancedWrappedAmounts.length, pool.coins.length);
            for (const amount of balancedWrappedAmounts) {
                assert.isAbove(amount, 0);
            }
        });

    });
}
Example #12
Source File: mockAccounts.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
export async function mockOracle(price = 50 * 10e7, expo = -7) {
	// default: create a $50 coin oracle
	const program = anchor.workspace.Pyth;

	anchor.setProvider(anchor.Provider.env());
	const priceFeedAddress = await createPriceFeed({
		oracleProgram: program,
		initPrice: price,
		expo: expo,
	});

	const feedData = await getFeedData(program, priceFeedAddress);
	assert.ok(feedData.price === price);

	return priceFeedAddress;
}
Example #13
Source File: identityCache.spec.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
describe('New identity cache tests', () => {
  it('Should add an identity to the cache', async () => {
    let cache;
    try {
      cache = new IdentityFetchCacheNew();
    } catch (error) {
      console.log(error);
      assert(error === null);
    }
    await cache.add('edgeware', '0x30DB748Fc0E4667CD6494f208de453464cf314A5');
    const result = await models.IdentityCache.findOne({
      where: {
        chain: 'edgeware',
        address: '0x30DB748Fc0E4667CD6494f208de453464cf314A5',
      },
    });
    assert(result.chain === 'edgeware');
    assert(result.address === '0x30DB748Fc0E4667CD6494f208de453464cf314A5');
  });
});
Example #14
Source File: heartbeat.spec.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
async function getPeer(
  self: PeerId,
  network: ReturnType<typeof createFakeNetwork>,
  netStatEvents: EventEmitter
): Promise<{ heartbeat: TestingHeartbeat; peers: NetworkPeers }> {
  const peers = new NetworkPeers([], [self], 0.3)

  const heartbeat = new TestingHeartbeat(
    peers,
    (protocol: string, handler: LibP2PHandlerFunction<any>) => network.subscribe(self, protocol, handler),
    ((dest: PeerId, protocol: string, msg: Uint8Array) => network.sendMessage(self, dest, protocol, msg)) as any,
    (async () => {
      assert.fail(`must not call hangUp`)
    }) as any,
    () => Promise.resolve(true),
    netStatEvents,
    (peerId) => peerId.toB58String() !== Charly.toB58String(),
    TESTING_ENVIRONMENT,
    {
      ...SHORT_TIMEOUTS,
      heartbeatThreshold: -3000,
      heartbeatInterval: 2000
    }
  )

  await heartbeat.start()

  return { heartbeat, peers }
}
Example #15
Source File: GenericOptionItemHandler.test.ts    From viewer-components-react with MIT License 6 votes vote down vote up
describe("GenericOptionItemHandler", () => {
  const GENERIC_STORAGE_KEY = "generic-storage-key";

  before(async () => {
  });

  afterEach(() => {
    sessionStorage.clear();
  });

  it("should get the value on init", async () => {
    let initialCondition = true;
    const setInitialValue = ((initialVal: boolean) => {
      sessionStorage.setItem(GENERIC_STORAGE_KEY, String(initialVal));
      initialCondition = initialVal;
    });
    const genericHandler = new GenericOptionItemHandler("tests", "generic handler", "anyicon", () => initialCondition, setInitialValue);
    genericHandler._setItemState(initialCondition);
    const returnValue = genericHandler.getIsActive();
    assert.isTrue(returnValue);
    assert.equal(sessionStorage.getItem(GENERIC_STORAGE_KEY), String(initialCondition));
  });

  it("should change the value when toggled", async () => {
    let initialCondition = true;
    const setInitialValue = ((initialVal: boolean) => {
      sessionStorage.setItem(GENERIC_STORAGE_KEY, String(initialVal));
      initialCondition = initialVal;
    });
    const genericHandler = new GenericOptionItemHandler("tests", "generic handler", "anyicon", () => initialCondition, setInitialValue);
    genericHandler._setItemState(initialCondition);
    genericHandler.toggle();
    const returnValue = genericHandler.getIsActive();
    assert.isFalse(returnValue);
    assert.equal(sessionStorage.getItem(GENERIC_STORAGE_KEY), "false");
  });
});
Example #16
Source File: api.spec.ts    From vue3-ts-base with MIT License 6 votes vote down vote up
describe('测试 User 模块 Api', () => {
  it('测试登录接口', async () => {
    const res = await UserService.login({
      userName: 'nihao',
      password: 'hahah'
    })
    console.log(res)
    assert.equal(res.data.code, 1, '业务接受不正常')
  })
})
Example #17
Source File: testUtilities.ts    From frontend-sample-showcase with MIT License 6 votes vote down vote up
function createViewDiv() {
  const div = document.createElement("div");
  assert(null !== div);
  div.style.width = div.style.height = "1000px";
  document.body.appendChild(div);
  // Object.defineProperty(div, "clientWidth", {
  //   writable: true,
  //   configurable: true,
  //   value: 1000,
  // });

  // Object.defineProperty(div, "clientHeight", {
  //   writable: true,
  //   configurable: true,
  //   value: 1000,
  // });

  // div.dispatchEvent(new Event("resize"));
  return div;
}
Example #18
Source File: btc-relay.test.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
describe("BTCRelay", function () {
    this.timeout(10000); // API can be slightly slow

    let api: ApiPromise;
    let interBtcAPI: InterBtcApi;

    before(async () => {
        api = await createSubstrateAPI(PARACHAIN_ENDPOINT);
        interBtcAPI = new DefaultInterBtcApi(api, "regtest", undefined, "testnet");
    });

    after(async () => {
        await api.disconnect();
    });

    it("should getLatestBTCBlockFromBTCRelay", async () => {
        const latestBTCBlockFromBTCRelay = await interBtcAPI.btcRelay.getLatestBlock();
        assert.isDefined(latestBTCBlockFromBTCRelay);
    }).timeout(1500);

    it("should getLatestBTCBlockHeightFromBTCRelay", async () => {
        const latestBTCBlockHeightFromBTCRelay = await interBtcAPI.btcRelay.getLatestBlockHeight();
        assert.isDefined(latestBTCBlockHeightFromBTCRelay);
    }).timeout(1500);
});
Example #19
Source File: backing.test.ts    From persistent-merkle-tree with Apache License 2.0 5 votes vote down vote up
describe("get", () => {
  it("should return the right node", () => {
    const n = subtreeFillToDepth(new LeafNode(Buffer.alloc(32, 1)), 3);
    const backing = new Tree(n);
    assert.deepEqual(backing.getRoot(8n), Buffer.alloc(32, 1));
  });
});
Example #20
Source File: languageProcessing.test.ts    From context-mod with MIT License 5 votes vote down vote up
describe('Language Detection', function () {

    describe('Derives language from user input', async function () {
        it('gets from valid, case-insensitive alpha2', async function () {
            const lang = await getLanguageTypeFromValue('eN');
            assert.equal(lang.alpha2, 'en');
        });
        it('gets from valid, case-insensitive alpha3', async function () {
            const lang = await getLanguageTypeFromValue('eNg');
            assert.equal(lang.alpha2, 'en');
        });
        it('gets from valid, case-insensitive language name', async function () {
            const lang = await getLanguageTypeFromValue('EnGlIsH');
            assert.equal(lang.alpha2, 'en');
        });

        it('throws on invalid value', function () {
            assert.isRejected(getLanguageTypeFromValue('pofdsfa'))
        });
    })

    describe('Recognizes the language in moderately long content well', function () {
        it('should recognize english', async function () {
            const lang = await getContentLanguage(longPositiveEnglish);
            assert.equal(lang.language.alpha2, 'en');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize french', async function () {
            const lang = await getContentLanguage(longFrench);
            assert.equal(lang.language.alpha2, 'fr');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize spanish', async function () {
            const lang = await getContentLanguage(longSpanish);
            assert.equal(lang.language.alpha2, 'es');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize german', async function () {
            const lang = await getContentLanguage(longGerman);
            assert.equal(lang.language.alpha2, 'de');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
        it('should recognize indonesian', async function () {
            const lang = await getContentLanguage(longIndonesian);
            assert.equal(lang.language.alpha2, 'id');
            assert.isFalse(lang.usedDefault);
            assert.isAtLeast(lang.bestGuess.score, 0.9);
        });
    });

    describe('Correctly handles short content classification', function () {
        it('uses default language', async function () {

            for (const content of [shortIndistinctEnglish, shortIndistinctEnglish2, shortIndonesian]) {
                const lang = await getContentLanguage(content);
                assert.equal(lang.language.alpha2, 'en', content);
                assert.isTrue(lang.usedDefault, content);
            }
        });

        it('uses best guess when default language is not provided', async function () {

            for (const content of [shortIndistinctEnglish, shortIndistinctEnglish2, shortIndonesian]) {
                const lang = await getContentLanguage(content, {defaultLanguage: false});
                assert.isFalse(lang.usedDefault);
            }
        });
    });
});
Example #21
Source File: palette.test.ts    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
describe('adding to palette', () => {
    it('creates new category on first add puts component there', () => {
      const paletteContent = `
      import react from "react";
      <Palette>
        <Category name="another"></Category>
      </Palette>
      `
      const actualPreviewsContent = addComponent(paletteContent, {
        componentPath,
        componentFileName: componentName
      }, true);

      assert.equal(stripAll(expectedFirst), stripAll(actualPreviewsContent));
    })
    it('generating to correct category on second add', () => {
      const componentName2 = 'TestedComponent2';
      const componentPath2 = "./tested2path"
      const expected = `
      import react from "react";
      import ${componentName2} from "${componentPath2}";
      import ${componentName} from "${componentPath}";
      <Palette>
        <Category name="another"></Category>
        <Category name="Screens">
          <Component name="${componentName}">
            <Variant>
              <${componentName} />
            </Variant>
          </Component>
          <Component name="${componentName2}">
            <Variant>
              <${componentName2} />
            </Variant>
          </Component>
        </Category>
      </Palette>
      `

      const actualPreviewsContent = addComponent(expectedFirst, {
        componentPath: componentPath2,
        componentFileName: componentName2
      }, true);

      assert.equal(stripAll(expected), stripAll(actualPreviewsContent));
    })
})
Example #22
Source File: packet-meter-ac.spec.ts    From atorch-console with MIT License 5 votes vote down vote up
describe('AC Meter', () => {
  const entries: Record<string, InstanceType<typeof ACMeterPacket>> = {
    FF55010100090400000E0000040000000000006401F40085002F00000A093C0000000039: {
      type: 1,
      mVoltage: 230800,
      mAmpere: 14,
      mWatt: 400,
      mWh: 0,
      price: 1,
      fee: 0,
      frequency: 50,
      pf: 0.133,
      temperature: 47,
      duration: '000:10:09',
      backlightTime: 60,
    },
    FF5501010008EB000000000000000001FE00006401F40000002F003125143C0000000066: {
      type: 1,
      mVoltage: 228300,
      mAmpere: 0,
      mWatt: 0,
      mWh: 5100000,
      price: 1,
      fee: 5.1,
      frequency: 50,
      pf: 0,
      temperature: 47,
      duration: '049:37:20',
      backlightTime: 60,
    },
    FF5501010008FF0000270000210000000000006401F401740031000038083C0000000088: {
      type: 1,
      mVoltage: 230300,
      mAmpere: 39,
      mWatt: 3300,
      mWh: 0,
      price: 1,
      fee: 0,
      frequency: 50,
      pf: 0.372,
      temperature: 49,
      duration: '000:56:08',
      backlightTime: 60,
    },
  };
  for (const [packet, expected] of Object.entries(entries)) {
    it(packet, () => {
      const block = Buffer.from(packet, 'hex');
      const report = new ACMeterPacket(block);
      assert.isTrue(isMeterPacket(report));
      assert.deepEqual(expected, report);
    });
  }
});
Example #23
Source File: payIds.test.ts    From paystring with Apache License 2.0 5 votes vote down vote up
describe('Data Access - getAllAddressInfoFromDatabase()', function (): void {
  before(async function () {
    await seedDatabase()
  })

  it('Gets address information for a known PayID (1 address)', async function () {
    // GIVEN a PayID known to exist in the database
    // WHEN we attempt to retrieve address information for that tuple
    const addressInfo = await getAllAddressInfoFromDatabase(
      'alice$xpring.money',
    )

    // THEN we get our seeded value back
    const expectedaddressInfo = [
      {
        paymentNetwork: 'XRPL',
        environment: 'TESTNET',
        details: {
          address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
        },
      },
    ]
    assert.deepEqual(addressInfo, expectedaddressInfo)
  })

  it('Gets address information for a known PayID (multiple addresses)', async function () {
    // GIVEN a PayID known to exist in the database
    // WHEN we attempt to retrieve address information for that tuple
    const addressInfo = await getAllAddressInfoFromDatabase('alice$127.0.0.1')

    // THEN we get our seeded values back
    const expectedaddressInfo = [
      {
        paymentNetwork: 'XRPL',
        environment: 'MAINNET',
        details: {
          address: 'rw2ciyaNshpHe7bCHo4bRWq6pqqynnWKQg',
          tag: '67298042',
        },
      },
      {
        paymentNetwork: 'XRPL',
        environment: 'TESTNET',
        details: {
          address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
        },
      },
      {
        paymentNetwork: 'BTC',
        environment: 'TESTNET',
        details: {
          address: 'mxNEbRXokcdJtT6sbukr1CTGVx8Tkxk3DB',
        },
      },
      {
        paymentNetwork: 'ACH',
        environment: null,
        details: {
          accountNumber: '000123456789',
          routingNumber: '123456789',
        },
      },
    ]
    assert.deepEqual(addressInfo, expectedaddressInfo)
  })

  it('Returns empty array for an unknown PayID', async function () {
    // GIVEN a PayID known to not exist in the database
    // WHEN we attempt to retrieve address information for that tuple
    const addressInfo = await getAllAddressInfoFromDatabase('johndoe$xpring.io')

    // THEN we get back an empty array
    assert.deepStrictEqual(addressInfo, [])
  })
})
Example #24
Source File: workspace.ts    From quarry with GNU Affero General Public License v3.0 5 votes vote down vote up
assertError = (error: IDLError, other: IDLError): void => {
  assert.strictEqual(error.code, other.code);
  assert.strictEqual(error.msg, other.msg);
}
Example #25
Source File: workspace.ts    From sencha with GNU Affero General Public License v3.0 5 votes vote down vote up
assertError = (error: IDLError, other: IDLError): void => {
  assert.strictEqual(error.code, other.code);
  assert.strictEqual(error.msg, other.msg);
}
Example #26
Source File: compile.ts    From polar with MIT License 5 votes vote down vote up
describe("Compile task", () => {
  afterEach(() => {
    fs.removeSync("./artifacts");
  });
  describe("Compile simple contract", function () {
    useFixtureProject("testproject");
    it("Should create .wasm files", async function () {
      await compile(false, [], false, false);

      assert.isTrue(fs.existsSync(`./artifacts/contracts/sample_project.wasm`));
    }).timeout(200000);
  });

  describe("Compile multi contract", function () {
    useFixtureProject("multiproject");
    it("Should create .wasm files for  each contract", async function () {
      await compile(false, [], false, false);

      assert.isTrue(fs.existsSync(`./artifacts/contracts/sample_project.wasm`));
      assert.isTrue(fs.existsSync(`./artifacts/contracts/sample_project_1.wasm`));
    }).timeout(200000);
  });

  describe("Should not compile multiple contract with same name", function () {
    useFixtureProject("multiproject-error");
    it("Should give an error of same contract names", async function () {
      await expectPolarErrorAsync(
        async () => await compile(false, [], false, false),
        ERRORS.GENERAL.SAME_CONTRACT_NAMES
      );
    }).timeout(200000);
  });

  describe("Compile by providing sourceDir", function () {
    useFixtureProject("testproject");
    it("Should create .wasm files of only given contract in sourceDir", async function () {
      await compile(false, ["contracts/"], false, false);

      assert.isTrue(fs.existsSync(`./artifacts/contracts/sample_project.wasm`));
    }).timeout(200000);
  });

  describe("Compile fail when contract has compile errors", function () {
    useFixtureProject("errorproject");
    it("Should raise Polar error", async function () {
      // check for Exception
      await expectPolarErrorAsync(
        async () => await compile(false, [], false, false),
        ERRORS.GENERAL.RUST_COMPILE_ERROR
      );
    }).timeout(200000);
  });
});
Example #27
Source File: RuntimeArgs.test.ts    From casper-js-sdk with Apache License 2.0 5 votes vote down vote up
describe(`RuntimeArgs`, () => {
  it('should serialize RuntimeArgs correctly', () => {
    const args = RuntimeArgs.fromMap({
      foo: CLValueBuilder.i32(1)
    });
    const bytes = args.toBytes().unwrap();
    expect(bytes).to.deep.eq(
      Uint8Array.from([
        1,
        0,
        0,
        0,
        3,
        0,
        0,
        0,
        102,
        111,
        111,
        4,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        1
      ])
    );
  });

  it('should serialize empty NamedArgs correctly', () => {
    const truth = decodeBase16('00000000');
    const runtimeArgs = RuntimeArgs.fromMap({});
    const bytes = runtimeArgs.toBytes().unwrap();
    expect(bytes).to.deep.eq(truth);
  });

  it('should deserialize RuntimeArgs', () => {
    let a = CLValueBuilder.u512(123);
    const runtimeArgs = RuntimeArgs.fromMap({
      a: CLValueBuilder.option(None, a.clType())
    });
    let serializer = new TypedJSON(RuntimeArgs);
    let str = serializer.stringify(runtimeArgs);
    let value = serializer.parse(str)!;
    assert.isTrue((value.args.get('a')! as CLOption<CLU512>).isNone());
  });

  it('should allow to extract lists of account hashes.', () => {
    const account0 = Keys.Ed25519.new().accountHash();
    const account1 = Keys.Ed25519.new().accountHash();
    const account0byteArray =         CLValueBuilder.byteArray(account0);
    const account1byteArray =         CLValueBuilder.byteArray(account1);
    let runtimeArgs = RuntimeArgs.fromMap({
      accounts: CLValueBuilder.list([
        account0byteArray,
        account1byteArray
      ])
    });
    let accounts = runtimeArgs.args.get('accounts')! as CLList<CLByteArray>;
    assert.deepEqual(accounts.get(0), account0byteArray);
    assert.deepEqual(accounts.get(1), account1byteArray);
  });
});
Example #28
Source File: boosting.test.ts    From curve-js with MIT License 5 votes vote down vote up
describe('Boosting', function() {
    this.timeout(120000);
    let address = '';

    before(async function() {
        await curve.init('JsonRpc', {}, { gasPrice: 0 });
        address = curve.signerAddress;
    });

    it('Creates lock in Voting Escrow contract', async function () {
        const lockAmount = '1000';

        const initialCrvBalance: string = await getCrv() as string;
        const lockTime = Date.now();
        await createLock(lockAmount, 365);
        const crvBalance = await getCrv() as string;
        const { lockedAmount, unlockTime } = await getLockedAmountAndUnlockTime() as { lockedAmount: string, unlockTime: number };

        assert.deepEqual(BN(lockedAmount), BN(initialCrvBalance).minus(BN(crvBalance)));
        assert.isAtLeast(unlockTime + (7 * 86400 * 1000), lockTime + (365 * 86400 * 1000));
    });

    it('Increases amount locked in Voting Escrow contract', async function () {
        const increaseLockAmount = '1000';

        const initialCrvBalance: string = await getCrv() as string;
        const { lockedAmount: initialLockedAmount } = await getLockedAmountAndUnlockTime() as { lockedAmount: string, unlockTime: number };
        await increaseAmount(increaseLockAmount);
        const crvBalance = await getCrv() as string;
        const { lockedAmount } = await getLockedAmountAndUnlockTime() as { lockedAmount: string, unlockTime: number };

        assert.deepEqual(BN(lockedAmount).minus(BN(initialLockedAmount)), BN(initialCrvBalance).minus(BN(crvBalance)));
    });

    it('Extends lock time', async function () {
        const { unlockTime: initialUnlockTime } = await getLockedAmountAndUnlockTime() as { lockedAmount: string, unlockTime: number };
        await increaseUnlockTime(120);
        const { unlockTime } = await getLockedAmountAndUnlockTime(address) as { lockedAmount: string, unlockTime: number };

        assert.isAtLeast(unlockTime + (7 * 86400 * 1000), initialUnlockTime + (120 * 86400 * 1000));
    });
});
Example #29
Source File: maxDeposit.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
describe('max deposit', () => {
	const provider = anchor.AnchorProvider.local();
	const connection = provider.connection;
	anchor.setProvider(provider);
	const chProgram = anchor.workspace.ClearingHouse as Program;

	let clearingHouse: Admin;

	let usdcMint;
	let userUSDCAccount;

	// ammInvariant == k == x * y
	const mantissaSqrtScale = new BN(Math.sqrt(MARK_PRICE_PRECISION.toNumber()));
	const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul(
		mantissaSqrtScale
	);
	const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul(
		mantissaSqrtScale
	);

	const usdcAmount = new BN(10 * 10 ** 6);

	before(async () => {
		usdcMint = await mockUSDCMint(provider);
		userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider);

		clearingHouse = Admin.from(
			connection,
			provider.wallet,
			chProgram.programId
		);
		await clearingHouse.initialize(usdcMint.publicKey, true);
		await clearingHouse.subscribe();

		const solUsd = await mockOracle(1);
		const periodicity = new BN(60 * 60); // 1 HOUR

		await clearingHouse.initializeMarket(
			Markets[0].marketIndex,
			solUsd,
			ammInitialBaseAssetReserve,
			ammInitialQuoteAssetReserve,
			periodicity
		);

		await clearingHouse.updateMaxDeposit(usdcAmount.div(new BN(2)));
	});

	after(async () => {
		await clearingHouse.unsubscribe();
	});

	it('successful deposit', async () => {
		await clearingHouse.initializeUserAccountAndDepositCollateral(
			usdcAmount.div(new BN(2)),
			userUSDCAccount.publicKey
		);
	});

	it('blocked deposit', async () => {
		try {
			await clearingHouse.depositCollateral(
				usdcAmount.div(new BN(2)),
				userUSDCAccount.publicKey
			);
		} catch (e) {
			return;
		}
		assert(false);
	});
});