DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Python Property Test


Hypothesis is a Python package play the role of QuickCheck in Haskell.

Install it with conda install -c conda-forge hypothesis.

An example from Quick start guide:

Save the following codes into hypo_test.py:

def encode(input_string):
    # if not input_string:
        # return []
    count = 1
    prev = ''
    lst = []
    for character in input_string:
        if character != prev:
            if prev:
                entry = (prev, count)
                lst.append(entry)
            count = 1
            prev = character
        else:
            count += 1
    else:
        entry = (character, count)
        lst.append(entry)
    return lst


def decode(lst):
    q = ''
    for character, count in lst:
        q += character * count
    return q


from hypothesis import given, example
from hypothesis.strategies import text

@given(s=text())
def test_decode_inverts_encode(s):
    assert decode(encode(s)) == s

Run it with python -m pytest hypo_test.py. The output is:

... Falsifying example: test_decode_inverts_encode(s='') ...

This means the empty string can't pass the test. Uncomment the 2nd and 3rd line, and run pytest again, the test will pass.

To debug the encode function, add the following test case into hypo_test.py:

def test_one_input():
    res = encode('00/000')
    print(res)
    print(decode(res))

Then run pytest hypo_test.py::test_one_input --trace. Now you are a pdb REPL.



Published

Nov 28, 2018

Last Updated

Nov 28, 2018

Category

Tech

Tags

  • hypothesis 1
  • python 136
  • test 4

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor