Repository: vyperlang/vyper

Issue:
State leakage across test runs when using parrellization
### What is wrong.

The tests at `tests/examples/safe_remote_purchase/test_safe_remote_purchase.py` fail when run using `pytest-xdist` to parallelize test runs.

```
    def test_abort(w3, assert_tx_failed, check_balance, get_contract, contract_code):
        a0, a1, a2 = w3.eth.accounts[:3]
        c = get_contract(contract_code, value=2)
        # Only sender can trigger refund
        assert_tx_failed(lambda: c.abort(transact={'from': a2}))
        # Refund works correctly
        c.abort(transact={'from': a0, 'gasPrice': 0})
>       assert check_balance() == (INIT_BAL_a0 - w3.toWei(2, 'ether'), INIT_BAL_a1)
E       assert (100000000000...0000000000000) == (9999980000000...0000000000000)
E         At index 0 diff: 1000000000000000000000000 != 999998000000000000000000
E         Use -v to get the full diff

tests/examples/safe_remote_purchase/test_safe_remote_purchase.py:62: AssertionError
```

replicate by installing `pytest-xdist` and running with

```
pytest tests/examples/safe_remote_purchase/test_safe_remote_purchase.py -n 2
```

It's likely this isn't deterministic and you may need to run the full suite.

### How can it be fixed.

Figure out where statefulness is leaking across test runs and fix it.


Discussion:
Updating the `w3` and `tester` fixtures in `tests/conftest.py` did not remedy this.
`patch_log_filter_remove`?
Whilst we are optimising tests, is there a way to make eth tester mine blocks without doing PoW (PoA maybe?). I think this is a huge bottle neck atm. I adjusted the difficulty lower but hardly had any effect. I just know for alot of the example tests forwarding blocks takes most of the tests time. Parrallelisation should be the last optimization we make.
@jacqueswww yes.  It's likely that `eth-tester` isn't taking advantage of this since it's relatively new.  We have an API for doing this (docs are broken so I'm linking you to the test suite where it's used)

https://github.com/ethereum/py-evm/blob/master/tests/core/builder-tools/test_chain_construction.py#L133

the `eth-tester` chain that the `PyEVMBackend` uses should be updated to use some version of this API to disable the POW check.
> Parrallelisation should be the last optimization we make.

Can you explain the reasoning behind this?  In most CI environments I've been able to gain an easy 2-3x speed increase simply by parallelizing with `pytest-xdist`.
@pipermeriam By last resort, I mean it should be the last step we switch on after all other optimisations have been made.

 So in any program I write, I see parrallelisation as the last resort, because it's cheating right? You are hiding the aggregate work that gets done. :-) Yeah I am a old riser and believe in the adage of `if you want fast programs, give a programmer a slow computer` :-P

@pipermeriam Thinking of it some more, lately I have realized that I actually get far more consistent metrics on single core performance accross all processors and platforms. So it make it so much easier to have a quick yardstick guage. This is because the actual performance increase per core is tiny across processor generations.
@jacqueswww I don't see the reasoning in either of those to not enable paralellization in the CI environment.

- Parallelization isn't required and won't be the default.  Locally, tests will still run single core unless you provide extra flags
- CI is a shared hosting environment making it an environment unsuitable for measuring performance.
- I agree with your logic in the context of writing an actual application, but I don't see how that logic extends to tests.  Fast test suite runs speed up the iteration cycle for development which has very tangible productivity boosts.
Agreed on parallelizing all the tests. It's not that big a deal, easy win!
Sure no problem, let's dot it.

Also, you are wrong that vyper isn't an `Application` actually you might be right as it's a `MetaApplication` :P the test run decreased by 400 seconds when I fixed a bug on ABI handling, pyetherum test suite was 2x faster than switching to eth tester - this is super useful. And I bet you if you guys enhance pyevm significantly one can pick it up. That's also why we leverage get_with_gas_estimation (will become get_contract eventually).
In my mind, the ideal structure of the compiler is a series of functions that moves one data structure form to another. If each layer is a pure function, there should be no issue testing each one in parallel, as the data in and out of each layer is what's important (pre/post conditions for a test)
That's not the truth though, it's about what you produce - because you could still be producing a long list of jumps and store codes with your pure functions, or reusing constants ineffectively  that are directly correlated to actual time on evm, thereby test time.

That level of testing is very primitive and you definitely need both functional and end to end tests.
So all I want to leave here as food for thought, is there is and could be so much more to tests than just testing functions and coverage :-) {or I would like to think so}.
> you are wrong that vyper isn't an `Application`

I wasn't intending to say Vyper isn't an application.  I was saying the tests aren't the application and thus I don't apply the same standards for performance gains (thus being fine with gaining speed through concurrency).  Sorry for any misunderstanding.
Ah yes, sorry I misread that ;) 

As for tests, I am onboard to make them as fast as possible on the CI :rocket:
> And I bet you if you guys enhance pyevm significantly one can pick it up

Yeah, we're aware, and it's very likely that the core EVM performance will get some :heart: in the near future.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -4,11 +4,12 @@
 
 
 test_deps = [
-    'pytest',
-    'pytest-cov',
-    'py-evm==0.2.0a34',
-    'eth-tester==0.1.0b33',
-    'web3==4.8.2',
+    'pytest>=3.6',
+    'pytest-cov==2.4.0',
+    'pytest-xdist==1.18.1',
+    'py-evm==0.2.0a39',
+    'eth-tester==0.1.0b37',
+    'web3==5.0.0a6'
 ]
 
 


Test patch:
diff --git a/tests/conftest.py b/tests/conftest.py
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,7 +1,5 @@
-import eth_tester
 import logging
 import pytest
-import web3
 
 from functools import wraps
 
@@ -18,9 +16,12 @@
 from web3 import (
     Web3,
 )
+from web3._utils.toolz import (
+    compose,
+)
 from web3.contract import (
-    ConciseContract,
-    ConciseMethod
+    Contract,
+    mk_collision_prop,
 )
 from vyper.parser.parser_utils import (
     LLLnode
@@ -32,9 +33,13 @@
 )
 
 
-class VyperMethod(ConciseMethod):
+class VyperMethod:
     ALLOWED_MODIFIERS = {'call', 'estimateGas', 'transact', 'buildTransaction'}
 
+    def __init__(self, function, normalizers=None):
+        self._function = function
+        self._function._return_data_normalizers = normalizers
+
     def __call__(self, *args, **kwargs):
         return self.__prepared_function(*args, **kwargs)
 
@@ -54,89 +59,82 @@ def __prepared_function(self, *args, **kwargs):
         return getattr(self._function(*args), modifier)(modifier_dict)
 
 
-class VyperContract(ConciseContract):
+class VyperContract:
 
-    def __init__(self, classic_contract, method_class=VyperMethod):
-        super().__init__(classic_contract, method_class)
+    """
+    An alternative Contract Factory which invokes all methods as `call()`,
+    unless you add a keyword argument. The keyword argument assigns the prep method.
 
+    This call
 
-############
-# PATCHING #
-############
+    > contract.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...})
 
-setattr(eth_tester.backends.pyevm.main, 'GENESIS_GAS_LIMIT', 10**9)
-setattr(eth_tester.backends.pyevm.main, 'GENESIS_DIFFICULTY', 1)
+    is equivalent to this call in the classic contract:
 
+    > contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...})
+    """
+    def __init__(self, classic_contract, method_class=VyperMethod):
 
-def set_evm_verbose_logging():
-    logger = logging.getLogger('evm')
-    logger.setLevel('TRACE')
+        classic_contract._return_data_normalizers += CONCISE_NORMALIZERS
+        self._classic_contract = classic_contract
+        self.address = self._classic_contract.address
 
+        protected_fn_names = [fn for fn in dir(self) if not fn.endswith('__')]
 
-# Useful options to comment out whilst working:
-set_evm_verbose_logging()
-# from vdb import vdb
-# vdb.set_evm_opcode_debugger()
+        for fn_name in self._classic_contract.functions:
 
+            # Override namespace collisions
+            if fn_name in protected_fn_names:
+                _concise_method = mk_collision_prop(fn_name)
 
-@pytest.fixture(autouse=True)
-def patch_log_filter_remove(monkeypatch):
+            else:
+                _classic_method = getattr(
+                    self._classic_contract.functions,
+                    fn_name)
 
-    def Filter_remove(self, *values):
+                _concise_method = method_class(
+                    _classic_method,
+                    self._classic_contract._return_data_normalizers
+                )
 
-        def get_key(v):
-            return v.get('transaction_hash'), v.get('log_index'), v.get('transaction_index')
+            setattr(self, fn_name, _concise_method)
 
-        values_to_remove = set([
-            get_key(value)
-            for value in values
-        ])
+    @classmethod
+    def factory(cls, *args, **kwargs):
+        return compose(cls, Contract.factory(*args, **kwargs))
 
-        queued_values = self.get_changes()
-        self.values = [
-            value
-            for value
-            in self.get_all()
-            if get_key(value) not in values_to_remove
-        ]
-        for value in queued_values:
-            if get_key(value) in values_to_remove:
-                continue
-            self.queue.put_nowait(value)
 
-    monkeypatch.setattr(eth_tester.utils.filters.Filter, 'remove', Filter_remove)
+def _none_addr(datatype, data):
+    if datatype == 'address' and int(data, base=16) == 0:
+        return (datatype, None)
+    else:
+        return (datatype, data)
 
 
-@pytest.fixture(autouse=True)
-def patch_is_encodeable_for_fixed(monkeypatch):
-    original_is_encodable = web3.utils.abi.is_encodable
+CONCISE_NORMALIZERS = (
+    _none_addr,
+)
 
-    def utils_abi_is_encodable(_type, value):
-        from eth_utils import is_integer
-        from eth_abi.abi import process_type
-        try:
-            base, sub, arrlist = _type
-        except ValueError:
-            base, sub, arrlist = process_type(_type)
+############
+# PATCHING #
+############
 
-        if not arrlist:
-            if base == 'fixed' and not arrlist:
-                return True
-            elif base == 'int':
-                if not is_integer(value):
-                    return False
-                exp = int(sub)
-                if value < -1 * 2**(exp - 1) or value > 2**(exp - 1) + 1:
-                    return False
-                return True
+# setattr(eth_tester.backends.pyevm.main, 'GENESIS_GAS_LIMIT', 10**9)
+# setattr(eth_tester.backends.pyevm.main, 'GENESIS_DIFFICULTY', 1)
+
+
+def set_evm_verbose_logging():
+    logger = logging.getLogger('evm')
+    logger.setLevel('TRACE')
 
-        # default behaviour
-        return original_is_encodable(_type, value)
 
-    monkeypatch.setattr(web3.utils.abi, 'is_encodable', utils_abi_is_encodable)
+# Useful options to comment out whilst working:
+# set_evm_verbose_logging()
+# from vdb import vdb
+# vdb.set_evm_opcode_debugger()
 
 
-@pytest.fixture(scope="module")
+@pytest.fixture
 def tester():
     t = EthereumTester()
     return t
@@ -146,7 +144,7 @@ def zero_gas_price_strategy(web3, transaction_params=None):
     return 0  # zero gas price makes testing simpler.
 
 
-@pytest.fixture(scope="module")
+@pytest.fixture
 def w3(tester):
     w3 = Web3(EthereumTesterProvider(tester))
     w3.eth.setGasPriceStrategy(zero_gas_price_strategy)
@@ -155,7 +153,7 @@ def w3(tester):
 
 @pytest.fixture
 def keccak():
-    return Web3.sha3
+    return Web3.keccak
 
 
 @pytest.fixture
diff --git a/tests/examples/auctions/test_blind_auction.py b/tests/examples/auctions/test_blind_auction.py
--- a/tests/examples/auctions/test_blind_auction.py
+++ b/tests/examples/auctions/test_blind_auction.py
@@ -39,7 +39,7 @@ def test_late_bid(w3, auction_contract, assert_tx_failed):
 
     # Try to bid after bidding has ended
     assert_tx_failed(lambda: auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (200).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (8675309).to_bytes(32, byteorder='big')
@@ -54,7 +54,7 @@ def test_too_many_bids(w3, auction_contract, assert_tx_failed):
     # First 128 bids should be able to be placed successfully
     for i in range(MAX_BIDS):
         auction_contract.bid(
-            w3.sha3(b''.join([
+            w3.keccak(b''.join([
                 (i).to_bytes(32, byteorder='big'),
                 (1).to_bytes(32, byteorder='big'),
                 (8675309).to_bytes(32, byteorder='big')
@@ -64,7 +64,7 @@ def test_too_many_bids(w3, auction_contract, assert_tx_failed):
 
     # 129th bid should fail
     assert_tx_failed(lambda: auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (128).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (8675309).to_bytes(32, byteorder='big')
@@ -78,7 +78,7 @@ def test_early_reval(w3, auction_contract, assert_tx_failed):
 
     # k1 places 1 real bid
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (100).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (8675309).to_bytes(32, byteorder='big')
@@ -116,7 +116,7 @@ def test_late_reveal(w3, auction_contract, assert_tx_failed):
 
     # k1 places 1 real bid
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (100).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (8675309).to_bytes(32, byteorder='big')
@@ -184,7 +184,7 @@ def test_blind_auction(w3, auction_contract):
 
     # k1 places 1 real bid
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (100).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (8675309).to_bytes(32, byteorder='big')
@@ -194,7 +194,7 @@ def test_blind_auction(w3, auction_contract):
 
     # k2 places 1 real bid (highest) and 2 fake
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (150).to_bytes(32, byteorder='big'),
             (1).to_bytes(32, byteorder='big'),
             (1234567).to_bytes(32, byteorder='big')
@@ -202,7 +202,7 @@ def test_blind_auction(w3, auction_contract):
         transact={'value': 150, 'from': k2}
     )
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (200).to_bytes(32, byteorder='big'),
             (0).to_bytes(32, byteorder='big'),
             (1234567).to_bytes(32, byteorder='big')
@@ -210,7 +210,7 @@ def test_blind_auction(w3, auction_contract):
         transact={'value': 250, 'from': k2}
     )
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (300).to_bytes(32, byteorder='big'),
             (1).to_bytes(32, byteorder='big'),
             (1234567).to_bytes(32, byteorder='big')
@@ -220,7 +220,7 @@ def test_blind_auction(w3, auction_contract):
 
     # k3 places 2 fake bids
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (175).to_bytes(32, byteorder='big'),
             (1).to_bytes(32, byteorder='big'),
             (9876543).to_bytes(32, byteorder='big')
@@ -228,7 +228,7 @@ def test_blind_auction(w3, auction_contract):
         transact={'value': 175, 'from': k3}
     )
     auction_contract.bid(
-        w3.sha3(b''.join([
+        w3.keccak(b''.join([
             (275).to_bytes(32, byteorder='big') +
             (1).to_bytes(32, byteorder='big') +
             (9876543).to_bytes(32, byteorder='big')
diff --git a/tests/examples/market_maker/test_on_chain_market_maker.py b/tests/examples/market_maker/test_on_chain_market_maker.py
--- a/tests/examples/market_maker/test_on_chain_market_maker.py
+++ b/tests/examples/market_maker/test_on_chain_market_maker.py
@@ -31,27 +31,27 @@ def test_initial_statet(market_maker):
 
 def test_initiate(w3, market_maker, erc20, assert_tx_failed):
     a0 = w3.eth.accounts[0]
-    erc20.approve(market_maker.address, 2 * 10**18, transact={})
-    market_maker.initiate(erc20.address, 1 * 10**18, transact={'value': 2 * 10**18})
-    assert market_maker.totalEthQty() == 2 * 10**18
-    assert market_maker.totalTokenQty() == 1 * 10**18
+    erc20.approve(market_maker.address, w3.toWei(2, "ether"), transact={})
+    market_maker.initiate(erc20.address, w3.toWei(1, "ether"), transact={'value': w3.toWei(2, "ether")})
+    assert market_maker.totalEthQty() == w3.toWei(2, "ether")
+    assert market_maker.totalTokenQty() == w3.toWei(1, "ether")
     assert market_maker.invariant() == 2 * 10**36
     assert market_maker.owner() == a0
     assert erc20.name() == TOKEN_NAME
     assert erc20.decimals() == TOKEN_DECIMALS
 
     # Initiate cannot be called twice
-    assert_tx_failed(lambda: market_maker.initiate(erc20.address, 1 * 10**18, transact={'value': 2 * 10**18}))
+    assert_tx_failed(lambda: market_maker.initiate(erc20.address, w3.toWei(1, "ether"), transact={'value': w3.toWei(2, "ether")}))
 
 
 def test_eth_to_tokens(w3, market_maker, erc20):
     a1 = w3.eth.accounts[1]
-    erc20.approve(market_maker.address, 2 * 10**18, transact={})
-    market_maker.initiate(erc20.address, 1 * 10**18, transact={'value': 2 * 10**18})
-    assert erc20.balanceOf(market_maker.address) == 1000000000000000000
+    erc20.approve(market_maker.address, w3.toWei(2, "ether"), transact={})
+    market_maker.initiate(erc20.address, w3.toWei(1, "ether"), transact={'value': w3.toWei(2, "ether")})
+    assert erc20.balanceOf(market_maker.address) == w3.toWei(1, "ether")
     assert erc20.balanceOf(a1) == 0
-    assert market_maker.totalTokenQty() == 1000000000000000000
-    assert market_maker.totalEthQty() == 2000000000000000000
+    assert market_maker.totalTokenQty() == w3.toWei(1, "ether")
+    assert market_maker.totalEthQty() == w3.toWei(2, "ether")
 
     market_maker.ethToTokens(transact={'value': 100, 'from': a1})
     assert erc20.balanceOf(market_maker.address) == 999999999999999950
@@ -62,30 +62,34 @@ def test_eth_to_tokens(w3, market_maker, erc20):
 
 def test_tokens_to_eth(w3, tester, market_maker, erc20):
     a1 = w3.eth.accounts[1]
-    erc20.transfer(a1, 2 * 10**18, transact={})
-    erc20.approve(market_maker.address, 2 * 10**18, transact={'from': a1})
-    market_maker.initiate(erc20.address, 1 * 10**18, transact={'value': 2 * 10**18, 'from': a1})
-    assert w3.eth.getBalance(market_maker.address) == 2000000000000000000
-    assert w3.eth.getBalance(a1) == 999997999999999999999900
-    assert market_maker.totalTokenQty() == 1000000000000000000
+    a1_balance_before = w3.eth.getBalance(a1)
 
-    erc20.approve(market_maker.address, 1 * 10**18, transact={'from': a1})
-    market_maker.tokensToEth(1 * 10**18, transact={'from': a1})
-    assert w3.eth.getBalance(market_maker.address) == 1000000000000000000
-    assert w3.eth.getBalance(a1) == 999998999999999999999900
-    assert market_maker.totalTokenQty() == 2000000000000000000
-    assert market_maker.totalEthQty() == 1000000000000000000
+    erc20.transfer(a1, w3.toWei(2, "ether"), transact={})
+    erc20.approve(market_maker.address, w3.toWei(2, "ether"), transact={'from': a1})
+    market_maker.initiate(erc20.address, w3.toWei(1, "ether"), transact={'value': w3.toWei(2, "ether"), 'from': a1})
+    assert w3.eth.getBalance(market_maker.address) == w3.toWei(2, "ether")
+    assert w3.eth.getBalance(a1) == a1_balance_before - w3.toWei(2, "ether")  # sent 2 eth, with initiate.
+    assert market_maker.totalTokenQty() == w3.toWei(1, "ether")
+
+    erc20.approve(market_maker.address, w3.toWei(1, "ether"), transact={'from': a1})
+    market_maker.tokensToEth(w3.toWei(1, "ether"), transact={'from': a1})
+    assert w3.eth.getBalance(market_maker.address) == w3.toWei(1, "ether")  # 1 eth less in market.
+    assert w3.eth.getBalance(a1) == a1_balance_before - w3.toWei(1, "ether")  # got 1 eth back, for trade.
+    assert market_maker.totalTokenQty() == w3.toWei(2, "ether")  # Tokens increased by 1
+    assert market_maker.totalEthQty() == w3.toWei(1, "ether")
 
 
 def test_owner_withdraw(w3, tester, market_maker, erc20, assert_tx_failed):
     a0, a1 = w3.eth.accounts[:2]
-    erc20.approve(market_maker.address, 2 * 10**18, transact={})
-    market_maker.initiate(erc20.address, 1 * 10**18, transact={'value': 2 * 10**18})
-    assert w3.eth.getBalance(a0) == 999994000000000000000000
-    assert erc20.balanceOf(a0) == 20999999000000000000000000
-
-    # Only owner can call ownerWithdraw
-    assert_tx_failed(lambda: market_maker.ownerWithdraw(transact={'from': a1}))
+    a0_balance_before = w3.eth.getBalance(a0)
+    # Approve 2 eth transfers.
+    erc20.approve(market_maker.address, w3.toWei(2, "ether"), transact={})
+    # Initiate market with 2 eth value.
+    market_maker.initiate(erc20.address, w3.toWei(1, "ether"), transact={'value': w3.toWei(2, "ether")})
+    assert w3.eth.getBalance(a0) == a0_balance_before - w3.toWei(2, "ether")  # 2 eth was sent to market_maker contract.
+    assert erc20.balanceOf(a0) == TOKEN_TOTAL_SUPPLY - w3.toWei(1, "ether")  # a0's balance is locked up in market_maker contract.
+
+    assert_tx_failed(lambda: market_maker.ownerWithdraw(transact={'from': a1}))  # Only owner can call ownerWithdraw
     market_maker.ownerWithdraw(transact={})
-    assert w3.eth.getBalance(a0) == 999996000000000000000000
-    assert erc20.balanceOf(a0) == 21000000000000000000000000
+    assert w3.eth.getBalance(a0) == a0_balance_before  # Eth balance restored.
+    assert erc20.balanceOf(a0) == TOKEN_TOTAL_SUPPLY  # Tokens returned to a0.
diff --git a/tests/examples/safe_remote_purchase/test_safe_remote_purchase.py b/tests/examples/safe_remote_purchase/test_safe_remote_purchase.py
--- a/tests/examples/safe_remote_purchase/test_safe_remote_purchase.py
+++ b/tests/examples/safe_remote_purchase/test_safe_remote_purchase.py
@@ -9,11 +9,6 @@
 import pytest
 
 
-# Inital balance of accounts
-INIT_BAL_a0 = 1000000000000000000000000
-INIT_BAL_a1 = 1000000000000000000000000
-
-
 @pytest.fixture
 def contract_code(get_contract):
     with open("examples/safe_remote_purchase/safe_remote_purchase.vy") as f:
@@ -22,20 +17,19 @@ def contract_code(get_contract):
 
 
 @pytest.fixture
-def check_balance(w3, tester):
-    def check_balance():
+def get_balance(w3, tester):
+    def get_balance():
         a0, a1 = w3.eth.accounts[:2]
         # balance of a1 = seller, a2 = buyer
         return w3.eth.getBalance(a0), w3.eth.getBalance(a1)
-    return check_balance
+    return get_balance
 
 
-def test_initial_state(w3, assert_tx_failed, get_contract, check_balance, contract_code):
-    assert check_balance() == (INIT_BAL_a0, INIT_BAL_a1)
+def test_initial_state(w3, assert_tx_failed, get_contract, get_balance, contract_code):
     # Inital deposit has to be divisible by two
     assert_tx_failed(lambda: get_contract(contract_code, value=13))
     # Seller puts item up for sale
-    a0_pre_bal, a1_pre_bal = check_balance()
+    a0_pre_bal, a1_pre_bal = get_balance()
     c = get_contract(contract_code, value_in_eth=2)
     # Check that the seller is set correctly
     assert c.seller() == w3.eth.accounts[0]
@@ -44,26 +38,29 @@ def test_initial_state(w3, assert_tx_failed, get_contract, check_balance, contra
     # Check if unlocked() works correctly after initialization
     assert c.unlocked() is True
     # Check that sellers (and buyers) balance is correct
-    assert check_balance() == ((INIT_BAL_a0 - w3.toWei(2, 'ether')), INIT_BAL_a1)
+    assert get_balance() == ((a1_pre_bal - w3.toWei(2, 'ether')), a1_pre_bal)
 
 
-def test_abort(w3, assert_tx_failed, check_balance, get_contract, contract_code):
+def test_abort(w3, assert_tx_failed, get_balance, get_contract, contract_code):
     a0, a1, a2 = w3.eth.accounts[:3]
-    c = get_contract(contract_code, value=2)
+
+    a0_pre_bal, a1_pre_bal = get_balance()
+    c = get_contract(contract_code, value=w3.toWei(2, 'ether'))
+    assert c.value() == w3.toWei(1, 'ether')
     # Only sender can trigger refund
     assert_tx_failed(lambda: c.abort(transact={'from': a2}))
     # Refund works correctly
     c.abort(transact={'from': a0, 'gasPrice': 0})
-    assert check_balance() == (INIT_BAL_a0 - w3.toWei(2, 'ether'), INIT_BAL_a1)
+    assert get_balance() == (a0_pre_bal, a1_pre_bal)
     # Purchase in process, no refund possible
     c = get_contract(contract_code, value=2)
     c.purchase(transact={'value': 2, 'from': a1, 'gasPrice': 0})
     assert_tx_failed(lambda: c.abort(transact={'from': a0}))
 
 
-def test_purchase(w3, get_contract, assert_tx_failed, check_balance, contract_code):
+def test_purchase(w3, get_contract, assert_tx_failed, get_balance, contract_code):
     a0, a1, a2, a3 = w3.eth.accounts[:4]
-    init_bal_a0, init_bal_a1 = check_balance()
+    init_bal_a0, init_bal_a1 = get_balance()
     c = get_contract(contract_code, value=2)
     # Purchase for too low/high price
     assert_tx_failed(lambda: c.purchase(transact={'value': 1, 'from': a1}))
@@ -75,14 +72,14 @@ def test_purchase(w3, get_contract, assert_tx_failed, check_balance, contract_co
     # Check if contract is locked correctly
     assert c.unlocked() is False
     # Check balances, both deposits should have been deducted
-    assert check_balance() == (init_bal_a0 - 2, init_bal_a1 - 2)
+    assert get_balance() == (init_bal_a0 - 2, init_bal_a1 - 2)
     # Allow nobody else to purchase
     assert_tx_failed(lambda: c.purchase(transact={'value': 2, 'from': a3}))
 
 
-def test_received(w3, get_contract, assert_tx_failed, check_balance, contract_code):
+def test_received(w3, get_contract, assert_tx_failed, get_balance, contract_code):
     a0, a1 = w3.eth.accounts[:2]
-    init_bal_a0, init_bal_a1 = check_balance()
+    init_bal_a0, init_bal_a1 = get_balance()
     c = get_contract(contract_code, value=2)
     # Can only be called after purchase
     assert_tx_failed(lambda: c.received(transact={'from': a1, 'gasPrice': 0}))
@@ -93,10 +90,10 @@ def test_received(w3, get_contract, assert_tx_failed, check_balance, contract_co
     # Check if buyer can call receive
     c.received(transact={'from': a1, 'gasPrice': 0})
     # Final check if everything worked. 1 value has been transferred
-    assert check_balance() == (init_bal_a0 + 1, init_bal_a1 - 1)
+    assert get_balance() == (init_bal_a0 + 1, init_bal_a1 - 1)
 
 
-def test_received_reentrancy(w3, get_contract, assert_tx_failed, check_balance, contract_code):
+def test_received_reentrancy(w3, get_contract, assert_tx_failed, get_balance, contract_code):
 
     buyer_contract_code = """
 contract PurchaseContract:
diff --git a/tests/examples/wallet/test_wallet.py b/tests/examples/wallet/test_wallet.py
--- a/tests/examples/wallet/test_wallet.py
+++ b/tests/examples/wallet/test_wallet.py
@@ -89,8 +89,8 @@ def test_javascript_signatures(w3, get_contract):
         ) for x in map(lambda z: w3.toBytes(hexstr=z[2:]), raw_sigs)
     ]
 
-    h = w3.sha3((0).to_bytes(32, "big") + b'\x00' * 12 + w3.toBytes(hexstr=recipient[2:]) + (25).to_bytes(32, "big") + b'')
-    h2 = w3.sha3(b"\x19Ethereum Signed Message:\n32" + h)
+    h = w3.keccak((0).to_bytes(32, "big") + b'\x00' * 12 + w3.toBytes(hexstr=recipient[2:]) + (25).to_bytes(32, "big") + b'')
+    h2 = w3.keccak(b"\x19Ethereum Signed Message:\n32" + h)
 
     # Check to make sure the signatures are valid
     assert is_same_address(Account.recoverHash(h2, sigs[0]), accounts[0])
diff --git a/tests/parser/features/test_assert.py b/tests/parser/features/test_assert.py
--- a/tests/parser/features/test_assert.py
+++ b/tests/parser/features/test_assert.py
@@ -48,15 +48,15 @@ def test2(a: int128, b: int128) -> int128:
     with pytest.raises(TransactionFailed) as e_info:
         c.test(0)
 
-    assert e_info.value.args[0] == b'larger than one please'
+    assert e_info.value.args[0] == 'larger than one please'
     # a = 0, b = 1
     with pytest.raises(TransactionFailed) as e_info:
         c.test2(0, 1)
-    assert e_info.value.args[0] == b'a is not large enough'
+    assert e_info.value.args[0] == 'a is not large enough'
     # a = 1, b = 0
     with pytest.raises(TransactionFailed) as e_info:
         c.test2(2, 2)
-    assert e_info.value.args[0] == b'b may only be 1'
+    assert e_info.value.args[0] == 'b may only be 1'
     # return correct value
     assert c.test2(5, 1) == 17
 
diff --git a/tests/parser/functions/test_default_parameters.py b/tests/parser/functions/test_default_parameters.py
--- a/tests/parser/functions/test_default_parameters.py
+++ b/tests/parser/functions/test_default_parameters.py
@@ -110,15 +110,10 @@ def bar(a: int128, b: int128 = -1) -> (int128, int128):
     assert c.bar(-123) == [-123, -1]
     assert c.bar(100, 100) == [100, 100]
 
-    # bypass abi encoding checking:
-    def utils_abi_is_encodable(_type, value):
-        return True
-
     def validate_value(cls, value):
         pass
 
     monkeypatch.setattr('eth_abi.encoding.NumberEncoder.validate_value', validate_value)
-    monkeypatch.setattr('web3.utils.abi.is_encodable', utils_abi_is_encodable)
 
     assert c.bar(200, 2**127 - 1) == [200, 2**127 - 1]
     assert_tx_failed(lambda: c.bar(200, 2**127))