Best Python code snippet using yandex-tank
BancorConverter.js
Source:BancorConverter.js  
1/* global artifacts, contract, before, it, assert */2/* eslint-disable prefer-reflect */3const BancorConverter = artifacts.require('BancorConverter.sol');4const SmartToken = artifacts.require('SmartToken.sol');5const BancorFormula = artifacts.require('BancorFormula.sol');6const BancorGasPriceLimit = artifacts.require('BancorGasPriceLimit.sol');7const BancorQuickConverter = artifacts.require('BancorQuickConverter.sol');8const BancorConverterExtensions = artifacts.require('BancorConverterExtensions.sol');9const TestERC20Token = artifacts.require('TestERC20Token.sol');10const utils = require('./helpers/Utils');11const weight10Percent = 100000;12const gasPrice = 22000000000;13const gasPriceBad = 22000000001;14let token;15let tokenAddress;16let converterExtensionsAddress;17let connectorToken;18let connectorToken2;19let connectorTokenAddress;20let connectorTokenAddress2 = '0x32f0f93396f0865d7ce412695beb3c3ad9ccca75';21// used by purchase/sale tests22async function initConverter(accounts, activate) {23    token = await SmartToken.new('Token1', 'TKN1', 2);24    tokenAddress = token.address;25    connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);26    connectorTokenAddress = connectorToken.address;27    connectorToken2 = await TestERC20Token.new('ERC Token 2', 'ERC2', 200000);28    connectorTokenAddress2 = connectorToken2.address;29    let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, connectorTokenAddress, 250000);30    let converterAddress = converter.address;31    await converter.addConnector(connectorTokenAddress2, 150000, false);32    await token.issue(accounts[0], 20000);33    await connectorToken.transfer(converterAddress, 5000);34    await connectorToken2.transfer(converterAddress, 8000);35    if (activate) {36        await token.transferOwnership(converterAddress);37        await converter.acceptTokenOwnership();38    }39    return converter;40}41function verifyConnector(connector, isSet, isEnabled, weight, isVirtualBalanceEnabled, virtualBalance) {42    assert.equal(connector[0], virtualBalance);43    assert.equal(connector[1], weight);44    assert.equal(connector[2], isVirtualBalanceEnabled);45    assert.equal(connector[3], isEnabled);46    assert.equal(connector[4], isSet);47}48function getConversionAmount(transaction, logIndex = 0) {49    return transaction.logs[logIndex].args._return.toNumber();50}51contract('BancorConverter', (accounts) => {52    before(async () => {53        let token = await SmartToken.new('Token1', 'TKN1', 2);54        let formula = await BancorFormula.new();55        let gasPriceLimit = await BancorGasPriceLimit.new(gasPrice);56        let quickConverter = await BancorQuickConverter.new();57        let converterExtensions = await BancorConverterExtensions.new(formula.address, gasPriceLimit.address, quickConverter.address);58        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);59        tokenAddress = token.address;60        converterExtensionsAddress = converterExtensions.address;61        connectorTokenAddress = connectorToken.address;62    });63    it('verifies the converter data after construction', async () => {64        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);65        let token = await converter.token.call();66        assert.equal(token, tokenAddress);67        let extensions = await converter.extensions.call();68        assert.equal(extensions, converterExtensionsAddress);69        let maxConversionFee = await converter.maxConversionFee.call();70        assert.equal(maxConversionFee, 0);71        let conversionsEnabled = await converter.conversionsEnabled.call();72        assert.equal(conversionsEnabled, true);73    });74    it('should throw when attempting to construct a converter with no token', async () => {75        try {76            await BancorConverter.new('0x0', converterExtensionsAddress, 0, '0x0', 0);77            assert(false, "didn't throw");78        }79        catch (error) {80            return utils.ensureException(error);81        }82    });83    it('should throw when attempting to construct a converter with no converter extensions', async () => {84        try {85            await BancorConverter.new(tokenAddress, '0x0', 0, '0x0', 0);86            assert(false, "didn't throw");87        }88        catch (error) {89            return utils.ensureException(error);90        }91    });92    it('should throw when attempting to construct a converter with invalid max fee', async () => {93        try {94            await BancorConverter.new(tokenAddress, converterExtensionsAddress, 1000000000, '0x0', 0);95            assert(false, "didn't throw");96        }97        catch (error) {98            return utils.ensureException(error);99        }100    });101    it('verifies the first connector when provided at construction time', async () => {102        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, connectorTokenAddress, 200000);103        let connectorToken = await converter.connectorTokens.call(0);104        assert.equal(connectorToken, connectorTokenAddress);105        let connector = await converter.connectors.call(connectorToken);106        verifyConnector(connector, true, true, 200000, false, 0);107    });108    it('should throw when attempting to construct a converter with a connector with invalid weight', async () => {109        try {110            await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, connectorTokenAddress, 1000001);111            assert(false, "didn't throw");112        }113        catch (error) {114            return utils.ensureException(error);115        }116    });117    it('verifies the connector token count before / after adding a connector', async () => {118        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);119        let connectorTokenCount = await converter.connectorTokenCount.call();120        assert.equal(connectorTokenCount, 0);121        await converter.addConnector(connectorTokenAddress, weight10Percent, false);122        connectorTokenCount = await converter.connectorTokenCount.call();123        assert.equal(connectorTokenCount, 1);124    });125    it('verifies the convertible token count before / after adding a connector', async () => {126        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);127        let convertibleTokenCount = await converter.convertibleTokenCount.call();128        assert.equal(convertibleTokenCount, 1);129        await converter.addConnector(connectorTokenAddress, weight10Percent, false);130        convertibleTokenCount = await converter.convertibleTokenCount.call();131        assert.equal(convertibleTokenCount, 2);132    });133    it('verifies the convertible token addresses', async () => {134        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);135        await converter.addConnector(connectorTokenAddress, weight10Percent, false);136        let convertibleTokenAddress = await converter.convertibleToken.call(0);137        assert.equal(convertibleTokenAddress, tokenAddress);138        convertibleTokenAddress = await converter.convertibleToken.call(1);139        assert.equal(convertibleTokenAddress, connectorTokenAddress);140    });141    it('verifies the owner can update the converter extensions contract address', async () => {142        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);143        await converter.setExtensions(accounts[3]);144        let extensions = await converter.extensions.call();145        assert.notEqual(extensions, converterExtensionsAddress);146    });147    it('should throw when a non owner attempts update the converter extensions contract address', async () => {148        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);149        try {150            await converter.setExtensions(accounts[3], { from: accounts[1] });151            assert(false, "didn't throw");152        }153        catch (error) {154            return utils.ensureException(error);155        }156    });157    it('should throw when a non owner attempts update the converter extensions contract address with an invalid address', async () => {158        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);159        try {160            await converter.setExtensions('0x0', { from: accounts[1] });161            assert(false, "didn't throw");162        }163        catch (error) {164            return utils.ensureException(error);165        }166    });167    it('should throw when a non owner attempts update the converter extensions contract address with the converter address', async () => {168        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);169        try {170            await converter.setExtensions(converter.address, { from: accounts[1] });171            assert(false, "didn't throw");172        }173        catch (error) {174            return utils.ensureException(error);175        }176    });177    it('should throw when a non owner attempts update the converter extensions contract address with the same existing address', async () => {178        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);179        try {180            await converter.setExtensions(converterExtensionsAddress, { from: accounts[1] });181            assert(false, "didn't throw");182        }183        catch (error) {184            return utils.ensureException(error);185        }186    });187    it('verifies the owner can update the fee', async () => {188        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);189        await converter.setConversionFee(30000);190        let conversionFee = await converter.conversionFee.call();191        assert.equal(conversionFee, 30000);192    });193    it('should throw when attempting to update the fee to an invalid value', async () => {194        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);195        try {196            await converter.setConversionFee(200001);197            assert(false, "didn't throw");198        }199        catch (error) {200            return utils.ensureException(error);201        }202    });203    it('should throw when a non owner attempts to update the fee', async () => {204        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);205        try {206            await converter.setConversionFee(30000, { from: accounts[1] });207            assert(false, "didn't throw");208        }209        catch (error) {210            return utils.ensureException(error);211        }212    });213    it('verifies that getConversionFeeAmount returns the correct amount', async () => {214        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);215        await converter.setConversionFee(10000);216        let conversionFeeAmount = await converter.getConversionFeeAmount.call(500000);217        assert.equal(conversionFeeAmount, 5000);218    });219    it('verifies that an event is fired when the owner update the fee', async () => {220        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);221        let watcher = converter.ConversionFeeUpdate();222        await converter.setConversionFee(30000);223        let events = await watcher.get();224        assert.equal(events[0].args._prevFee.valueOf(), 0);225        assert.equal(events[0].args._newFee.valueOf(), 30000);226    });227    it('verifies that an event is fired when the owner update the fee multiple times', async () => {228        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);229        let watcher = converter.ConversionFeeUpdate();230        let events;231        for (let i = 1; i <= 10; ++i) {232            await converter.setConversionFee(10000 * i);233            events = await watcher.get();234            assert.equal(events[0].args._prevFee.valueOf(), 10000 * (i - 1));235            assert.equal(events[0].args._newFee.valueOf(), 10000 * i);236        }237    });238    it('should not fire an event when attempting to update the fee to an invalid value', async () => {239        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);240        let watcher = converter.ConversionFeeUpdate();241        try {242            await converter.setConversionFee(200001);243            assert(false, "didn't throw");244        }245        catch (error) {246            let events = await watcher.get();247            assert.equal(events.length, 0);248            return utils.ensureException(error);249        }250    });251    it('should not fire an event when a non owner attempts to update the fee', async () => {252        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 200000, '0x0', 0);253        let watcher = converter.ConversionFeeUpdate();254        try {255            await converter.setConversionFee(30000, { from: accounts[1] });256            assert(false, "didn't throw");257        }258        catch (error) {259            let events = await watcher.get();260            assert.equal(events.length, 0);261            return utils.ensureException(error);262        }263    });264    it('verifies that 2 connectors are added correctly', async () => {265        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);266        await converter.addConnector(connectorTokenAddress, weight10Percent, false);267        let connector = await converter.connectors.call(connectorTokenAddress);268        verifyConnector(connector, true, true, weight10Percent, false, 0);269        await converter.addConnector(connectorTokenAddress2, 200000, false);270        connector = await converter.connectors.call(connectorTokenAddress2);271        verifyConnector(connector, true, true, 200000, false, 0);272    });273    it('should throw when a non owner attempts to add a connector', async () => {274        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);275        try {276            await converter.addConnector(connectorTokenAddress, weight10Percent, false, { from: accounts[1] });277            assert(false, "didn't throw");278        }279        catch (error) {280            return utils.ensureException(error);281        }282    });283    it('should throw when attempting to add a connector when the converter is active', async () => {284        let token = await SmartToken.new('Token1', 'TKN1', 2);285        let converter = await BancorConverter.new(token.address, converterExtensionsAddress, 0, '0x0', 0);286        token.transferOwnership(converter.address);287        converter.acceptTokenOwnership();288        try {289            await converter.addConnector(connectorTokenAddress, weight10Percent, false);290            assert(false, "didn't throw");291        }292        catch (error) {293            return utils.ensureException(error);294        }295    });296    it('should throw when attempting to add a connector with invalid address', async () => {297        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);298        try {299            await converter.addConnector('0x0', weight10Percent, false);300            assert(false, "didn't throw");301        }302        catch (error) {303            return utils.ensureException(error);304        }305    });306    it('should throw when attempting to add a connector with weight = 0', async () => {307        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);308        try {309            await converter.addConnector(connectorTokenAddress, 0, false);310            assert(false, "didn't throw");311        }312        catch (error) {313            return utils.ensureException(error);314        }315    });316    it('should throw when attempting to add a connector with weight greater than 100%', async () => {317        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);318        try {319            await converter.addConnector(connectorTokenAddress, 1000001, false);320            assert(false, "didn't throw");321        }322        catch (error) {323            return utils.ensureException(error);324        }325    });326    it('should throw when attempting to add the token as a connector', async () => {327        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);328        try {329            await converter.addConnector(tokenAddress, weight10Percent, false);330            assert(false, "didn't throw");331        }332        catch (error) {333            return utils.ensureException(error);334        }335    });336    it('should throw when attempting to add the converter as a connector', async () => {337        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);338        try {339            await converter.addConnector(converter.address, weight10Percent, false);340            assert(false, "didn't throw");341        }342        catch (error) {343            return utils.ensureException(error);344        }345    });346    it('should throw when attempting to add a connector that already exists', async () => {347        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);348        await converter.addConnector(connectorTokenAddress, weight10Percent, false);349        try {350            await converter.addConnector(connectorTokenAddress, 200000, false);351            assert(false, "didn't throw");352        }353        catch (error) {354            return utils.ensureException(error);355        }356    });357    it('should throw when attempting to add multiple connectors with total weight greater than 100%', async () => {358        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);359        await converter.addConnector(connectorTokenAddress, 500000, false);360        try {361            await converter.addConnector(connectorTokenAddress2, 500001, false);362            assert(false, "didn't throw");363        }364        catch (error) {365            return utils.ensureException(error);366        }367    });368    it('verifies that the owner can update a connector', async () => {369        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);370        await converter.addConnector(connectorTokenAddress, weight10Percent, false);371        let connector = await converter.connectors.call(connectorTokenAddress);372        verifyConnector(connector, true, true, weight10Percent, false, 0);373        await converter.updateConnector(connectorTokenAddress, 200000, true, 50);374        connector = await converter.connectors.call(connectorTokenAddress);375        verifyConnector(connector, true, true, 200000, true, 50);376    });377    it('should throw when a non owner attempts to update a connector', async () => {378        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);379        await converter.addConnector(connectorTokenAddress, weight10Percent, false);380        try {381            await converter.updateConnector(connectorTokenAddress, 200000, false, 0, { from: accounts[1] });382            assert(false, "didn't throw");383        }384        catch (error) {385            return utils.ensureException(error);386        }387    });388    it('should throw when attempting to update a connector that does not exist', async () => {389        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);390        await converter.addConnector(connectorTokenAddress, weight10Percent, false);391        try {392            await converter.updateConnector(connectorTokenAddress2, 200000, false, 0);393            assert(false, "didn't throw");394        }395        catch (error) {396            return utils.ensureException(error);397        }398    });399    it('should throw when attempting to update a connector with weight = 0', async () => {400        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);401        await converter.addConnector(connectorTokenAddress, weight10Percent, false);402        try {403            await converter.updateConnector(connectorTokenAddress, 0, false, 0);404            assert(false, "didn't throw");405        }406        catch (error) {407            return utils.ensureException(error);408        }409    });410    it('should throw when attempting to update a connector with weight greater than 100%', async () => {411        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);412        await converter.addConnector(connectorTokenAddress, weight10Percent, false);413        try {414            await converter.updateConnector(connectorTokenAddress, 1000001, false, 0);415            assert(false, "didn't throw");416        }417        catch (error) {418            return utils.ensureException(error);419        }420    });421    it('should throw when attempting to update a connector that will result in total weight greater than 100%', async () => {422        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);423        await converter.addConnector(connectorTokenAddress, 500000, false);424        await converter.addConnector(connectorTokenAddress2, 400000, false);425        try {426            await converter.updateConnector(connectorTokenAddress2, 500001, false, 0);427            assert(false, "didn't throw");428        }429        catch (error) {430            return utils.ensureException(error);431        }432    });433    it('verifies that the manager can disable / re-enable conversions', async () => {434        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);435        await converter.transferManagement(accounts[4]);436        await converter.acceptManagement({ from: accounts[4] });437        let conversionsEnabled = await converter.conversionsEnabled.call();438        assert.equal(conversionsEnabled, true);439        await converter.disableConversions(true, { from: accounts[4] });440        conversionsEnabled = await converter.conversionsEnabled.call();441        assert.equal(conversionsEnabled, false);442        await converter.disableConversions(false, { from: accounts[4] });443        conversionsEnabled = await converter.conversionsEnabled.call();444        assert.equal(conversionsEnabled, true);445    });446    it('should throw when a non owner attempts to disable conversions', async () => {447        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);448        try {449            await converter.disableConversions(true, { from: accounts[1] });450            assert(false, "didn't throw");451        }452        catch (error) {453            return utils.ensureException(error);454        }455    });456    it('verifies that the owner can disable / re-enable connector purchases', async () => {457        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);458        await converter.addConnector(connectorTokenAddress, weight10Percent, false);459        let connector = await converter.connectors.call(connectorTokenAddress);460        verifyConnector(connector, true, true, weight10Percent, false, 0);461        await converter.disableConnectorPurchases(connectorTokenAddress, true);462        connector = await converter.connectors.call(connectorTokenAddress);463        verifyConnector(connector, true, false, weight10Percent, false, 0);464        await converter.disableConnectorPurchases(connectorTokenAddress, false);465        connector = await converter.connectors.call(connectorTokenAddress);466        verifyConnector(connector, true, true, weight10Percent, false, 0);467    });468    it('should throw when a non owner attempts to disable connector purchases', async () => {469        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);470        await converter.addConnector(connectorTokenAddress, weight10Percent, false);471        try {472            await converter.disableConnectorPurchases(connectorTokenAddress, true, { from: accounts[1] });473            assert(false, "didn't throw");474        }475        catch (error) {476            return utils.ensureException(error);477        }478    });479    it('should throw when attempting to disable connector purchases for a connector that does not exist', async () => {480        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);481        await converter.addConnector(connectorTokenAddress, weight10Percent, false);482        try {483            await converter.disableConnectorPurchases(connectorTokenAddress2, true);484            assert(false, "didn't throw");485        }486        catch (error) {487            return utils.ensureException(error);488        }489    });490    it('verifies that the correct connector balance is returned regardless of whether virtual balance is set or not', async () => {491        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);492        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);493        await converter.addConnector(connectorToken.address, weight10Percent, false);494        let connectorBalance;495        connectorBalance = await converter.getConnectorBalance.call(connectorToken.address);496        assert.equal(connectorBalance, 0);497        await connectorToken.transfer(converter.address, 1000);498        connectorBalance = await converter.getConnectorBalance.call(connectorToken.address);499        assert.equal(connectorBalance, 1000);500        await converter.updateConnector(connectorToken.address, 200000, true, 5000);501        connectorBalance = await converter.getConnectorBalance.call(connectorToken.address);502        assert.equal(connectorBalance, 5000);503        await converter.updateConnector(connectorToken.address, 200000, false, 5000);504        connectorBalance = await converter.getConnectorBalance.call(connectorToken.address);505        assert.equal(connectorBalance, 1000);506    });507    it('should throw when attempting to retrieve the balance for a connector that does not exist', async () => {508        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);509        await converter.addConnector(connectorTokenAddress, weight10Percent, false);510        try {511            await converter.getConnectorBalance.call(connectorTokenAddress2);512            assert(false, "didn't throw");513        }514        catch (error) {515            return utils.ensureException(error);516        }517    });518    it('verifies that the owner can withdraw from the connector', async () => {519        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);520        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);521        await converter.addConnector(connectorToken.address, weight10Percent, false);522        await connectorToken.transfer(converter.address, 1000);523        let converterBalance = await connectorToken.balanceOf(converter.address);524        assert.equal(converterBalance, 1000);525        await converter.withdrawTokens(connectorToken.address, accounts[2], 50);526        converterBalance = await connectorToken.balanceOf(converter.address);527        assert.equal(converterBalance, 950);528        let account2Balance = await connectorToken.balanceOf(accounts[2]);529        assert.equal(account2Balance, 50);530    });531    it('should throw when a non owner attempts to withdraw from the connector', async () => {532        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);533        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);534        await converter.addConnector(connectorToken.address, weight10Percent, false);535        await connectorToken.transfer(converter.address, 1000);536        try {537            await converter.withdrawTokens(connectorToken.address, accounts[3], 50, { from: accounts[1] });538            assert(false, "didn't throw");539        }540        catch (error) {541            return utils.ensureException(error);542        }543    });544    it('should throw when attempting to withdraw from a connector to an invalid address', async () => {545        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);546        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);547        await converter.addConnector(connectorToken.address, weight10Percent, false);548        await connectorToken.transfer(converter.address, 1000);549        try {550            await converter.withdrawTokens(connectorToken.address, '0x0', 50);551            assert(false, "didn't throw");552        }553        catch (error) {554            return utils.ensureException(error);555        }556    });557    it('should throw when attempting to withdraw from a connector to the converter address', async () => {558        let converter = await BancorConverter.new(tokenAddress, converterExtensionsAddress, 0, '0x0', 0);559        let connectorToken = await TestERC20Token.new('ERC Token 1', 'ERC1', 100000);560        await converter.addConnector(connectorToken.address, weight10Percent, false);561        await connectorToken.transfer(converter.address, 1000);562        try {563            await converter.withdrawTokens(connectorToken.address, converter.address, 50);564            assert(false, "didn't throw");565        }566        catch (error) {567            return utils.ensureException(error);568        }569    });570    it('verifies that getReturn returns a valid amount', async () => {571        let converter = await initConverter(accounts, true);572        let returnAmount = await converter.getReturn.call(connectorTokenAddress, tokenAddress, 500);573        assert.isNumber(returnAmount.toNumber());574        assert.notEqual(returnAmount.toNumber(), 0);575    });576    it('verifies that getReturn returns the same amount as getPurchaseReturn when converting from a connector to the token', async () => {577        let converter = await initConverter(accounts, true);578        let returnAmount = await converter.getReturn.call(connectorTokenAddress, tokenAddress, 500);579        let purchaseReturnAmount = await converter.getPurchaseReturn.call(connectorTokenAddress, 500);580        assert.equal(returnAmount.toNumber(), purchaseReturnAmount.toNumber());581    });582    it('verifies that getReturn returns the same amount as getSaleReturn when converting from the token to a connector', async () => {583        let converter = await initConverter(accounts, true);584        let returnAmount = await converter.getReturn.call(tokenAddress, connectorTokenAddress, 500);585        let saleReturnAmount = await converter.getSaleReturn.call(connectorTokenAddress, 500);586        assert.isNumber(returnAmount.toNumber());587        assert.notEqual(returnAmount.toNumber(), 0);588        assert.equal(returnAmount.toNumber(), saleReturnAmount.toNumber());589    });590    it('verifies that getReturn returns the same amount as buy -> sell when converting from connector 1 to connector 2', async () => {591        let converter = await initConverter(accounts, true);592        let returnAmount = await converter.getReturn.call(connectorTokenAddress, connectorTokenAddress2, 500);593        await connectorToken.approve(converter.address, 500);594        let purchaseRes = await converter.buy(connectorTokenAddress, 500, 1);595        let purchaseAmount = getConversionAmount(purchaseRes);596        let saleRes = await converter.sell(connectorTokenAddress2, purchaseAmount, 1);597        let saleAmount = getConversionAmount(saleRes);598        assert.equal(returnAmount, saleAmount);599    });600    it('should throw when attempting to get the return with an invalid from token adress', async () => {601        let converter = await initConverter(accounts, true);602        try {603            await converter.getReturn.call('0x0', connectorTokenAddress2, 500);604            assert(false, "didn't throw");605        }606        catch (error) {607            return utils.ensureException(error);608        }609    });610    it('should throw when attempting to get the return with an invalid to token address', async () => {611        let converter = await initConverter(accounts, true);612        try {613            await converter.getReturn.call(connectorTokenAddress, '0x0', 500);614            assert(false, "didn't throw");615        }616        catch (error) {617            return utils.ensureException(error);618        }619    });620    it('should throw when attempting to get the return with identical from/to addresses', async () => {621        let converter = await initConverter(accounts, true);622        try {623            await converter.getReturn.call(connectorTokenAddress, connectorTokenAddress, 500);624            assert(false, "didn't throw");625        }626        catch (error) {627            return utils.ensureException(error);628        }629    });630    it('should throw when attempting to get the purchase return while the converter is not active', async () => {631        let converter = await initConverter(accounts, false);632        try {633            await converter.getPurchaseReturn.call(connectorTokenAddress, 500);634            assert(false, "didn't throw");635        }636        catch (error) {637            return utils.ensureException(error);638        }639    });640    it('should throw when attempting to get the purchase return with a non connector address', async () => {641        let converter = await initConverter(accounts, true);642        try {643            await converter.getPurchaseReturn.call(tokenAddress, 500);644            assert(false, "didn't throw");645        }646        catch (error) {647            return utils.ensureException(error);648        }649    });650    it('should throw when attempting to get the purchase return while purchasing with the connector is disabled', async () => {651        let converter = await initConverter(accounts, true);652        await converter.disableConnectorPurchases(connectorTokenAddress, true);653        try {654            await converter.getPurchaseReturn.call(connectorTokenAddress, 500);655            assert(false, "didn't throw");656        }657        catch (error) {658            return utils.ensureException(error);659        }660    });661    it('should throw when attempting to get the sale return while the converter is not active', async () => {662        let converter = await initConverter(accounts, false);663        try {664            await converter.getSaleReturn.call(connectorTokenAddress, 500);665            assert(false, "didn't throw");666        }667        catch (error) {668            return utils.ensureException(error);669        }670    });671    it('should throw when attempting to get the sale return with a non connector address', async () => {672        let converter = await initConverter(accounts, true);673        try {674            await converter.getSaleReturn.call(tokenAddress, 500);675            assert(false, "didn't throw");676        }677        catch (error) {678            return utils.ensureException(error);679        }680    });681    it('verifies that convert returns a valid amount', async () => {682        let converter = await initConverter(accounts, true);683        await connectorToken.approve(converter.address, 500);684        let res = await converter.convert(connectorTokenAddress, tokenAddress, 500, 1);685        let conversionAmount = getConversionAmount(res);686        assert.isNumber(conversionAmount);687        assert.notEqual(conversionAmount, 0);688    });689    it('verifies that convert returns the same amount as buy when converting from a connector to the token', async () => {690        let converter = await initConverter(accounts, true);691        await connectorToken.approve(converter.address, 500);692        let conversionRes = await converter.convert(connectorTokenAddress, tokenAddress, 500, 1);693        let conversionAmount = getConversionAmount(conversionRes);694        assert.isNumber(conversionAmount);695        assert.notEqual(conversionAmount, 0);696        converter = await initConverter(accounts, true);697        await connectorToken.approve(converter.address, 500);698        let purchaseRes = await converter.buy(connectorTokenAddress, 500, 1);699        let purchaseAmount = getConversionAmount(purchaseRes);700        assert.equal(conversionAmount, purchaseAmount);701    });702    it('verifies that convert returns the same amount as sell when converting from the token to a connector', async () => {703        let converter = await initConverter(accounts, true);704        let conversionRes = await converter.convert(tokenAddress, connectorTokenAddress, 500, 1);705        let conversionAmount = getConversionAmount(conversionRes);706        assert.isNumber(conversionAmount);707        assert.notEqual(conversionAmount, 0);708        converter = await initConverter(accounts, true);709        let saleRes = await converter.sell(connectorTokenAddress, 500, 1);710        let saleAmount = getConversionAmount(saleRes);711        assert.equal(conversionAmount, saleAmount);712    });713    it('verifies that convert returns the same amount as buy -> sell when converting from connector 1 to connector 2', async () => {714        let converter = await initConverter(accounts, true);715        await connectorToken.approve(converter.address, 500);716        let conversionRes = await converter.convert(connectorTokenAddress, connectorTokenAddress2, 500, 1);717        let conversionAmount = getConversionAmount(conversionRes, 1);718        assert.isNumber(conversionAmount);719        assert.notEqual(conversionAmount, 0);720        converter = await initConverter(accounts, true);721        await connectorToken.approve(converter.address, 500);722        let purchaseRes = await converter.buy(connectorTokenAddress, 500, 1);723        let purchaseAmount = getConversionAmount(purchaseRes);724        let saleRes = await converter.sell(connectorTokenAddress2, purchaseAmount, 1);725        let saleAmount = getConversionAmount(saleRes);726        assert.equal(conversionAmount, saleAmount);727    });728    it('verifies that selling right after buying does not result in an amount greater than the original purchase amount', async () => {729        let converter = await initConverter(accounts, true);730        await connectorToken.approve(converter.address, 500);731        let purchaseRes = await converter.buy(connectorTokenAddress, 500, 1);732        let purchaseAmount = getConversionAmount(purchaseRes);733        let saleRes = await converter.sell(connectorTokenAddress, purchaseAmount, 1);734        let saleAmount = getConversionAmount(saleRes);735        assert(saleAmount <= 500);736    });737    it('verifies that buying right after selling does not result in an amount greater than the original sale amount', async () => {738        let converter = await initConverter(accounts, true);739        let saleRes = await converter.sell(connectorTokenAddress, 500, 1);740        let saleAmount = getConversionAmount(saleRes);741        await connectorToken.approve(converter.address, 500);742        let purchaseRes = await converter.buy(connectorTokenAddress, saleAmount, 1);743        let purchaseAmount = getConversionAmount(purchaseRes);744        assert(purchaseAmount <= 500);745    });746    it('should throw when attempting to convert with an invalid from token adress', async () => {747        let converter = await initConverter(accounts, true);748        await connectorToken.approve(converter.address, 500);749        try {750            await converter.convert('0x0', connectorTokenAddress2, 500, 1);751            assert(false, "didn't throw");752        }753        catch (error) {754            return utils.ensureException(error);755        }756    });757    it('should throw when attempting to convert with an invalid to token address', async () => {758        let converter = await initConverter(accounts, true);759        await connectorToken.approve(converter.address, 500);760        try {761            await converter.convert(connectorTokenAddress, '0x0', 500, 1);762            assert(false, "didn't throw");763        }764        catch (error) {765            return utils.ensureException(error);766        }767    });768    it('should throw when attempting to convert with identical from/to addresses', async () => {769        let converter = await initConverter(accounts, true);770        await connectorToken.approve(converter.address, 500);771        try {772            await converter.convert(connectorTokenAddress, connectorTokenAddress, 500, 0);773            assert(false, "didn't throw");774        }775        catch (error) {776            return utils.ensureException(error);777        }778    });779    it('should throw when attempting to convert with 0 minimum requested amount', async () => {780        let converter = await initConverter(accounts, true);781        await connectorToken.approve(converter.address, 500);782        try {783            await converter.convert(connectorTokenAddress, connectorTokenAddress2, 500, 2000);784            assert(false, "didn't throw");785        }786        catch (error) {787            return utils.ensureException(error);788        }789    });790    it('should throw when attempting to convert when the return is smaller than the minimum requested amount', async () => {791        let converter = await initConverter(accounts, true);792        await connectorToken.approve(converter.address, 500);793        try {794            await converter.convert(connectorTokenAddress, connectorTokenAddress2, 500, 2000);795            assert(false, "didn't throw");796        }797        catch (error) {798            return utils.ensureException(error);799        }800    });801    it('verifies balances after buy', async () => {802        let converter = await initConverter(accounts, true);803        let tokenPrevBalance = await token.balanceOf.call(accounts[0]);804        let connectorTokenPrevBalance = await connectorToken.balanceOf.call(accounts[0]);805        await connectorToken.approve(converter.address, 500);806        let purchaseRes = await converter.buy(connectorTokenAddress, 500, 1);807        let purchaseAmount = getConversionAmount(purchaseRes);808        let connectorTokenNewBalance = await connectorToken.balanceOf.call(accounts[0]);809        assert.equal(connectorTokenNewBalance.toNumber(), connectorTokenPrevBalance.minus(500).toNumber());810        let tokenNewBalance = await token.balanceOf.call(accounts[0]);811        assert.equal(tokenNewBalance.toNumber(), tokenPrevBalance.plus(purchaseAmount).toNumber());812    });813    it('should throw when attempting to buy while the converter is not active', async () => {814        let converter = await initConverter(accounts, false);815        await connectorToken.approve(converter.address, 500);816        try {817            await converter.buy(connectorTokenAddress, 500, 1);818            assert(false, "didn't throw");819        }820        catch (error) {821            return utils.ensureException(error);822        }823    });824    it('should throw when attempting to buy with a non connector address', async () => {825        let converter = await initConverter(accounts, true);826        await connectorToken.approve(converter.address, 500);827        try {828            await converter.buy(tokenAddress, 500, 1);829            assert(false, "didn't throw");830        }831        catch (error) {832            return utils.ensureException(error);833        }834    });835    it('should throw when attempting to buy while the purchase yields 0 return', async () => {836        let converter = await initConverter(accounts, true);837        await connectorToken.approve(converter.address, 500);838        try {839            await converter.buy(connectorTokenAddress, 0, 1);840            assert(false, "didn't throw");841        }842        catch (error) {843            return utils.ensureException(error);844        }845    });846    it('should throw when attempting to buy while conversions are disabled', async () => {847        let converter = await initConverter(accounts, true);848        await converter.disableConversions(true);849        await connectorToken.approve(converter.address, 500);850        try {851            await converter.buy(connectorTokenAddress, 500, 1);852            assert(false, "didn't throw");853        }854        catch (error) {855            return utils.ensureException(error);856        }857    });858    it('should throw when attempting to buy with gas price higher than the universal limit', async () => {859        let converter = await initConverter(accounts, true);860        await connectorToken.approve(converter.address, 500);861        try {862            await converter.buy(connectorTokenAddress, 500, 1, { gasPrice: gasPriceBad });863            assert(false, "didn't throw");864        }865        catch (error) {866            return utils.ensureException(error);867        }868    });869    it('should throw when attempting to buy with 0 minimum requested amount', async () => {870        let converter = await initConverter(accounts, true);871        await connectorToken.approve(converter.address, 500);872        try {873            await converter.buy(connectorTokenAddress, 500, 0);874            assert(false, "didn't throw");875        }876        catch (error) {877            return utils.ensureException(error);878        }879    });880    it('should throw when attempting to buy when the return is smaller than the minimum requested amount', async () => {881        let converter = await initConverter(accounts, true);882        await connectorToken.approve(converter.address, 500);883        try {884            await converter.buy(connectorTokenAddress, 500, 2000);885            assert(false, "didn't throw");886        }887        catch (error) {888            return utils.ensureException(error);889        }890    });891    it('should throw when attempting to buy while the connector purchases are disabled', async () => {892        let converter = await initConverter(accounts, true);893        await connectorToken.approve(converter.address, 500);894        await converter.disableConnectorPurchases(connectorTokenAddress, true);895        try {896            await converter.buy(connectorTokenAddress, 500, 1);897            assert(false, "didn't throw");898        }899        catch (error) {900            return utils.ensureException(error);901        }902    });903    it('should throw when attempting to buy without first approving the converter to transfer from the buyer account in the connector contract', async () => {904        let converter = await initConverter(accounts, true);905        try {906            await converter.buy(connectorTokenAddress, 500, 1);907            assert(false, "didn't throw");908        }909        catch (error) {910            return utils.ensureException(error);911        }912    });913    it('verifies balances after sell', async () => {914        let converter = await initConverter(accounts, true);915        let tokenPrevBalance = await token.balanceOf.call(accounts[0]);916        let connectorTokenPrevBalance = await connectorToken.balanceOf.call(accounts[0]);917        let saleRes = await converter.sell(connectorTokenAddress, 500, 1);918        let saleAmount = getConversionAmount(saleRes);919        let connectorTokenNewBalance = await connectorToken.balanceOf.call(accounts[0]);920        assert.equal(connectorTokenNewBalance.toNumber(), connectorTokenPrevBalance.plus(saleAmount).toNumber());921        let tokenNewBalance = await token.balanceOf.call(accounts[0]);922        assert.equal(tokenNewBalance.toNumber(), tokenPrevBalance.minus(500).toNumber());923    });924    it('should throw when attempting to sell while the converter is not active', async () => {925        let converter = await initConverter(accounts, false);926        try {927            await converter.sell(connectorTokenAddress, 500, 1);928            assert(false, "didn't throw");929        }930        catch (error) {931            return utils.ensureException(error);932        }933    });934    it('should throw when attempting to sell with a non connector address', async () => {935        let converter = await initConverter(accounts, true);936        try {937            await converter.sell(tokenAddress, 500, 1);938            assert(false, "didn't throw");939        }940        catch (error) {941            return utils.ensureException(error);942        }943    });944    it('should throw when attempting to sell while the sale yields 0 return', async () => {945        let converter = await initConverter(accounts, true);946        try {947            await converter.sell(connectorTokenAddress, 0, 1);948            assert(false, "didn't throw");949        }950        catch (error) {951            return utils.ensureException(error);952        }953    });954    it('should throw when attempting to sell while conversions are disabled', async () => {955        let converter = await initConverter(accounts, true);956        await converter.disableConversions(true);957        try {958            await converter.sell(connectorTokenAddress, 500, 1);959            assert(false, "didn't throw");960        }961        catch (error) {962            return utils.ensureException(error);963        }964    });965    it('should throw when attempting to sell with 0 minimum requested amount', async () => {966        let converter = await initConverter(accounts, true);967        try {968            await converter.sell(connectorTokenAddress, 500, 0);969            assert(false, "didn't throw");970        }971        catch (error) {972            return utils.ensureException(error);973        }974    });975    it('should throw when attempting to sell when the return is smaller than the minimum requested amount', async () => {976        let converter = await initConverter(accounts, true);977        try {978            await converter.sell(connectorTokenAddress, 500, 2000);979            assert(false, "didn't throw");980        }981        catch (error) {982            return utils.ensureException(error);983        }984    });985    it('should throw when attempting to sell with amount greater then the seller balance', async () => {986        let converter = await initConverter(accounts, true);987        try {988            await converter.sell(connectorTokenAddress, 30000, 1);989            assert(false, "didn't throw");990        }991        catch (error) {992            return utils.ensureException(error);993        }994    });...EditExtractorConverters.jsx
Source:EditExtractorConverters.jsx  
1/*2 * Copyright (C) 2020 Graylog, Inc.3 *4 * This program is free software: you can redistribute it and/or modify5 * it under the terms of the Server Side Public License, version 1,6 * as published by MongoDB, Inc.7 *8 * This program is distributed in the hope that it will be useful,9 * but WITHOUT ANY WARRANTY; without even the implied warranty of10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11 * Server Side Public License for more details.12 *13 * You should have received a copy of the Server Side Public License14 * along with this program. If not, see15 * <http://www.mongodb.com/licensing/server-side-public-license>.16 */17import PropTypes from 'prop-types';18import React from 'react';19import { Select } from 'components/common';20import { Row, Col, Panel, Button, Input } from 'components/bootstrap';21import {22  CSVConverterConfiguration,23  DateConverterConfiguration,24  FlexdateConverterConfiguration,25  HashConverterConfiguration,26  IpAnonymizerConverterConfiguration,27  LowercaseConverterConfiguration,28  NumericConverterConfiguration,29  SplitAndCountConverterConfiguration,30  SyslogPriFacilityConverterConfiguration,31  SyslogPriLevelConverterConfiguration,32  TokenizerConverterConfiguration,33  UppercaseConverterConfiguration,34  LookupTableConverterConfiguration,35} from 'components/extractors/converters_configuration';36import ExtractorUtils from 'util/ExtractorUtils';37class EditExtractorConverters extends React.Component {38  static propTypes = {39    extractorType: PropTypes.string.isRequired,40    converters: PropTypes.array.isRequired,41    onChange: PropTypes.func.isRequired,42  };43  constructor(props) {44    super(props);45    this.state = {46      displayedConverters: props.converters.map((converter) => converter.type),47      disabledConverters: {}, // Keep disabled converters configuration, so the user doesn't need to type it again48      selectedConverter: undefined,49    };50  }51  _onConverterSelect = (newValue) => {52    this.setState({ selectedConverter: newValue });53  };54  _onConverterAdd = () => {55    const { displayedConverters, selectedConverter } = this.state;56    const nextDisplayedConverters = displayedConverters.concat(selectedConverter);57    this.setState({ selectedConverter: undefined, displayedConverters: nextDisplayedConverters });58  };59  _onConverterChange = (converterType, converter) => {60    const { disabledConverters } = this.state;61    const { onChange } = this.props;62    if (converter) {63      const newDisabledConverters = disabledConverters;64      if ('converterType' in newDisabledConverters) {65        delete newDisabledConverters[converterType];66        this.setState({ disabledConverters: newDisabledConverters });67      }68    } else {69      const newDisabledConverters = disabledConverters;70      newDisabledConverters[converterType] = this._getConverterByType(converterType);71      this.setState({ disabledConverters: newDisabledConverters });72    }73    onChange(converterType, converter);74  };75  _getConverterOptions = () => {76    const { displayedConverters } = this.state;77    const converterOptions = [];78    Object.keys(ExtractorUtils.ConverterTypes).forEach((converterType) => {79      const type = ExtractorUtils.ConverterTypes[converterType];80      const disabled = displayedConverters.indexOf(type) !== -1;81      converterOptions.push({82        value: type,83        label: ExtractorUtils.getReadableConverterTypeName(type),84        disabled: disabled,85      });86    });87    return converterOptions;88  };89  _getConverterByType = (converterType) => {90    const { converters } = this.props;91    const currentConverter = converters.filter((converter) => converter.type === converterType)[0];92    return (currentConverter ? currentConverter.config : {});93  };94  _getConvertersConfiguration = () => {95    const { displayedConverters, disabledConverters } = this.state;96    const controls = displayedConverters.map((converterType) => {97      // Get converter configuration from disabledConverters if it was disabled98      let converterConfig = this._getConverterByType(converterType);99      if (Object.keys(converterConfig).length === 0 && ('converterType' in disabledConverters)) {100        converterConfig = disabledConverters[converterType];101      }102      switch (converterType) {103        case ExtractorUtils.ConverterTypes.NUMERIC:104          return (105            <NumericConverterConfiguration key={converterType}106                                           type={converterType}107                                           configuration={converterConfig}108                                           onChange={this._onConverterChange} />109          );110        case ExtractorUtils.ConverterTypes.DATE:111          return (112            <DateConverterConfiguration key={converterType}113                                        type={converterType}114                                        configuration={converterConfig}115                                        onChange={this._onConverterChange} />116          );117        case ExtractorUtils.ConverterTypes.HASH:118          return (119            <HashConverterConfiguration key={converterType}120                                        type={converterType}121                                        configuration={converterConfig}122                                        onChange={this._onConverterChange} />123          );124        case ExtractorUtils.ConverterTypes.SPLIT_AND_COUNT:125          return (126            <SplitAndCountConverterConfiguration key={converterType}127                                                 type={converterType}128                                                 configuration={converterConfig}129                                                 onChange={this._onConverterChange} />130          );131        case ExtractorUtils.ConverterTypes.IP_ANONYMIZER:132          return (133            <IpAnonymizerConverterConfiguration key={converterType}134                                                type={converterType}135                                                configuration={converterConfig}136                                                onChange={this._onConverterChange} />137          );138        case ExtractorUtils.ConverterTypes.SYSLOG_PRI_LEVEL:139          return (140            <SyslogPriLevelConverterConfiguration key={converterType}141                                                  type={converterType}142                                                  configuration={converterConfig}143                                                  onChange={this._onConverterChange} />144          );145        case ExtractorUtils.ConverterTypes.SYSLOG_PRI_FACILITY:146          return (147            <SyslogPriFacilityConverterConfiguration key={converterType}148                                                     type={converterType}149                                                     configuration={converterConfig}150                                                     onChange={this._onConverterChange} />151          );152        case ExtractorUtils.ConverterTypes.TOKENIZER:153          return (154            <TokenizerConverterConfiguration key={converterType}155                                             type={converterType}156                                             configuration={converterConfig}157                                             onChange={this._onConverterChange} />158          );159        case ExtractorUtils.ConverterTypes.CSV:160          return (161            <CSVConverterConfiguration key={converterType}162                                       type={converterType}163                                       configuration={converterConfig}164                                       onChange={this._onConverterChange} />165          );166        case ExtractorUtils.ConverterTypes.LOWERCASE:167          return (168            <LowercaseConverterConfiguration key={converterType}169                                             type={converterType}170                                             configuration={converterConfig}171                                             onChange={this._onConverterChange} />172          );173        case ExtractorUtils.ConverterTypes.UPPERCASE:174          return (175            <UppercaseConverterConfiguration key={converterType}176                                             type={converterType}177                                             configuration={converterConfig}178                                             onChange={this._onConverterChange} />179          );180        case ExtractorUtils.ConverterTypes.FLEXDATE:181          return (182            <FlexdateConverterConfiguration key={converterType}183                                            type={converterType}184                                            configuration={converterConfig}185                                            onChange={this._onConverterChange} />186          );187        case ExtractorUtils.ConverterTypes.LOOKUP_TABLE:188          return (189            <LookupTableConverterConfiguration key={converterType}190                                               type={converterType}191                                               configuration={converterConfig}192                                               onChange={this._onConverterChange} />193          );194        default:195          // eslint-disable-next-line no-console196          console.warn(`Converter type ${converterType} is not supported.`);197          return <></>;198      }199    });200    return controls;201  };202  render() {203    const { extractorType } = this.props;204    const { selectedConverter } = this.state;205    if (extractorType === ExtractorUtils.ExtractorTypes.GROK206      || extractorType === ExtractorUtils.ExtractorTypes.JSON) {207      return (208        <div className="form-group">209          <div className="col-md-offset-2 col-md-10">210            <Panel bsStyle="info" style={{ marginBottom: 0 }}>211              Cannot add converters to{' '}212              <em>{ExtractorUtils.getReadableExtractorTypeName(extractorType)}</em> extractors.213            </Panel>214          </div>215        </div>216      );217    }218    return (219      <div>220        <Input id="add-converter"221               label="Add converter"222               labelClassName="col-md-2"223               wrapperClassName="col-md-10"224               help="Add converters to transform the extracted value.">225          <Row className="row-sm">226            <Col md={11}>227              <Select id="add-converter"228                      placeholder="Select a converter"229                      options={this._getConverterOptions()}230                      value={selectedConverter}231                      onChange={this._onConverterSelect} />232            </Col>233            <Col md={1} className="text-right">234              <Button bsStyle="info" onClick={this._onConverterAdd} disabled={!selectedConverter}>235                Add236              </Button>237            </Col>238          </Row>239        </Input>240        {this._getConvertersConfiguration()}241      </div>242    );243  }244}...yaml_schema_v1beta.py
Source:yaml_schema_v1beta.py  
1# Copyright 2016 Google Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#    http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Definition for conversion between legacy YAML and the API JSON formats."""15from __future__ import absolute_import16from googlecloudsdk.third_party.appengine.admin.tools.conversion import converters as c17from googlecloudsdk.third_party.appengine.admin.tools.conversion import schema as s18SCHEMA = s.Message(19    api_config=s.Message(20        url=s.Value(converter=c.ToJsonString),21        login=s.Value(converter=c.EnumConverter('LOGIN')),22        secure=s.Value('security_level', converter=c.EnumConverter('SECURE')),23        auth_fail_action=s.Value(converter=c.EnumConverter('AUTH_FAIL_ACTION')),24        script=s.Value(converter=c.ToJsonString)),25    api_version=s.Value('runtime_api_version', converter=c.ToJsonString),26    auto_id_policy=s.Value('beta_settings',27                           lambda val: {'auto_id_policy': val}),28    automatic_scaling=s.Message(29        converter=c.ConvertAutomaticScaling,30        cool_down_period_sec=s.Value('cool_down_period',31                                     converter=c.SecondsToDuration),32        cpu_utilization=s.Message(33            target_utilization=s.Value(),34            aggregation_window_length_sec=s.Value('aggregation_window_length',35                                                  converter=c.SecondsToDuration)36        ),37        max_instances=s.Value('max_instances'),38        min_instances=s.Value('min_instances'),39        target_cpu_utilization=s.Value('target_cpu_utilization'),40        target_throughput_utilization=s.Value('target_throughput_utilization'),41        max_num_instances=s.Value('max_total_instances'),42        min_pending_latency=s.Value(converter=c.LatencyToDuration),43        min_idle_instances=s.Value(converter=44                                   c.StringToInt(handle_automatic=True)),45        max_idle_instances=s.Value(converter=46                                   c.StringToInt(handle_automatic=True)),47        max_pending_latency=s.Value(converter=c.LatencyToDuration),48        max_concurrent_requests=s.Value(converter=c.StringToInt()),49        min_num_instances=s.Value('min_total_instances'),50        target_network_sent_bytes_per_sec=s.Value(51            'target_sent_bytes_per_sec'),52        target_network_sent_packets_per_sec=s.Value(53            'target_sent_packets_per_sec'),54        target_network_received_bytes_per_sec=s.Value(55            'target_received_bytes_per_sec'),56        target_network_received_packets_per_sec=s.Value(57            'target_received_packets_per_sec'),58        target_disk_write_bytes_per_sec=s.Value(59            'target_write_bytes_per_sec'),60        target_disk_write_ops_per_sec=s.Value(61            'target_write_ops_per_sec'),62        target_disk_read_bytes_per_sec=s.Value(63            'target_read_bytes_per_sec'),64        target_disk_read_ops_per_sec=s.Value(65            'target_read_ops_per_sec'),66        target_request_count_per_sec=s.Value(),67        target_concurrent_requests=s.Value(),68        custom_metrics=s.RepeatedField(element=s.Message(69            metric_name=s.Value(converter=c.ToJsonString),70            target_type=s.Value(converter=c.ToJsonString),71            target_utilization=s.Value('target_utilization'),72            single_instance_assignment=s.Value('single_instance_assignment'),73            filter=s.Value(converter=c.ToJsonString))),74    ),75    basic_scaling=s.Message(76        idle_timeout=s.Value(converter=c.IdleTimeoutToDuration),77        max_instances=s.Value(converter=c.StringToInt())),78    beta_settings=s.Map(),79    default_expiration=s.Value(converter=c.ExpirationToDuration),80    endpoints_api_service=s.Message(81        name=s.Value(),82        rollout_strategy=s.Value(83            converter=c.ConvertEndpointsRolloutStrategyToEnum),84        config_id=s.Value(),85        trace_sampling=s.Value('disable_trace_sampling', converter=c.Not),86    ),87    env=s.Value(),88    env_variables=s.Map(),89    error_handlers=s.RepeatedField(element=s.Message(90        error_code=s.Value(converter=c.EnumConverter('ERROR_CODE')),91        file=s.Value('static_file', converter=c.ToJsonString),92        mime_type=s.Value(converter=c.ToJsonString))),93    # Restructure the handler after it's complete, since this is more94    # complicated than a simple rename.95    handlers=s.RepeatedField(element=s.Message(96        converter=c.ConvertUrlHandler,97        auth_fail_action=s.Value(converter=c.EnumConverter('AUTH_FAIL_ACTION')),98        static_dir=s.Value(converter=c.ToJsonString),99        secure=s.Value('security_level', converter=c.EnumConverter('SECURE')),100        redirect_http_response_code=s.Value(101            converter=c.EnumConverter('REDIRECT_HTTP_RESPONSE_CODE')),102        http_headers=s.Map(),103        url=s.Value('url_regex'),104        expiration=s.Value(converter=c.ExpirationToDuration),105        static_files=s.Value('path', converter=c.ToJsonString),106        script=s.Value('script_path', converter=c.ToJsonString),107        upload=s.Value('upload_path_regex', converter=c.ToJsonString),108        api_endpoint=s.Value(),109        application_readable=s.Value(),110        position=s.Value(),111        login=s.Value(converter=c.EnumConverter('LOGIN')),112        mime_type=s.Value(converter=c.ToJsonString),113        require_matching_file=s.Value())),114    health_check=s.Message(115        check_interval_sec=s.Value('check_interval',116                                   converter=c.SecondsToDuration),117        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),118        healthy_threshold=s.Value(),119        enable_health_check=s.Value('disable_health_check', converter=c.Not),120        unhealthy_threshold=s.Value(),121        host=s.Value(converter=c.ToJsonString),122        restart_threshold=s.Value()),123    liveness_check=s.Message(124        check_interval_sec=s.Value('check_interval',125                                   converter=c.SecondsToDuration),126        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),127        initial_delay_sec=s.Value('initial_delay',128                                  converter=c.SecondsToDuration),129        success_threshold=s.Value(),130        failure_threshold=s.Value(),131        path=s.Value(),132        host=s.Value(converter=c.ToJsonString)),133    readiness_check=s.Message(134        check_interval_sec=s.Value('check_interval',135                                   converter=c.SecondsToDuration),136        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),137        app_start_timeout_sec=s.Value('app_start_timeout',138                                      converter=c.SecondsToDuration),139        success_threshold=s.Value(),140        failure_threshold=s.Value(),141        path=s.Value(),142        host=s.Value(converter=c.ToJsonString)),143    inbound_services=s.RepeatedField(element=s.Value(144        converter=c.EnumConverter('INBOUND_SERVICE'))),145    instance_class=s.Value(converter=c.ToJsonString),146    libraries=s.RepeatedField(element=s.Message(147        version=s.Value(converter=c.ToJsonString),148        name=s.Value(converter=c.ToJsonString))),149    manual_scaling=s.Message(150        instances=s.Value(converter=c.StringToInt())),151    network=s.Message(152        instance_tag=s.Value(converter=c.ToJsonString),153        name=s.Value(converter=c.ToJsonString),154        subnetwork_name=s.Value(converter=c.ToJsonString),155        forwarded_ports=s.RepeatedField(element=s.Value(converter=156                                                        c.ToJsonString)),157        session_affinity=s.Value()158    ),159    vpc_access_connector=s.Message(160        name=s.Value(converter=c.ToJsonString),161    ),162    zones=s.RepeatedField(element=s.Value(converter=c.ToJsonString)),163    nobuild_files=s.Value('nobuild_files_regex', converter=c.ToJsonString),164    resources=s.Message(165        memory_gb=s.Value(),166        disk_size_gb=s.Value('disk_gb'),167        cpu=s.Value(),168        volumes=s.RepeatedField(element=s.Message(169            name=s.Value(converter=c.ToJsonString),170            volume_type=s.Value(converter=c.ToJsonString),171            size_gb=s.Value()))),172    runtime=s.Value(converter=c.ToJsonString),173    runtime_channel=s.Value(converter=c.ToJsonString),174    standard_websocket=s.Value('enable_standard_websocket'),175    threadsafe=s.Value(),176    version=s.Value('id', converter=c.ToJsonString),177    vm=s.Value(),...yaml_schema_v1.py
Source:yaml_schema_v1.py  
1# Copyright 2016 Google Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#    http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Definition for conversion between legacy YAML and the API JSON formats."""15from __future__ import absolute_import16from googlecloudsdk.third_party.appengine.admin.tools.conversion import converters as c17from googlecloudsdk.third_party.appengine.admin.tools.conversion import schema as s18SCHEMA = s.Message(19    api_config=s.Message(20        url=s.Value(converter=c.ToJsonString),21        login=s.Value(converter=c.EnumConverter('LOGIN')),22        secure=s.Value('security_level', converter=c.EnumConverter('SECURE')),23        auth_fail_action=s.Value(converter=c.EnumConverter('AUTH_FAIL_ACTION')),24        script=s.Value(converter=c.ToJsonString)),25    api_version=s.Value('runtime_api_version', converter=c.ToJsonString),26    auto_id_policy=s.Value('beta_settings',27                           lambda val: {'auto_id_policy': val}),28    automatic_scaling=s.Message(29        converter=c.ConvertAutomaticScaling,30        cool_down_period_sec=s.Value('cool_down_period',31                                     converter=c.SecondsToDuration),32        cpu_utilization=s.Message(33            target_utilization=s.Value(),34            aggregation_window_length_sec=s.Value('aggregation_window_length',35                                                  converter=c.SecondsToDuration)36        ),37        max_instances=s.Value('max_instances'),38        min_instances=s.Value('min_instances'),39        target_cpu_utilization=s.Value('target_cpu_utilization'),40        target_throughput_utilization=s.Value('target_throughput_utilization'),41        max_num_instances=s.Value('max_total_instances'),42        min_pending_latency=s.Value(converter=c.LatencyToDuration),43        min_idle_instances=s.Value(converter=44                                   c.StringToInt(handle_automatic=True)),45        max_idle_instances=s.Value(converter=46                                   c.StringToInt(handle_automatic=True)),47        max_pending_latency=s.Value(converter=c.LatencyToDuration),48        max_concurrent_requests=s.Value(converter=c.StringToInt()),49        min_num_instances=s.Value('min_total_instances'),50        target_network_sent_bytes_per_sec=s.Value(51            'target_sent_bytes_per_second'),52        target_network_sent_packets_per_sec=s.Value(53            'target_sent_packets_per_second'),54        target_network_received_bytes_per_sec=s.Value(55            'target_received_bytes_per_second'),56        target_network_received_packets_per_sec=s.Value(57            'target_received_packets_per_second'),58        target_disk_write_bytes_per_sec=s.Value(59            'target_write_bytes_per_second'),60        target_disk_write_ops_per_sec=s.Value(61            'target_write_ops_per_second'),62        target_disk_read_bytes_per_sec=s.Value(63            'target_read_bytes_per_second'),64        target_disk_read_ops_per_sec=s.Value(65            'target_read_ops_per_second'),66        target_request_count_per_sec=s.Value(67            'target_request_count_per_second'),68        target_concurrent_requests=s.Value()),69    basic_scaling=s.Message(70        idle_timeout=s.Value(converter=c.IdleTimeoutToDuration),71        max_instances=s.Value(converter=c.StringToInt())),72    beta_settings=s.Map(),73    default_expiration=s.Value(converter=c.ExpirationToDuration),74    endpoints_api_service=s.Message(75        name=s.Value(),76        rollout_strategy=s.Value(77            converter=c.ConvertEndpointsRolloutStrategyToEnum),78        config_id=s.Value(),79        trace_sampling=s.Value('disable_trace_sampling', converter=c.Not),80    ),81    env=s.Value(),82    env_variables=s.Map(),83    error_handlers=s.RepeatedField(element=s.Message(84        error_code=s.Value(converter=c.EnumConverter('ERROR_CODE')),85        file=s.Value('static_file', converter=c.ToJsonString),86        mime_type=s.Value(converter=c.ToJsonString))),87    # Restructure the handler after it's complete, since this is more88    # complicated than a simple rename.89    handlers=s.RepeatedField(element=s.Message(90        converter=c.ConvertUrlHandler,91        auth_fail_action=s.Value(converter=c.EnumConverter('AUTH_FAIL_ACTION')),92        static_dir=s.Value(converter=c.ToJsonString),93        secure=s.Value('security_level', converter=c.EnumConverter('SECURE')),94        redirect_http_response_code=s.Value(95            converter=c.EnumConverter('REDIRECT_HTTP_RESPONSE_CODE')),96        http_headers=s.Map(),97        url=s.Value('url_regex'),98        expiration=s.Value(converter=c.ExpirationToDuration),99        static_files=s.Value('path', converter=c.ToJsonString),100        script=s.Value('script_path', converter=c.ToJsonString),101        upload=s.Value('upload_path_regex', converter=c.ToJsonString),102        api_endpoint=s.Value(),103        application_readable=s.Value(),104        position=s.Value(),105        login=s.Value(converter=c.EnumConverter('LOGIN')),106        mime_type=s.Value(converter=c.ToJsonString),107        require_matching_file=s.Value())),108    health_check=s.Message(109        check_interval_sec=s.Value('check_interval',110                                   converter=c.SecondsToDuration),111        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),112        healthy_threshold=s.Value(),113        enable_health_check=s.Value('disable_health_check', converter=c.Not),114        unhealthy_threshold=s.Value(),115        host=s.Value(converter=c.ToJsonString),116        restart_threshold=s.Value()),117    liveness_check=s.Message(118        check_interval_sec=s.Value('check_interval',119                                   converter=c.SecondsToDuration),120        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),121        initial_delay_sec=s.Value('initial_delay',122                                  converter=c.SecondsToDuration),123        success_threshold=s.Value(),124        failure_threshold=s.Value(),125        path=s.Value(),126        host=s.Value(converter=c.ToJsonString)),127    readiness_check=s.Message(128        check_interval_sec=s.Value('check_interval',129                                   converter=c.SecondsToDuration),130        timeout_sec=s.Value('timeout', converter=c.SecondsToDuration),131        app_start_timeout_sec=s.Value('app_start_timeout',132                                      converter=c.SecondsToDuration),133        success_threshold=s.Value(),134        failure_threshold=s.Value(),135        path=s.Value(),136        host=s.Value(converter=c.ToJsonString)),137    inbound_services=s.RepeatedField(element=s.Value(138        converter=c.EnumConverter('INBOUND_SERVICE'))),139    instance_class=s.Value(converter=c.ToJsonString),140    libraries=s.RepeatedField(element=s.Message(141        version=s.Value(converter=c.ToJsonString),142        name=s.Value(converter=c.ToJsonString))),143    manual_scaling=s.Message(144        instances=s.Value(converter=c.StringToInt())),145    network=s.Message(146        instance_tag=s.Value(converter=c.ToJsonString),147        name=s.Value(converter=c.ToJsonString),148        subnetwork_name=s.Value(converter=c.ToJsonString),149        forwarded_ports=s.RepeatedField(element=s.Value(converter=150                                                        c.ToJsonString))),151    zones=s.RepeatedField(element=s.Value(converter=c.ToJsonString)),152    nobuild_files=s.Value('nobuild_files_regex', converter=c.ToJsonString),153    resources=s.Message(154        memory_gb=s.Value(),155        disk_size_gb=s.Value('disk_gb'),156        cpu=s.Value(),157        volumes=s.RepeatedField(element=s.Message(158            name=s.Value(converter=c.ToJsonString),159            volume_type=s.Value(converter=c.ToJsonString),160            size_gb=s.Value()))),161    runtime=s.Value(converter=c.ToJsonString),162    runtime_channel=s.Value(converter=c.ToJsonString),163    standard_websocket=s.Value('enable_standard_websocket'),164    threadsafe=s.Value(),165    version=s.Value('id', converter=c.ToJsonString),166    vm=s.Value(),...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
