Skip to content

Commit

Permalink
Teach astroid about Hypothesis (#820)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD authored Sep 14, 2020
1 parent bb35723 commit 290df48
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Release Date: TBA

Fixes #815

* Added a brain for ``hypothesis.strategies.composite``

* Added a brain for ``sqlalchemy.orm.session``

* Separate string and bytes classes patching
Expand Down
53 changes: 53 additions & 0 deletions astroid/brain/brain_hypothesis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
"""
Astroid hook for the Hypothesis library.
Without this hook pylint reports no-value-for-parameter for use of strategies
defined using the `@hypothesis.strategies.composite` decorator. For example:
from hypothesis import strategies as st
@st.composite
def a_strategy(draw):
return draw(st.integers())
a_strategy()
"""

import astroid

COMPOSITE_NAMES = (
"composite",
"st.composite",
"strategies.composite",
"hypothesis.strategies.composite",
)


def is_decorated_with_st_composite(node):
"""Return True if a decorated node has @st.composite applied."""
if node.decorators and node.args.args and node.args.args[0].name == "draw":
for decorator_attribute in node.decorators.nodes:
if decorator_attribute.as_string() in COMPOSITE_NAMES:
return True
return False


def remove_draw_parameter_from_composite_strategy(node):
"""Given that the FunctionDef is decorated with @st.composite, remove the
first argument (`draw`) - it's always supplied by Hypothesis so we don't
need to emit the no-value-for-parameter lint.
"""
del node.args.args[0]
del node.args.annotations[0]
del node.args.type_comment_args[0]
return node


astroid.MANAGER.register_transform(
node_class=astroid.FunctionDef,
transform=remove_draw_parameter_from_composite_strategy,
predicate=is_decorated_with_st_composite,
)

0 comments on commit 290df48

Please sign in to comment.