Python eth_tester.EthereumTester() Examples

The following are 30 code examples of eth_tester.EthereumTester(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_tester , or try the search function .
Example #1
Source File: web3_service.py    From django-eth-events with MIT License 6 votes vote down vote up
def __init__(self, provider,
                 max_workers: int=10, max_batch_requests: int=10, slow_provider_timeout: int=400):
        """
        :param node_uri: Node http address. If uri starts with 'test', EthereumTester will be used
        :param max_workers: Max workers for multithread calls. 1 -> No multithread
        :param max_batch_requests: Max requests in the same batch for RPC
        :param self.slow_provider_timeout: Timeout for time lasting requests (like filters)
        """
        self.provider = provider
        self.max_workers = max_workers
        self.max_batch_requests = max_batch_requests
        self.slow_provider_timeout = slow_provider_timeout
        self.node_uri = self.get_node_uri()

        self.web3 = Web3(provider)
        self.web3_slow = Web3(self.slow_provider)
        self.http_session = requests.session()

        # If rinkeby, inject Geth PoA middleware
        # http://web3py.readthedocs.io/en/latest/middleware.html#geth-style-proof-of-authority
        try:
            if int(self.web3.net.version) == RINKEBY_CHAIN_ID:
                self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
        # For tests using dummy connections (like IPC)
        except (UnhandledRequest, ConnectionError, ConnectionRefusedError, FileNotFoundError):
            pass 
Example #2
Source File: test_donation.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def test_manager_account_could_withdraw_money(web3, chain):
    donation, _ = chain.provider.get_or_deploy_contract('Donation')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    donatur_name = b'Taylor Swift'
    set_txn_hash = donation.functions.donate(donatur_name).transact({'from': account2, 'value': web3.toWei('1', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    initial_balance = web3.eth.getBalance(web3.eth.coinbase)
    set_txn_hash = donation.functions.withdraw_donation().transact({'from': web3.eth.coinbase})
    chain.wait.for_receipt(set_txn_hash)

    after_withdraw_balance = web3.eth.getBalance(web3.eth.coinbase)

    assert abs((after_withdraw_balance - initial_balance) - web3.toWei('1', 'ether')) < web3.toWei('10', 'gwei') 
Example #3
Source File: test_crowd_sale_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def test_purchase_token(web3, chain):
    crowd_sale_token, _ = chain.provider.get_or_deploy_contract('CrowdSaleToken')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]
    account3 = t.get_accounts()[2]

    set_txn_hash = crowd_sale_token.functions.__default__().transact({'from': account2, 'value': web3.toWei('1', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    set_txn_hash = crowd_sale_token.functions.__default__().transact({'from': account3, 'value': web3.toWei('2', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    ethBalance_account2 = crowd_sale_token.functions.ethBalances(account2).call()
    balance_account2 = crowd_sale_token.functions.balanceOf(account2).call()
    amountRaised = crowd_sale_token.functions.amountRaised().call()
    balance_account1 = crowd_sale_token.functions.balanceOf(web3.eth.coinbase).call()
    assert ethBalance_account2 == web3.toWei('1', 'ether')
    assert balance_account2 == 100
    assert amountRaised == web3.toWei('3', 'ether')
    assert balance_account1 == (10000 - 100 - 200) 
Example #4
Source File: test_pyevm.py    From eth-tester with MIT License 6 votes vote down vote up
def test_custom_virtual_machines():
    if not is_pyevm_available():
        pytest.skip("PyEVM is not available")

    backend = PyEVMBackend(vm_configuration=(
        (0, FrontierVM),
        (3, MuirGlacierVM),
    ))

    # This should be a FrontierVM block
    VM_at_2 = backend.chain.get_vm_class_for_block_number(2)
    # This should be a MuirGlacier block
    VM_at_3 = backend.chain.get_vm_class_for_block_number(3)

    assert issubclass(VM_at_2, FrontierVM)
    assert not issubclass(VM_at_2, MuirGlacierVM)
    assert issubclass(VM_at_3, MuirGlacierVM)

    # Right now, just test that EthereumTester doesn't crash
    # Maybe some more sophisticated test to make sure the VMs are set correctly?
    # We should to make sure the VM config translates all the way to the main
    #   tester, maybe with a custom VM that hard-codes some block value? that can
    #   be found with tester.get_block_by_number()?
    EthereumTester(backend=backend) 
Example #5
Source File: test_simple_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def test_transfer(web3, chain):
    simple_token, _ = chain.provider.get_or_deploy_contract('SimpleToken')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    old_balance = simple_token.functions.balances(account2).call()
    assert old_balance == 0

    set_txn_hash = simple_token.functions.transfer(account2, 10).transact({'from': web3.eth.coinbase})
    chain.wait.for_receipt(set_txn_hash)

    sender_new_balance = simple_token.functions.balances(web3.eth.coinbase).call()
    assert sender_new_balance == 9990
    destination_new_balance = simple_token.functions.balances(account2).call()
    assert destination_new_balance == 10 
Example #6
Source File: test_pyevm.py    From eth-tester with MIT License 6 votes vote down vote up
def test_override_genesis_state(self):
        state_overrides = {"balance": to_wei(900000, "ether")}
        test_accounts = 3

        # Initialize PyEVM backend with custom genesis state
        genesis_state = PyEVMBackend._generate_genesis_state(
            overrides=state_overrides, num_accounts=test_accounts
        )

        # Test the correct number of accounts are created with the specified balance override
        pyevm_backend = PyEVMBackend(genesis_state=genesis_state)
        assert len(pyevm_backend.account_keys) == test_accounts
        for private_key in pyevm_backend.account_keys:
            account = private_key.public_key.to_canonical_address()
            balance = pyevm_backend.get_balance(account=account)
            assert balance == state_overrides["balance"]

        # Test integration with EthereumTester
        tester = EthereumTester(backend=pyevm_backend)
        for private_key in pyevm_backend.account_keys:
            account = private_key.public_key.to_checksum_address()
            balance = tester.get_balance(account=account)
            assert balance == state_overrides["balance"] 
Example #7
Source File: test_pyevm.py    From eth-tester with MIT License 6 votes vote down vote up
def test_override_genesis_parameters(self):

        # Establish a custom gas limit
        param_overrides = {"gas_limit": 4750000}
        block_one_gas_limit = param_overrides['gas_limit']

        # Initialize PyEVM backend with custom genesis parameters
        genesis_params = PyEVMBackend._generate_genesis_params(
            overrides=param_overrides
        )
        pyevm_backend = PyEVMBackend(genesis_parameters=genesis_params)
        genesis_block = pyevm_backend.get_block_by_number(0)
        assert genesis_block["gas_limit"] == param_overrides["gas_limit"]
        genesis_block = pyevm_backend.get_block_by_number(1)
        assert genesis_block["gas_limit"] == block_one_gas_limit

        # Integrate with EthereumTester
        tester = EthereumTester(backend=pyevm_backend)
        genesis_block = tester.get_block_by_number(0)
        assert genesis_block["gas_limit"] == param_overrides["gas_limit"]
        genesis_block = tester.get_block_by_number(1)
        assert genesis_block["gas_limit"] == block_one_gas_limit 
Example #8
Source File: test_erc20_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def test_transfer(web3, chain):
    erc20_token, _ = chain.provider.get_or_deploy_contract('ERC20Token')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    old_balance = erc20_token.functions.balanceOf(account2).call()
    assert old_balance == 0

    set_txn_hash = erc20_token.functions.transfer(account2, 10).transact({'from': web3.eth.coinbase})
    chain.wait.for_receipt(set_txn_hash)

    sender_new_balance = erc20_token.functions.balanceOf(web3.eth.coinbase).call()
    assert sender_new_balance == 999990
    destination_new_balance = erc20_token.functions.balanceOf(account2).call()
    assert destination_new_balance == 10 
Example #9
Source File: test_stable_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def test_freeze_balance(web3, chain):
    stable_coin, _ = chain.provider.get_or_deploy_contract('StableCoin')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]
    account3 = t.get_accounts()[2]

    set_txn_hash = stable_coin.functions.transfer(account2, 10).transact()
    chain.wait.for_receipt(set_txn_hash)

    set_txn_hash = stable_coin.functions.transfer(account3, 1).transact({'from': account2})
    chain.wait.for_receipt(set_txn_hash)

    set_txn_hash = stable_coin.functions.freezeBalance(account2, True).transact()
    chain.wait.for_receipt(set_txn_hash)

    with pytest.raises(eth_tester.exceptions.TransactionFailed):
        stable_coin.functions.transfer(account3, 1).transact({'from': account2})

    set_txn_hash = stable_coin.functions.freezeBalance(account2, False).transact()
    chain.wait.for_receipt(set_txn_hash)

    set_txn_hash = stable_coin.functions.transfer(account3, 1).transact({'from': account2})
    chain.wait.for_receipt(set_txn_hash) 
Example #10
Source File: contracts.py    From raiden-contracts with MIT License 6 votes vote down vote up
def get_web3(eth_tester: EthereumTester, deployer_key: PrivateKey) -> Web3:
    """Returns an initialized Web3 instance"""
    provider = EthereumTesterProvider(eth_tester)
    web3 = Web3(provider)

    # add faucet account to tester
    eth_tester.add_account(deployer_key.to_hex())

    # make faucet rich
    eth_tester.send_transaction(
        {
            "from": eth_tester.get_accounts()[0],
            "to": private_key_to_address(deployer_key.to_hex()),
            "gas": 21000,
            "value": FAUCET_ALLOWANCE,
        }
    )

    return web3 
Example #11
Source File: web3_fixtures.py    From raiden-contracts with MIT License 6 votes vote down vote up
def web3(ethereum_tester: EthereumTester) -> Web3:
    """Returns an initialized Web3 instance"""
    provider = EthereumTesterProvider(ethereum_tester)
    web3 = Web3(provider)
    # Improve test speed by skipping the gas cost estimation.
    web3.eth.estimateGas = lambda txn: int(5.2e6)  # type: ignore  # pylint: disable=E1101

    # add faucet account to tester
    ethereum_tester.add_account(FAUCET_PRIVATE_KEY.hex())

    # make faucet rich
    ethereum_tester.send_transaction(
        {
            "from": ethereum_tester.get_accounts()[0],
            "to": FAUCET_ADDRESS,
            "gas": 21000,
            "value": FAUCET_ALLOWANCE,
        }
    )

    # Enable strict type checks
    web3.enable_strict_bytes_type_checking()

    return web3 
Example #12
Source File: utils.py    From raiden-contracts with MIT License 6 votes vote down vote up
def create_account(web3: Web3, ethereum_tester: EthereumTester) -> Callable:
    def get(privkey: Optional[PrivateKey] = None) -> HexAddress:
        if not privkey:
            privkey = get_random_privkey()
        address = private_key_to_address(privkey)

        if not any((is_same_address(address, x) for x in ethereum_tester.get_accounts())):
            # account has not been added to ethereum_tester, yet
            ethereum_tester.add_account(privkey.hex())

        for faucet in web3.eth.accounts[:10]:
            try:
                web3.eth.sendTransaction(
                    {"from": faucet, "to": address, "value": Wei(1 * int(units["finney"]))}
                )
                break
            except TransactionFailed:
                continue
        return address

    return get 
Example #13
Source File: web3_fixtures.py    From raiden-contracts with MIT License 5 votes vote down vote up
def ethereum_tester(patch_genesis_gas_limit: None) -> EthereumTester:  # pylint: disable=W0613
    """Returns an instance of an Ethereum tester"""
    return EthereumTester(PyEVMBackend()) 
Example #14
Source File: utils.py    From raiden-contracts with MIT License 5 votes vote down vote up
def get_private_key(ethereum_tester: EthereumTester) -> Callable:
    def get(account_address: HexAddress) -> PrivateKey:
        keys = [
            key.to_bytes()
            for key in ethereum_tester.backend.account_keys
            if is_same_address(key.public_key.to_address(), account_address)
        ]
        assert len(keys) == 1
        return keys[0]

    return get 
Example #15
Source File: conftest.py    From trinity with MIT License 5 votes vote down vote up
def tester():
    return EthereumTester(PyEVMBackend()) 
Example #16
Source File: web3_service.py    From django-eth-events with MIT License 5 votes vote down vote up
def get_provider_from_uri(node_uri: str):
        if node_uri.startswith('http'):
            return HTTPProvider(node_uri)
        elif node_uri.startswith('ipc'):
            path = node_uri.replace('ipc://', '')
            return IPCProvider(ipc_path=path)
        elif node_uri.startswith('test'):
            return EthereumTesterProvider(EthereumTester())
        else:
            raise ValueError('%s uri is not supported. Must start by http, ipc, or test' % node_uri) 
Example #17
Source File: test_pyevm.py    From eth-tester with MIT License 5 votes vote down vote up
def eth_tester():
    if not is_pyevm_available():
        pytest.skip("PyEVM is not available")
    backend = PyEVMBackend()
    return EthereumTester(backend=backend) 
Example #18
Source File: base_conftest.py    From vyper with Apache License 2.0 5 votes vote down vote up
def tester():
    custom_genesis = PyEVMBackend._generate_genesis_params(overrides={"gas_limit": 4500000})
    backend = PyEVMBackend(genesis_parameters=custom_genesis)
    return EthereumTester(backend=backend) 
Example #19
Source File: conftest.py    From vyper with Apache License 2.0 5 votes vote down vote up
def get_contract_module():
    """
    This fixture is used for Hypothesis tests to ensure that
    the same contract is called over multiple runs of the test.
    """
    tester = EthereumTester()
    w3 = Web3(EthereumTesterProvider(tester))
    w3.eth.setGasPriceStrategy(zero_gas_price_strategy)

    def get_contract_module(source_code, *args, **kwargs):
        return _get_contract(w3, source_code, *args, **kwargs)

    return get_contract_module 
Example #20
Source File: test_django_eth_events.py    From pm-trading-db with MIT License 5 votes vote down vote up
def setUp(self):
        self.web3 = Web3Service(provider=EthereumTesterProvider(EthereumTester())).web3
        self.provider = self.web3.providers[0]
        self.web3.eth.defaultAccount = self.web3.eth.coinbase

        # Mock web3
        self.daemon = DaemonFactory()
        self.ipfs = Ipfs()

        self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 1000000}

        # create oracles
        centralized_contract_factory = self.web3.eth.contract(abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')),
                                                              bytecode=centralized_oracle_bytecode)
        tx_hash = centralized_contract_factory.constructor().transact()
        self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt(tx_hash).get('contractAddress')
        self.centralized_oracle_factory = self.web3.eth.contract(self.centralized_oracle_factory_address,
                                                                 abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')))

        self.contracts = [
            {
                'NAME': 'Centralized Oracle Factory',
                'EVENT_ABI': load_json_file(abi_file_path('CentralizedOracleFactory.json')),
                'EVENT_DATA_RECEIVER': 'chainevents.event_receivers.CentralizedOracleFactoryReceiver',
                'ADDRESSES': [self.centralized_oracle_factory_address[2::]]
            }
        ]

        self.listener_under_test = EventListener(contract_map=self.contracts,
                                                 provider=self.provider) 
Example #21
Source File: test_event_listener.py    From django-ethereum-events with MIT License 5 votes vote down vote up
def setUpTestData(cls):
        cls.eth_tester = EthereumTester(backend=PyEVMBackend())
        cls.provider = EthereumTesterProvider(cls.eth_tester)
        cls.web3 = Web3(cls.provider)

        # Deploy the Bank test contract
        cls.bank_abi = json.loads(BANK_ABI_RAW)
        bank_bytecode = BANK_BYTECODE

        Bank = cls.web3.eth.contract(abi=cls.bank_abi, bytecode=bank_bytecode)
        tx_hash = Bank.constructor().transact()
        tx_receipt = cls.web3.eth.waitForTransactionReceipt(tx_hash)
        cls.bank_address = tx_receipt.contractAddress
        cls.bank_contract = cls.web3.eth.contract(address=cls.bank_address, abi=cls.bank_abi)

        # Deploy the Claim test contract
        cls.claim_abi = json.loads(CLAIM_ABI_RAW)
        claim_bytecode = CLAIM_BYTECODE

        Claim = cls.web3.eth.contract(abi=cls.claim_abi, bytecode=claim_bytecode)
        tx_hash = Claim.constructor().transact()
        tx_receipt = cls.web3.eth.waitForTransactionReceipt(tx_hash)
        cls.claim_address = tx_receipt.contractAddress
        cls.claim_contract = cls.web3.eth.contract(address=cls.claim_address, abi=cls.claim_abi)

        # Take a snapshot of this state so far
        cls.clean_state_snapshot = cls.eth_tester.take_snapshot() 
Example #22
Source File: test_decoder.py    From django-ethereum-events with MIT License 5 votes vote down vote up
def setUpTestData(cls):
        super(DecoderTestCase, cls).setUpTestData()

        cls.eth_tester = EthereumTester(backend=PyEVMBackend())
        cls.provider = EthereumTesterProvider(cls.eth_tester)
        cls.web3 = Web3(cls.provider)

        # Deploy the Bank test contract
        cls.bank_abi = json.loads(BANK_ABI_RAW)
        bank_bytecode = BANK_BYTECODE

        Bank = cls.web3.eth.contract(abi=cls.bank_abi, bytecode=bank_bytecode)
        tx_hash = Bank.constructor().transact()
        tx_receipt = cls.web3.eth.waitForTransactionReceipt(tx_hash)
        cls.bank_address = tx_receipt.contractAddress
        cls.bank_contract = cls.web3.eth.contract(address=cls.bank_address, abi=cls.bank_abi)

        # Take a snapshot of this state so far
        cls.clean_state_snapshot = cls.eth_tester.take_snapshot()

        # Log contains a LogDeposit event with the following arguments
        # owner: self.web3.eth.accounts[0]
        # amount: 1 ether
        with open(cls.events_log_file) as log_file:
            test_logs = json.load(log_file)

        # From web3 v3 to web3 v4, the topics as we as the blockHash, transactionHash are
        # wrapped with the HexBytes class.
        cls.logs = cls._proccess_logs(test_logs) 
Example #23
Source File: test_donation.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_other_account_could_not_withdraw_money(web3, chain):
    donation, _ = chain.provider.get_or_deploy_contract('Donation')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    donatur_name = b'Taylor Swift'
    set_txn_hash = donation.functions.donate(donatur_name).transact({'from': account2, 'value': web3.toWei('1', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    with pytest.raises(eth_tester.exceptions.TransactionFailed):
        donation.functions.withdraw_donation().transact({'from': account2}) 
Example #24
Source File: test_crowd_sale_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_withdrawal(web3, chain):
    crowd_sale_token, _ = chain.provider.get_or_deploy_contract('CrowdSaleToken')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    beforeCrowdsaleEthBalanceAccount2 = web3.eth.getBalance(account2)
    beforeCrowdsaleEthBalanceAccount1 = web3.eth.getBalance(web3.eth.coinbase)

    set_txn_hash = crowd_sale_token.functions.__default__().transact({'from': account2, 'value': web3.toWei('40', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    # move forward 101 days
    web3.testing.timeTravel(int(time.time()) + 3600 * 24 * 101)
    web3.testing.mine(1)

    set_txn_hash = crowd_sale_token.functions.checkGoalReached().transact()
    chain.wait.for_receipt(set_txn_hash)

    set_txn_hash = crowd_sale_token.functions.safeWithdrawal().transact()
    chain.wait.for_receipt(set_txn_hash)

    afterCrowdsaleEthBalanceAccount2 = web3.eth.getBalance(account2)
    afterCrowdsaleEthBalanceAccount1 = web3.eth.getBalance(web3.eth.coinbase)

    assert abs(beforeCrowdsaleEthBalanceAccount2 - afterCrowdsaleEthBalanceAccount2 - web3.toWei('40', 'ether')) < web3.toWei('1', 'gwei')
    assert abs(afterCrowdsaleEthBalanceAccount1 - beforeCrowdsaleEthBalanceAccount1 - web3.toWei('40', 'ether')) < web3.toWei('1', 'gwei') 
Example #25
Source File: test_crowd_sale_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_refund(web3, chain):
    crowd_sale_token, _ = chain.provider.get_or_deploy_contract('CrowdSaleToken')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    beforeCrowdsaleEthBalanceAccount2 = web3.eth.getBalance(account2)

    set_txn_hash = crowd_sale_token.functions.__default__().transact({'from': account2, 'value': web3.toWei('5', 'ether')})
    chain.wait.for_receipt(set_txn_hash)

    # move forward 101 days
    web3.testing.timeTravel(int(time.time()) + 3600 * 24 * 101)
    web3.testing.mine(1)

    set_txn_hash = crowd_sale_token.functions.checkGoalReached().transact()
    chain.wait.for_receipt(set_txn_hash)

    ethBalanceAccount2 = crowd_sale_token.functions.ethBalances(account2).call()
    assert ethBalanceAccount2 == web3.toWei('5', 'ether')

    set_txn_hash = crowd_sale_token.functions.safeWithdrawal().transact({'from': account2})
    chain.wait.for_receipt(set_txn_hash)

    afterCrowdsaleEthBalanceAccount2 = web3.eth.getBalance(account2)

    assert abs(beforeCrowdsaleEthBalanceAccount2 - web3.toWei('5', 'ether') - afterCrowdsaleEthBalanceAccount2) < web3.toWei('1', 'gwei')

    ethBalanceAccount2 = crowd_sale_token.functions.ethBalances(account2).call()
    assert ethBalanceAccount2 == 0 
Example #26
Source File: test_simple_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_fail_transfer(web3, chain):
    simple_token, _ = chain.provider.get_or_deploy_contract('SimpleToken')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    with pytest.raises(eth_tester.exceptions.TransactionFailed):
        simple_token.functions.transfer(web3.eth.coinbase, 10).transact({'from': account2}) 
Example #27
Source File: test_erc20_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_approve(web3, chain):
    erc20_token, _ = chain.provider.get_or_deploy_contract('ERC20Token')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    allowance = erc20_token.functions.allowance(web3.eth.coinbase, account2).call()
    assert allowance == 0

    set_txn_hash = erc20_token.functions.approve(account2, 100).transact({'from': web3.eth.coinbase})
    chain.wait.for_receipt(set_txn_hash)

    allowance = erc20_token.functions.allowance(web3.eth.coinbase, account2).call()
    assert allowance == 100 
Example #28
Source File: test_erc20_token.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_fail_transfer(web3, chain):
    erc20_token, _ = chain.provider.get_or_deploy_contract('ERC20Token')

    t = eth_tester.EthereumTester()
    account2 = t.get_accounts()[1]

    with pytest.raises(eth_tester.exceptions.TransactionFailed):
        erc20_token.functions.transfer(web3.eth.coinbase, 10).transact({'from': account2}) 
Example #29
Source File: test_videos_sharing.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def test_upload_video(web3, chain):
    video_sharing, _ = chain.provider.get_or_deploy_contract('VideosSharing')

    t = eth_tester.EthereumTester()
    video_uploader = t.get_accounts()[1]

    index = video_sharing.functions.latest_videos_index(video_uploader).call()
    assert index == 0

    upload_video(video_sharing, chain, video_uploader, b'video-ipfs-path', b"video title")

    index = video_sharing.functions.latest_videos_index(video_uploader).call()
    path = video_sharing.functions.videos_path(video_uploader, 0).call()
    title = video_sharing.functions.videos_title(video_uploader, 0).call()
    assert index == 1
    assert path == b'video-ipfs-path'
    assert title == b"video title"

    upload_video(video_sharing, chain, video_uploader, b'video-ipfs-path2', b"video title2")

    index = video_sharing.functions.latest_videos_index(video_uploader).call()
    path = video_sharing.functions.videos_path(video_uploader, 1).call()
    title = video_sharing.functions.videos_title(video_uploader, 1).call()
    assert index == 2
    assert path == b'video-ipfs-path2'
    assert title == b"video title2"

    events = video_sharing.events.UploadVideo.createFilter(fromBlock=0).get_all_entries()

    assert events[0]['args']['_user'] == video_uploader
    assert events[0]['args']['_index'] == 0

    assert events[1]['args']['_user'] == video_uploader
    assert events[1]['args']['_index'] == 1 
Example #30
Source File: test_event_listener_functions.py    From django-eth-events with MIT License 5 votes vote down vote up
def setUp(self):
        self.daemon = DaemonFactory()
        self.el = EventListener(provider=EthereumTesterProvider(EthereumTester()))
        self.provider = self.el.provider
        self.el.web3.eth.defaultAccount = self.el.web3.eth.coinbase
        self.el.decoder.reset()
        self.maxDiff = None