def test_deploying_contract_with_error_during_deploy_sanity_check(project_dir, THROWER): """ Just a sanity check that the `Thrower` contract can be successfully deployed. """ project = Project() chain = project.get_chain("testrpc") exports = [] with chain: Thrower = chain.web3.eth.contract(**THROWER) @click.command() def wrapper(): math_contract = deploy_contract_and_verify( chain, contract_name="Thrower", base_contract_factory=Thrower, deploy_arguments=[False] ) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code == 0 assert "Verified contract bytecode" in result.output assert "No runtime available" not in result.output
def test_initialized(): """Crowdsale is properly initialized with given parameters.""" project_dir = DATACOIN_PATH project = Project(project_dir, create_config_file=True) with project.get_chain('tester') as chain: beneficiary = chain.web3.eth.accounts[3] multisig = chain.web3.eth.accounts[4] # Initialize crowdsale args = [beneficiary, multisig, 0] crowdsale, _ = chain.provider.get_or_deploy_contract('Crowdsale', deploy_args=args) # Initialize token args = [beneficiary] # Owner set token, _ = chain.provider.get_or_deploy_contract('DataCoin', deploy_args=args) assert crowdsale.call().tokenReward( ) == '0x0000000000000000000000000000000000000000' crowdsale.transact({"from": beneficiary}).setToken(token.address) assert crowdsale.call().tokenReward( ) != '0x0000000000000000000000000000000000000000' token.transact({ "from": beneficiary }).approve(crowdsale.address, 440000000) assert token.call().balanceOf(beneficiary) == 500000000 assert token.call().totalSupply() == 500000000 assert token.call().owner().lower() == beneficiary assert token.call().allowance(beneficiary, crowdsale.address) == 440000000 assert token.call().owner().lower() == crowdsale.call().beneficiary( ).lower()
def test_deploying_contract_with_error_during_deploy_sanity_check(project_dir, THROWER): """ Just a sanity check that the `Thrower` contract can be successfully deployed. """ project = Project() chain = project.get_chain('testrpc') exports = [] with chain: Thrower = chain.web3.eth.contract(**THROWER) @click.command() def wrapper(): math_contract = deploy_contract_and_verify( chain, contract_name='Thrower', base_contract_factory=Thrower, deploy_arguments=[False], ) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code == 0 assert "Verified contract bytecode" in result.output assert "No runtime available" not in result.output
def test_with_successful_deploy_sans_runtime_bytecode(project_dir, MATH): project = Project() chain = project.get_chain("testrpc") exports = [] with chain: Math = chain.web3.eth.contract(abi=MATH["abi"], code=MATH["code"]) assert not Math.code_runtime @click.command() def wrapper(): math_contract = deploy_contract_and_verify(chain, contract_name="Math", base_contract_factory=Math) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code == 0, str(result.output) + "\n" + str(result.exception) assert len(exports) == 1 math_contract = exports[0] expected = "~~{0}~~".format(math_contract.address) assert expected in result.output assert "Verified contract bytecode" not in result.output assert "No runtime available" in result.output
def test_with_successful_deploy_sans_runtime_bytecode(project_dir, MATH): project = Project() chain = project.get_chain('testrpc') exports = [] with chain: Math = chain.web3.eth.contract( abi=MATH['abi'], code=MATH['code'], ) assert not Math.code_runtime @click.command() def wrapper(): math_contract = deploy_contract_and_verify( chain, contract_name='Math', base_contract_factory=Math, ) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code == 0, str(result.output) + '\n' + str(result.exception) assert len(exports) == 1 math_contract = exports[0] expected = "~~{0}~~".format(math_contract.address) assert expected in result.output assert "Verified contract bytecode" not in result.output assert "No runtime available" in result.output
def test_project_tester_chain(project_dir): project = Project(project_dir) chain = project.get_chain('tester') with chain as running_tester_chain: web3 = running_tester_chain.web3 assert web3.version.node.startswith('TestRPC')
def test_project_testrpc_chain(project_dir): project = Project(project_dir, create_config_file=True) chain = project.get_chain('testrpc') with chain as running_tester_chain: web3 = running_tester_chain.web3 assert web3.version.node.startswith('TestRPC')
def test_project_tester_chain(project_dir): project = Project(project_dir) chain = project.get_chain('tester') with chain as running_tester_chain: web3 = running_tester_chain.web3 assert web3.clientVersion.startswith('EthereumTester')
def test_project_temp_chain(project_dir): project = Project() chain = project.get_chain('temp') with chain as running_temp_chain: web3 = running_temp_chain.web3 assert hasattr(running_temp_chain, 'geth') assert web3.version.node.startswith('Geth')
def test_project_contract_factories_property(project_dir, write_project_file, MATH): write_project_file('contracts/Math.sol', MATH['source']) project = Project() with project.get_chain('testrpc') as chain: assert len(chain.contract_factories.Math.abi) == len(MATH['abi']) assert len(chain.contract_factories.Math.code) > 2 assert len(chain.contract_factories.Math.code_runtime) > 2
def test_buy_tokens(): """Sending ETH successfully buys tokens.""" start = 1488294000 end = 1490112000 project_dir = DATACOIN_PATH project = Project(project_dir, create_config_file=True) with project.get_chain('tester') as chain: beneficiary = chain.web3.eth.accounts[3] multisig = chain.web3.eth.accounts[4] customer = chain.web3.eth.accounts[1] # Initialize crowdsale args = [beneficiary, multisig, 0] crowdsale, _ = chain.provider.get_or_deploy_contract('Crowdsale', deploy_args=args) # Initialize token args = [beneficiary] # Owner set token, _ = chain.provider.get_or_deploy_contract('DataCoin', deploy_args=args) assert crowdsale.call().tokenReward( ) == '0x0000000000000000000000000000000000000000' crowdsale.transact({"from": beneficiary}).setToken(token.address) assert crowdsale.call().tokenReward( ) != '0x0000000000000000000000000000000000000000' token.transact({ "from": beneficiary }).approve(crowdsale.address, 440000000) # Doing open crowdsale crowdsale.transact().setCurrent(start + 1) token.transact().setCurrent(start + 1) chain.web3.eth.sendTransaction({ "from": customer, "to": crowdsale.address, "value": Web3.toWei(20, "ether"), "gas": 250000, }) # We get ERC-20 event events = token.pastEvents("Transfer").get() assert len(events) == 1 e = events[0] assert e["args"]["to"].lower() == customer assert e["args"]["from"].lower() == beneficiary assert e["args"]["value"] == 24000 # We get crowdsale event events = crowdsale.pastEvents("FundTransfer").get() assert len(events) == 1 e = events[0] assert e["args"]["backer"].lower() == customer assert e["args"]["amount"] == Web3.toWei(20, "ether") assert e["args"]["amountRaised"] == Web3.toWei(20, "ether")
def local_chain(project_dir, write_project_file): write_project_file('populus.ini', '[chain:local]') project = Project() chain = project.get_chain('local') # create a new account create_new_account(chain.geth.data_dir, b'a-test-password') return chain
def local_chain(project_dir): project = Project() project.config['chains.local.chain.class'] = 'populus.chain.LocalGethChain' project.config['chains.local.web3.provider.class'] = 'web3.providers.ipc.IPCProvider' project.config['chains.local.contracts.backends.Memory.$ref'] = 'contracts.backends.Memory' project.write_config() chain = project.get_chain('local') return chain
def test_project_morden_chain(project_dir): project = Project() chain = project.get_chain('morden') with chain as running_morden_chain: web3 = running_morden_chain.web3 assert web3.version.node.startswith('Geth') running_morden_chain.wait.for_block(block_number=1, timeout=180) block_1 = web3.eth.getBlock(1) assert block_1['hash'] == TESTNET_BLOCK_1_HASH
def local_chain(project_dir): project = Project() project.config['chains.local.chain.class'] = 'populus.chain.LocalGethChain' project.config[ 'chains.local.web3.provider.class'] = 'web3.providers.ipc.IPCProvider' project.config['chains.local.web3.provider.settings.ipc_path'] = ( get_geth_ipc_path(get_local_chain_datadir(project.project_dir, 'local'))) project.write_config() chain = project.get_chain('local') return chain
def test_external_rpc_chain(project_dir, write_project_file): project = Project() with project.get_chain('testrpc') as chain: web3 = chain.web3 registrar = chain.registrar project.config[ 'chains.external.chain.class'] = 'populus.chain.ExternalChain' project.config['chains.external.registrar'] = registrar.address project.config[ 'chains.external.web3.provider.class'] = 'web3.providers.rpc.HTTPProvider' project.config[ 'chains.external.web3.provider.settings.endpoint_uri'] = 'http://127.0.0.1:{0}'.format( chain.port) project.write_config() with project.get_chain('external') as external_chain: ext_web3 = external_chain.web3 ext_registrar = external_chain.registrar assert ext_web3.eth.coinbase == web3.eth.coinbase assert registrar.address == ext_registrar.address
def test_select_account_with_invalid_option(project_dir, stdin): project = Project() chain = project.get_chain('temp') @click.command() def wrapper(): account = select_account(chain) print("~~{0}~~".format(account)) with chain: runner = CliRunner() result = runner.invoke(wrapper, [], input="{0}\n".format(stdin)) assert result.exit_code != 0
def test_external_ipc_chain(project_dir, write_project_file): project = Project() with project.get_chain('temp') as chain: web3 = chain.web3 chain.wait.for_unlock(timeout=30) registrar = chain.registrar project.config[ 'chains.external.chain.class'] = 'populus.chain.ExternalChain' project.config['chains.external.registrar'] = registrar.address project.config[ 'chains.external.web3.provider.class'] = 'web3.providers.ipc.IPCProvider' project.config[ 'chains.external.web3.provider.settings.ipc_path'] = chain.geth.ipc_path project.write_config() with project.get_chain('external') as external_chain: ext_web3 = external_chain.web3 ext_registrar = external_chain.registrar assert ext_web3.eth.coinbase == web3.eth.coinbase assert registrar.address == ext_registrar.address
def test_dates(): """Dates match given in the project material.""" project_dir = DATACOIN_PATH project = Project(project_dir, create_config_file=True) with project.get_chain('tester') as chain: beneficiary = chain.web3.eth.accounts[3] multisig = chain.web3.eth.accounts[4] customer = chain.web3.eth.accounts[1] # Initialize crowdsale args = [beneficiary, multisig, 0] crowdsale, _ = chain.provider.get_or_deploy_contract('Crowdsale', deploy_args=args) # Initialize token args = [beneficiary] # Owner set token, _ = chain.provider.get_or_deploy_contract('DataCoin', deploy_args=args) assert crowdsale.call().tokenReward( ) == '0x0000000000000000000000000000000000000000' crowdsale.transact({"from": beneficiary}).setToken(token.address) assert crowdsale.call().tokenReward( ) != '0x0000000000000000000000000000000000000000' token.transact({ "from": beneficiary }).approve(crowdsale.address, 440000000) deadlines = [ crowdsale.call().deadlines(0), crowdsale.call().deadlines(1), crowdsale.call().deadlines(2), crowdsale.call().deadlines(3) ] print("Start is {}".format( datetime.datetime.fromtimestamp(crowdsale.call().start(), tz=datetime.timezone.utc))) for idx, deadline in enumerate(deadlines): print("Deadline {} is {}".format( idx, datetime.datetime.fromtimestamp(deadline, tz=datetime.timezone.utc))) print("Token is transferable {}".format( datetime.datetime.fromtimestamp(token.call().startTime(), tz=datetime.timezone.utc))) assert token.call().startTime() == deadlines[-1]
def test_external_ipc_chain(project_dir, write_project_file): project = Project() with project.get_chain('temp') as chain: web3 = chain.web3 chain.wait.for_unlock(timeout=30) registrar = chain.registrar ini_contents = '\n'.join(( "[chain:external]", "is_external=True", "ipc_path={ipc_path}".format(ipc_path=chain.geth.ipc_path), "registrar={registrar}".format(registrar=registrar.address), )) write_project_file('populus.ini', ini_contents) project.reload_config() with project.get_chain('external') as external_chain: ext_web3 = external_chain.web3 ext_registrar = external_chain.registrar assert ext_web3.eth.coinbase == web3.eth.coinbase assert registrar.address == ext_registrar.address
def test_external_rpc_chain(project_dir, write_project_file): project = Project() with project.get_chain('testrpc') as chain: web3 = chain.web3 registrar = chain.registrar ini_contents = '\n'.join(( "[chain:external]", "is_external=True", "provider=web3.providers.rpc.RPCProvider", "port={port}".format(port=chain.port), "registrar={registrar}".format(registrar=registrar.address), )) write_project_file('populus.ini', ini_contents) project.reload_config() with project.get_chain('external') as external_chain: ext_web3 = external_chain.web3 ext_registrar = external_chain.registrar assert ext_web3.eth.coinbase == web3.eth.coinbase assert registrar.address == ext_registrar.address
def test_project_local_chain_rpc(project_dir, write_project_file): write_project_file('populus.ini', '\n'.join(( '[chain:custom-chain]', 'provider=web3.providers.rpc.RPCProvider', ))) project = Project() chain = project.get_chain('custom-chain') with chain as running_local_chain: web3 = running_local_chain.web3 assert web3.version.node.startswith('Geth') running_local_chain.wait.for_block(block_number=1, timeout=180) block_1 = web3.eth.getBlock(1) assert block_1['hash'] != MAINNET_BLOCK_1_HASH assert block_1['hash'] != TESTNET_BLOCK_1_HASH assert block_1['miner'] == web3.eth.coinbase
def test_request_account_unlock_with_bad_password(project_dir): project = Project() chain = project.get_chain('temp') # create 3 new accounts account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) @click.command() def wrapper(): request_account_unlock(chain, account, None) with chain: assert is_account_locked(chain.web3, account) runner = CliRunner() result = runner.invoke(wrapper, [], input="bad-password\n") assert result.exit_code != 0 assert is_account_locked(chain.web3, account)
def test_chain_web3_is_preconfigured_with_default_from(project_dir, write_project_file): write_project_file('populus.ini', '[chain:local]') project = Project() chain = project.get_chain('local') default_account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) project.config.set('chain:local', 'default_account', default_account) project.write_config() with chain: web3 = chain.web3 assert len(web3.eth.accounts) == 2 assert web3.eth.defaultAccount == default_account assert web3.eth.coinbase != default_account
def test_project_local_chain_ipc(project_dir): project = Project() project.config['chains.local.chain.class'] = 'populus.chain.LocalGethChain' project.config[ 'chains.local.web3.provider.class'] = 'web3.providers.ipc.IPCProvider' project.write_config() chain = project.get_chain('local') with chain as running_local_chain: web3 = running_local_chain.web3 assert web3.version.node.startswith('Geth') running_local_chain.wait.for_block(block_number=1, timeout=180) block_1 = web3.eth.getBlock(1) assert block_1['hash'] != MAINNET_BLOCK_1_HASH assert block_1['hash'] != TESTNET_BLOCK_1_HASH assert block_1['miner'] == web3.eth.coinbase
def test_initializing_no_choices(project_dir, write_project_file): write_project_file('populus.ini', "[chain:local_a]") project = Project() with project.get_chain('local_a') as chain: project.config.set('chain:local_a', 'deploy_from', chain.web3.eth.coinbase) project.write_config() runner = CliRunner() result = runner.invoke( main, ['chain', 'init', 'local_a'], ) assert result.exit_code == 0, result.output + str(result.exception) updated_project = Project() assert 'registrar' in updated_project.config.chains['local_a'] assert 'deploy_from' in updated_project.config.chains['local_a']
def test_request_account_unlock_with_bad_password(project_dir): project = Project() chain = project.get_chain('temp') # create 3 new accounts account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) @click.command() def wrapper(): request_account_unlock(chain, account, None) with chain: assert is_account_locked(chain.web3, account) runner = CliRunner() result = runner.invoke(wrapper, [], input="bad-password\n") assert result.exit_code != 0 assert is_account_locked(chain.web3, account)
def test_deploying_contract_with_error_during_deploy(project_dir, THROWER): project = Project() chain = project.get_chain("testrpc") exports = [] with chain: Thrower = chain.web3.eth.contract(**THROWER) @click.command() def wrapper(): math_contract = deploy_contract_and_verify( chain, contract_name="Thrower", base_contract_factory=Thrower, deploy_arguments=[True] ) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code != 0
def test_chain_web3_is_preconfigured_with_default_from(project_dir, write_project_file): write_project_file('populus.ini', '[chain:local]') project = Project() chain = project.get_chain('local') default_account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) project.config.set('chain:local', 'default_account', default_account) project.write_config() with chain: web3 = chain.web3 assert len(web3.eth.accounts) == 2 assert web3.eth.defaultAccount == default_account assert web3.eth.coinbase != default_account
def test_get_price_tiers(): """Price tiers match given dates.""" project_dir = DATACOIN_PATH project = Project(project_dir, create_config_file=True) with project.get_chain('tester') as chain: beneficiary = chain.web3.eth.accounts[3] multisig = chain.web3.eth.accounts[4] customer = chain.web3.eth.accounts[1] # Initialize crowdsale args = [beneficiary, multisig, 0] crowdsale, _ = chain.provider.get_or_deploy_contract('Crowdsale', deploy_args=args) # Initialize token args = [beneficiary] # Owner set token, _ = chain.provider.get_or_deploy_contract('DataCoin', deploy_args=args) assert crowdsale.call().tokenReward( ) == '0x0000000000000000000000000000000000000000' crowdsale.transact({"from": beneficiary}).setToken(token.address) assert crowdsale.call().tokenReward( ) != '0x0000000000000000000000000000000000000000' token.transact({ "from": beneficiary }).approve(crowdsale.address, 440000000) deadlines = [1488297600, 1488902400, 1489507200, 1490112000] prices = [ 833333333333333, 909090909090909, 952380952380952, 1000000000000000 ] for idx, deadline in enumerate(deadlines): crowdsale.transact().setCurrent(deadline - 1) assert crowdsale.call().getPrice() == prices[idx] # Post last deadline prcie crowdsale.transact().setCurrent(deadlines[-1] + 1) assert crowdsale.call().getPrice() == 1000000000000000
def test_select_account_helper_with_accounts(project_dir, account_index): project = Project() chain = project.get_chain('temp') # create 3 new accounts create_new_account(chain.geth.data_dir, b'a-test-password') @click.command() def wrapper(): account = select_account(chain) print("~~{0}~~".format(account)) with chain: account = chain.web3.eth.accounts[account_index] runner = CliRunner() result = runner.invoke(wrapper, [], input="{0}\n".format(account)) assert result.exit_code == 0 expected = "~~{0}~~".format(account) assert expected in result.output
def test_initializing_local_chain(project_dir, write_project_file): write_project_file('populus.ini', "[chain:local_a]") project = Project() runner = CliRunner() chain = project.get_chain('local_a') deploy_from = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) with chain: chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30) funding_txn_hash = chain.web3.eth.sendTransaction({ 'from': chain.web3.eth.coinbase, 'to': deploy_from, 'value': int(chain.web3.toWei(10, 'ether')), }) chain.wait.for_receipt(funding_txn_hash, timeout=60) result = runner.invoke( main, ['chain', 'init'], input=(( "local_a\n" # choose chain. "{0}\n" # pick deploy account. "Y\n" # set account as default "a-test-password\n" # unlock account "".format(deploy_from)))) assert result.exit_code == 0, result.output + str(result.exception) updated_project = Project() assert 'registrar' in updated_project.config.chains['local_a'] assert 'deploy_from' in updated_project.config.chains['local_a']
def test_initializing_local_chain(project_dir, write_project_file): write_project_file('populus.ini', "[chain:local_a]") project = Project() runner = CliRunner() chain = project.get_chain('local_a') deploy_from = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) with chain: chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30) funding_txn_hash = chain.web3.eth.sendTransaction({ 'from': chain.web3.eth.coinbase, 'to': deploy_from, 'value': int(chain.web3.toWei(10, 'ether')), }) chain.wait.for_receipt(funding_txn_hash, timeout=60) result = runner.invoke( main, ['chain', 'init'], input=(( "local_a\n" # choose chain. "{0}\n" # pick deploy account. "Y\n" # set account as default "a-test-password\n" # unlock account "".format(deploy_from) )) ) assert result.exit_code == 0, result.output + str(result.exception) updated_project = Project() assert 'registrar' in updated_project.config.chains['local_a'] assert 'deploy_from' in updated_project.config.chains['local_a']
def web3() -> Web3: """A py.test fixture to get a Web3 interface to a temporary geth instance. This is session scoped fixture. Geth is launched only once during the beginning of the test run. Geth will have huge instant balance on its coinbase account. Geth will also mine our transactions on artificially low difficulty level. :yield: :py:class:`web3.Web3` instance """ project = Project() # Configure where Populus can find our contracts.json build_dir = os.path.join(os.getcwd(), "websauna", "wallet", "ethereum") project.config["populus.build_dir"] = build_dir project.config["chains.temp.provider.class"] = "web3.providers.rpc.RPCProvider" # This returns with project.get_chain("temp") as geth_proc: web3 = geth_proc.web3 # Allow access to sendTransaction() to use coinbase balance # to deploy contracts. Password is from py-geth # default_blockchain_password file. Assume we don't # run tests for more than 9999 seconds coinbase = web3.eth.coinbase success = web3.personal.unlockAccount( coinbase, passphrase="this-is-not-a-secure-password", duration=9999) assert success, "Could not unlock test geth coinbase account" yield web3
def test_deploying_contract_with_error_during_deploy(project_dir, THROWER): project = Project() chain = project.get_chain('testrpc') exports = [] with chain: Thrower = chain.web3.eth.contract(**THROWER) @click.command() def wrapper(): math_contract = deploy_contract_and_verify( chain, contract_name='Thrower', base_contract_factory=Thrower, deploy_arguments=[True], ) exports.append(math_contract) print("~~{0}~~".format(math_contract.address)) runner = CliRunner() result = runner.invoke(wrapper, []) assert result.exit_code != 0
def test_project_local_chain_rpc(project_dir): project = Project() rpc_port = str(get_open_port()) project.config['chains.local.chain.class'] = 'populus.chain.LocalGethChain' project.config['chains.local.chain.settings.rpc_port'] = rpc_port project.config[ 'chains.local.web3.provider.class'] = 'web3.providers.rpc.HTTPProvider' project.config[ 'chains.local.web3.provider.settings.endpoint_uri'] = "http://127.0.0.1:{0}".format( rpc_port) project.write_config() chain = project.get_chain('local') with chain as running_local_chain: web3 = running_local_chain.web3 assert web3.version.node.startswith('Geth') running_local_chain.wait.for_block(block_number=1, timeout=180) block_1 = web3.eth.getBlock(1) assert block_1['hash'] != MAINNET_BLOCK_1_HASH assert block_1['hash'] != TESTNET_BLOCK_1_HASH assert block_1['miner'] == web3.eth.coinbase
def test_select_account_helper_with_accounts(project_dir, account_index): project = Project() chain = project.get_chain('temp') # create 3 new accounts create_new_account(chain.geth.data_dir, b'a-test-password') create_new_account(chain.geth.data_dir, b'a-test-password') create_new_account(chain.geth.data_dir, b'a-test-password') @click.command() def wrapper(): account = select_account(chain) print("~~{0}~~".format(account)) with chain: account = chain.web3.eth.accounts[account_index] runner = CliRunner() result = runner.invoke(wrapper, [], input="{0}\n".format(account)) assert result.exit_code == 0 expected = "~~{0}~~".format(account) assert expected in result.output
def test_migrate_cmd(project_dir, write_project_file, MATH): class MigrationA(migrations.Migration): migration_id = '0001_deploy_math' dependencies = [] operations = [ migrations.DeployContract('Math'), ] compiled_contracts = { 'Math': MATH, } class MigrationB(migrations.Migration): migration_id = '0002_increment' dependencies = ['0001_deploy_math'] operations = [ migrations.TransactContract( contract_name='Math', method_name='increment', arguments=[3], contract_address=migrations.Address.defer(key='contract/Math'), timeout=30, ), ] compiled_contracts = { 'Math': MATH, } write_project_file('contracts/Math.sol', MATH['source']) write_project_file('migrations/__init__.py') migration_0001_path = os.path.join( project_dir, 'migrations', '0001_deploy_math.py', ) with open(migration_0001_path, 'w') as migration_0001: write_migration(migration_0001, MigrationA) migration_0002_path = os.path.join( project_dir, 'migrations', '0002_increment.py', ) with open(migration_0002_path, 'w') as migration_0002: write_migration(migration_0002, MigrationB) write_project_file('populus.ini', '[chain:local_a]') project = Project() # sanity assert len(project.migrations) == 2 with project.get_chain('local_a') as chain: chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30) project.config.set('chain:local_a', 'deploy_from', chain.web3.eth.coinbase) RegistrarFactory = get_registrar(web3=chain.web3) deploy_transaction_hash = RegistrarFactory.deploy() registrar_address = chain.wait.for_contract_address(deploy_transaction_hash, timeout=60) project.config.set('chain:local_a', 'registrar', registrar_address) project.write_config() runner = CliRunner() result = runner.invoke(main, ['migrate', 'local_a']) assert result.exit_code == 0, result.output + str(result.exception) with project.get_chain('local_a') as chain: registrar = chain.registrar math_address = registrar.call().getAddress('contract/Math') Math = chain.contract_factories.Math(address=math_address) assert Math.call().counter() == 3
def web3() -> Web3: """A py.test fixture to get a Web3 interface to a temporary geth instance. This is session scoped fixture. Geth is launched only once during the beginning of the test run. Geth will have huge instant balance on its coinbase account. Geth will also mine our transactions on artificially low difficulty level. :yield: :py:class:`web3.Web3` instance """ project = Project() # Project is configured using populus.config.Config class # which is a subclass of Python config parser. # Instead of reading .ini file, here we dynamically # construct the configuration. project.config = Config() # Settings come for [populus] section of the config. project.config.add_section("populus") # Configure where Populus can find our contracts.json build_dir = os.path.join(os.getcwd(), "websauna", "wallet", "ethereum") project.config.set("populus", "build_dir", build_dir) chain_kwargs = { # Force RPC provider instead of default IPC one "provider": RPCProvider, "wait_for_dag_timeout": 20*60, "overrides": { "jitvm": "false", } } # This returns with project.get_chain("temp", **chain_kwargs) as geth_proc: web3 = geth_proc.web3 # Use compatible web3.py version assert web3._requestManager.provider.network_timeout web3._requestManager.provider.network_timeout = 10 web3._requestManager.provider.connection_timeout = 10 # Allow access to sendTransaction() to use coinbase balance # to deploy contracts. Password is from py-geth # default_blockchain_password file. Assume we don't # run tests for more than 9999 seconds coinbase = web3.eth.coinbase success = web3.personal.unlockAccount( coinbase, passphrase="this-is-not-a-secure-password", duration=9999) assert success, "Could not unlock test geth coinbase account" yield web3
def test_show_chain_sync_progress(): project = Project() main_chain = project.get_chain('temp', no_discover=False, max_peers=None, port=str(get_open_port()), rpc_enabled=False, ws_enabled=False) with main_chain: sync_chain = project.get_chain('temp', no_discover=False, max_peers=None, mine=False, miner_threads=None, port=str(get_open_port()), rpc_enabled=False, ws_enabled=False) main_chain_data_dir = main_chain.geth.data_dir sync_chain_data_dir = sync_chain.geth.data_dir main_genesis_file = os.path.join(main_chain_data_dir, 'genesis.json') sync_genesis_file = os.path.join(sync_chain_data_dir, 'genesis.json') main_chaindata_dir = os.path.join(main_chain_data_dir, 'chaindata') sync_chaindata_dir = os.path.join(sync_chain_data_dir, 'chaindata') os.remove(sync_genesis_file) shutil.rmtree(sync_chaindata_dir) shutil.copyfile(main_genesis_file, sync_genesis_file) shutil.copytree(main_chaindata_dir, sync_chaindata_dir) block_numbers = [] runner = CliRunner() @click.command() def wrapper(): block_numbers.append(sync_chain.web3.eth.blockNumber) show_chain_sync_progress(sync_chain) block_numbers.append(sync_chain.web3.eth.blockNumber) with sync_chain: main_node_info = main_chain.web3.admin.nodeInfo main_enode = "enode://{node_id}@127.0.0.1:{node_port}".format( node_id=main_node_info['id'], node_port=main_node_info['ports']['listener'], ) sync_node_info = sync_chain.web3.admin.nodeInfo sync_enode = "enode://{node_id}@127.0.0.1:{node_port}".format( node_id=sync_node_info['id'], node_port=sync_node_info['ports']['listener'], ) main_chain.wait.for_block(BLOCK_DELTA, timeout=BLOCK_DELTA * 4) main_chain_start_block = main_chain.web3.eth.blockNumber sync_chain_start_block = sync_chain.web3.eth.blockNumber assert main_chain_start_block - sync_chain_start_block >= BLOCK_DELTA // 2 assert sync_chain.web3.net.peerCount == 0 sync_chain.web3.admin.addPeer(main_enode) main_chain.web3.admin.addPeer(sync_enode) sync_chain.wait.for_peers(timeout=60) result = runner.invoke(wrapper, []) assert result.exit_code == 0 assert len(block_numbers) == 2 start_block = block_numbers[0] end_block = block_numbers[1] assert start_block <= 1 assert end_block >= 20