简体   繁体   English

使用pytest.fixture选择退出功能

[英]Using pytest.fixture to opt out of function

I have a function that I don't want to run every time I run tests in my Flask-RESTFul API. 我有一个我不想每次在Flask-RESTFul API中运行测试时都运行的函数。 This is an example of the setup: 这是设置的示例:

class function(Resource):
    def post(self):
        print 'test'
        do_action()
        return {'success':True}

in my test I want to run this function, but ignore do_action(). 在我的测试中,我想运行此函数,但忽略do_action()。 How would I make this happen using pytest? 我如何使用pytest做到这一点?

This seems like a good opportunity to mark the tests 这似乎是标记测试的好机会

@pytest.mark.foo_test
class function(Resource):
    def post(self):
        print 'test'
        do_action()
        return {'success':True}

Then if you call with 那你打电话给

py.test -v -m foo_test

It will run only those tests marked "foo_test" 它将仅运行标记为“ foo_test”的测试

If you call with 如果您致电

py.test -v -m "not foo_test"

It will run all tests not marked "foo_test" 它将运行所有未标记为“ foo_test”的测试

You can mock do_action in your test: 您可以在测试中模拟do_action

def test_post(resource, mocker):
    m = mocker.patch.object(module_with_do_action, 'do_action')
    resource.post()
    assert m.call_count == 1

So the actual function will not be called in this test, with the added benefit that you can check if the post implementation is actuall calling the function. 因此,在此测试中不会调用实际函数,其附加好处是您可以检查post实现是否实际调用该函数。

This requires pytest-mocker to be installed (shameless plug). 这需要安装pytest-mocker (无耻的插件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM