使用Python单元测试和VCR时,我们可以使用一个函数来生成不同的卡带文件吗?

2024-06-16 11:06:56 发布

您现在位置:Python中文网/ 问答频道 /正文

vcrpy是python录制/播放包,下面是指导原则中的常用方法

class TestCloudAPI(unittest.TestCase):
    def test_get_api_token(self):
        with vcr.use_cassette('fixtures/vcr_cassettes/test_get_api_token.yaml'): 
            # real request and testing

    def test_container_lifecycle(self):
        with vcr.use_cassette('fixtures/vcr_cassettes/test_container_lifecycle.yaml'):

我想有不同的记录文件,所以我必须在每个方法中重复这一点。在

有没有可能在某个地方用一条线来简化这一点:

^{pr2}$

Tags: 方法testselftokenapiyamlgetuse
3条回答

使用vcrpy-unittest可以更容易地实现这一点,正如您可能猜测的那样,vcrpy和{}之间的集成。在

你的例子如下:

from vcr_unittest import VCRTestCase

class TestCloudAPI(VCRTestCase):
    def test_get_api_token(self):
        # real request and testing

    def test_container_lifecycle(self):
        # real request and testing

磁带会根据测试自动命名,并与测试文件一起保存在cassettes目录中。例如,这将创建两个文件:cassettes/TestCloudAPI.test_get_api_token.yaml和{}。在

目录和命名可以通过重写两个方法来定制:_get_cassette_library_dir_get_cassette_name,但这可能不是必需的。在

vcrpy-unittest位于github的https://github.com/agriffis/vcrpy-unittest,PyPI位于https://pypi.python.org/pypi/vcrpy-unittest

目前VCR中没有一个功能可以实现这一点,但您可以自己制作。Check out the decorator that Venmo created.

现在,在较新版本的vcrpy中,通过完全省略磁带名来支持这一点。根据文件:

VCR.py now allows the omission of the path argument to the use_cassette function. Both of the following are now legal/should work

@my_vcr.use_cassette
def my_test_function():
...

In both cases, VCR.py will use a path that is generated from the provided test function’s name. If no cassette_library_dir has been set, the cassette will be in a file with the name of the test function in directory of the file in which the test function is declared. If a cassette_library_dir has been set, the cassette will appear in that directory in a file with the name of the decorated function.

It is possible to control the path produced by the automatic naming machinery by customizing the path_transformer and func_path_generator vcr variables

相关问题 更多 >