Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contract_strategy #528

Merged
merged 3 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion brownie/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from brownie.exceptions import BrownieTestWarning

from .stateful import state_machine # NOQA: F401
from .strategies import strategy # NOQA: F401
from .strategies import contract_strategy, strategy # NOQA: F401

# hypothesis warns against combining function-scoped fixtures with @given
# but in brownie this is a documented and useful behaviour
Expand Down
21 changes: 18 additions & 3 deletions brownie/test/strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from hypothesis.strategies import SearchStrategy
from hypothesis.strategies._internal.deferred import DeferredStrategy

from brownie import network
from brownie import network, project
from brownie.convert import Fixed, Wei
from brownie.convert.utils import get_int_bounds

Expand All @@ -18,8 +18,12 @@


class _DeferredStrategyRepr(DeferredStrategy):
def __init__(self, fn: Callable, repr_target: str) -> None:
super().__init__(fn)
self._repr_target = repr_target

def __repr__(self):
return "sampled_from(accounts)"
return f"sampled_from({self._repr_target})"


def _exclude_filter(fn: Callable) -> Callable:
Expand Down Expand Up @@ -73,7 +77,7 @@ def _decimal_strategy(

@_exclude_filter
def _address_strategy() -> SearchStrategy:
return _DeferredStrategyRepr(lambda: st.sampled_from(list(network.accounts)))
return _DeferredStrategyRepr(lambda: st.sampled_from(list(network.accounts)), "accounts")


@_exclude_filter
Expand Down Expand Up @@ -136,6 +140,17 @@ def _tuple_strategy(abi_type: TupleType) -> SearchStrategy:
return st.tuples(*strategies)


def contract_strategy(contract_name: str) -> SearchStrategy:
def _contract_deferred(name):
for proj in project.get_loaded_projects():
if name in proj.dict():
return st.sampled_from(list(proj[name]))

raise NameError(f"Contract '{name}' does not exist in any active projects")

return _DeferredStrategyRepr(lambda: _contract_deferred(contract_name), contract_name)


def strategy(type_str: str, **kwargs: Any) -> SearchStrategy:
type_str = TYPE_STR_TRANSLATIONS.get(type_str, type_str)
if type_str == "fixed168x10":
Expand Down
43 changes: 41 additions & 2 deletions docs/tests-hypothesis-property.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,19 @@ To begin writing property-based tests, import the following two methods:

from brownie.test import given, strategy

* ``given`` is a decorator that converts a test function that accepts arguments into a randomized test. This is a thin wrapper around :func:`hypothesis.given <hypothesis.given>`, the API is identical.
* ``strategy`` is a method for creating :ref:`test strategies<hypothesis-strategies>` based on ABI types.
.. py:function:: brownie.test.given

A decorator for turning a test function that accepts arguments into a randomized test.

When using Brownie, this is the main entry point to property-based testing. This is a thin wrapper around :func:`hypothesis.given <hypothesis.given>`, the API is identical.

.. warning::

Be sure to import ``@given`` from Brownie and not directly from Hypothesis. Importing the function directly can cause issues with test isolation.

.. py:function:: brownie.test.strategy

A method for creating :ref:`test strategies<hypothesis-strategies>` based on ABI types.

A test using Hypothesis consists of two parts: A function that looks like a normal pytest test with some additional arguments, and a ``@given`` decorator that specifies how to those arguments are provided.

Expand Down Expand Up @@ -294,6 +305,34 @@ This strategy does not accept any keyword arguments.
>>> strategy('(uint16,bool)').example()
(47628, False)

Contract Strategies
-------------------

The ``contract_strategy`` function is used to draw from :func:`ProjectContract <brownie.network.contract.ProjectContract>` objects within a :func:`ContractContainer <brownie.network.contract.ContractContainer>`.


.. py:function:: brownie.test.contract_strategy(contract_name)

`Base strategy:` :func:`hypothesis.strategies.sampled_from <hypothesis.strategies.sampled_from>`

A strategy to access :func:`ProjectContract <brownie.network.contract.ProjectContract>` objects.

* ``contract_name``: The name of the contract, given as a string

.. code-block:: python

>>> ERC20
[<ERC20 Contract '0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87'>, <ERC20 Contract '0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6'>]

>>> from brownie.test import contract_strategy
>>> contract_strategy('ERC20')
sampled_from(ERC20)

>>> contract_strategy('ERC20').example()
<ERC20 Contract '0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6'>



Other Strategies
----------------

Expand Down
26 changes: 26 additions & 0 deletions tests/test/strategies/test_contract_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/python3

import pytest
from hypothesis import given
from hypothesis.strategies._internal.deferred import DeferredStrategy

from brownie.network.contract import ProjectContract
from brownie.test import contract_strategy


def test_strategy():
assert isinstance(contract_strategy("ERC20"), DeferredStrategy)


def test_repr():
assert repr(contract_strategy("Token")) == "sampled_from(Token)"


def test_does_not_exist():
with pytest.raises(NameError):
contract_strategy("Foo").validate()


@given(contract=contract_strategy("BrownieTester"))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably could add number of samples = 1 to a settings object here

def test_given(tester, contract):
assert isinstance(contract, ProjectContract)