Skip to content
This repository has been archived by the owner on May 23, 2023. It is now read-only.

Using pyethereum.tester

Li Xuanji edited this page Oct 9, 2018 · 10 revisions

It will be documented as if you did:

from ethereum.tools import tester
from ethereum import utils
chain = tester.Chain()
contract = chain.contract(...)

Interacting with the blockchain

  • tester.Chain() creates a new test-blockchain with a genesis block.
    • Returns the chain tester.
  • tester.State() creates a new test-state with the genesis state passed in.
    • Can be used for lightweight testing when you don't need mining & block logic.
    • Returns the state tester.
  • chain.tx(private_key, to, value, data=b'') sends a transaction using the given private key to the given address with the given value and data.
    • Returns the return value of the transaction execution
  • chain.contract(code, language='evm') creates a contract with the given code, in the given language. Acceptable languages are evm, serpent, solidity and viper. If any of the latter three are used, returns an ABIContract object, of which you can then call functions.
  • contract.<method_name>(...args, sender=k0) creates a transaction from sender to the deployed contract calling <method_name> with args.
  • chain.mine(n=1, coinbase=a0) pretend-mines n times, with coinbase the blockmaker.
    • Returns nothing; (None)
  • chain.change_head(parent, coinbase=a0) changes the tester's head_state to build on the block that you pass in as parent.
    • Returns nothing; (None)
  • chain.snapshot() returns a snapshot object.
  • chain.revert(snapshot) takes a snapshot as input and reverts to that snapshot.

Convenience accounts

The tester module generates ten keys and ten addresses: tester.k0 ... tester.k9 and their corresponding addresses tester.a0 ... tester.a9.

Getting data out of the state

  • chain.head_state returns the State object at the head. You can then access various methods of this including get_code(addr), get_balance(addr), get_nonce(addr) and get_storage_at(addr, key).
  • chain.block.transactions returns the transactions included in the block
  • chain.head_state.receipts returns the receipts

Example

from ethereum.tools import tester
c = tester.Chain()
x = c.contract("""
def foo(x):
    return x + 5
""", language='serpent')
assert x.foo(2) == 7
bn = c.head_state.block_number
c.mine(5)
assert c.head_state.block_number == bn + 5
x2 = c.contract("""
data moose

def increment_moose():
    self.moose += 1
    return self.moose
""", language='serpent')
assert x2.increment_moose() == 1
assert x2.increment_moose() == 2
Clone this wiki locally