如何不编辑Python测试

并在代码之外取出测试结果。本文是关于自动化和增加Python测试的便利性。


图片


介绍性


我有一个已经开发了几年的项目。该项目中没有测试。而且他对其他团队有积极的依赖性,这也影响了结果。


回归测试是获得更自信发展的步骤之一。其实质是将计算的数据与程序的最后规范结果进行比较。 


python . .


:


  • . , Python xml, json . , textwrap.dedent.
  • . .
  • . , . . .


, . testoot 3.4+.


.  .


foo . :


def foo():
    return {'a': 1}

def test_simple(testoot: Testoot):
    testoot.test(foo())

pytest:


pytest -s tests

. . testoot Testoot .


:


def foo():
    return {'a': 2}

def test_simple(testoot: Testoot):
    testoot.test(foo())

AssertionError :


...
def test_simple(testoot: Testoot):
>       testoot.test(foo()))

cls = <class 'testoot.ext.pytest.PytestComparator'>, test_obj = {'a': 2}, canon_obj = {'a': 1}

    @classmethod
    def compare(cls, test_obj: any, canon_obj: any):
        """Compares objects"""
>       assert test_obj == canon_obj
E       AssertionError


. - .


--canonize.


pytest -s tests --canonize

, pytest ( --verbose ):


tests/test_console/test_console.py [tests/test_console/test_console.py::test_simple]
{'a': 2} == {'a': 1}
~Differing items:
~{'a': 2} != {'a': 1}
~Use -v to get the full diff
Canonize [yn]? y
.

. .


. : 


  • pickle. Python. VCS pickle
  • bytes. , .
  • str. utf-8 , .
  • json . json, , .

, VCS .


. .


def test_filename(testoot: Testoot):
    d = Path(testoot.storage.root_dir / 'hello.json')
    d.write_text('{}')

    testoot.test_filename(str(d))


Testoot. :


import pytest

from testoot.ext.pytest import PytestContext
from testoot.ext.simple import DefaultBaseTestoot
from testoot.pub import AskCanonizePolicy, PickleSerializer, \
    LocalDirectoryStorage, ConsoleUserInteraction, Testoot

@pytest.fixture(scope='module')
def base_testoot():
    regress = DefaultBaseTestoot(
        storage=LocalDirectoryStorage('.testoot'),
    )
    regress.storage.ensure_exists()
    yield regress

@pytest.fixture(scope='function')
def testoot(base_testoot, request):
    fixture = Testoot(base_testoot, PytestContext(request))
    yield fixture

DefaultBaseTestoot . Testoot (scope='function'). pytest request , .


DefaultBaseTestoot BaseTestoot -: .testoot pickle-, --canonize.


-:


regress = DefaultBaseTestoot(
    serializer=JsonSerializer(),
)

. pytest :


class PytestComparator(Comparator):
    @classmethod
    def compare(cls, test_obj: any, canon_obj: any):
        """Compares objects"""
        assert test_obj == canon_obj

PytestContext(request, serializer=BinarySerializer(), comparator=PytestComparator()). :


def test_str(testoot: Testoot):
    result = 'abc'
    regress.test(result, serializer=StringSerializer(), comparator=PytestComparator())

, BaseTestoot.



, . , . 


也可能有必要从数据中删除不断变化的元素,例如上次更改的日期。这样,这样的更改就不会渗透到存储的数据中。


结论


这是Python库的测试和功能的概述。我将很乐意提出意见和建议!


安装:pip3 install testoot
文档:https : //testoot.readthedocs.io
源代码:https : //github.com/aptakhin/testoot


All Articles