Last active
May 7, 2019 17:24
-
-
Save stephen-bunn/52e2ba18c0a75bac3be9ccbad8dda85e to your computer and use it in GitHub Desktop.
Medium - Hypothesis example test for is_plaindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Basic pytest+hypothesis for ``is_palindrome`` method.""" | |
from typing import Any, Callable | |
from hypothesis import given, assume | |
from hypothesis.strategies import text, composite | |
def is_palindrome(string: str) -> bool: | |
"""Determine if a given string is a palindrome. | |
:param str string: The string to process | |
:return: True if given string is a palindrome, otherwise False | |
:rtype: bool | |
""" | |
return string == string[::-1] | |
@composite | |
def palindrome(draw: Callable[..., Any]) -> str: | |
"""Composite hypothesis strategy for palindrome strings. | |
:param Callable[..., Any] draw: Function for drawing from hypothesis strategies | |
:return: A palindrome string | |
:rtype: str | |
""" | |
partial_content = draw(text()) | |
return partial_content + partial_content[::-1] | |
@composite | |
def not_palindrome(draw: Callable[..., Any]) -> str: | |
"""Composite hypothesis strategy for non-palindrome strings. | |
:param Callable[..., Any] draw: Function for drawing from hypothesis strategies | |
:return: A non-palindrome string | |
:rtype: str | |
""" | |
prefix_content = draw(text(min_size=2)) | |
assume(len(set(prefix_content)) > 1) | |
return prefix_content + prefix_content[::-1][:-1] | |
@given(palindrome()) | |
def test_is_plaindrome(palindrome): | |
"""Test true cases for ``is_palindrome``. | |
:param str palindrome: A palindrome string | |
""" | |
assert is_palindrome(palindrome) | |
@given(not_palindrome()) | |
def test_not_is_palindrome(not_palindrome): | |
"""Test false cases for ``is_plaindrome``. | |
:param str not_palindrome: A non-palindrome string | |
""" | |
assert not is_palindrome(not_palindrome) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment