Skip to content

Autogenerate tests from README code examples #44

@PFython

Description

@PFython

READMEs will often include code to demonstrate the intended behaviour of a script. A great utility would be to automatically convert code snippets into outline tests, or at least an 80% version where all the tedious formatting and copy/pasting has been avoided.

For example:

README:

## 1. ATTRIBUTE NAMES

>>> x = CleverDict(значение = "znacheniyeh: Russian word for 'value'")
>>> x.значение
"znacheniyeh: Russian word for 'value'"

## 2. ERRORS
>>> x.nonexistent
AttributeError: 'nonexistent'

TEST

class test_README_code_examples:
    def test_ATTRIBUTE_NAMES_1(self):
        """ Code Example 1 from section: 1. ATTRIBUTE NAMES of the README """
        x = CleverDict(значение = "znacheniyeh: Russian word for 'value'")
        assert  x.значение == "znacheniyeh: Russian word for 'value'"
    def test_ATTRIBUTE_NAMES_1(self):
        """ Code Example 1 from section 2. ATTRIBUTE NAMES of the README """
        with pytest.raises(AttributeError):
            x.nonexistent

OUTLINE APPROACH

import pyperclip
lines = pyperclip.paste()
lines1 = [x for x in lines.split("\n") if "    " in x]
lines2 = [x.replace('    >>> x\r', 'assert x == "') for x in lines1]
lines3 = [x.replace('>>> ', '') for x in lines2]
lines4 = ["    "+x for x in lines3]
# macro for inserting "assert ", going to end of line, deleting \n and subsequent 8(?) spaces etc.
pyperclip.copy(lines4)  # or actually append to test.py 

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions