[英]How can I pass mock objects to a pytest fixture
Sorry for the title, I'll surely have to update that... What I have is a pytest test function: 抱歉,标题,我一定要更新。。。我有一个pytest测试功能:
def test_update_db():
mock_connection = Mock(spec=Connection)
db_updater = DbUpdater(mock_connection)
db_updater.run("some parameter")
mock_connection.gna.assert_called_with("some different parameter")
That works, but is ugly: db_updater should really be a fixture. 那行得通,但是很丑:db_updater应该确实是一个固定装置。 But I'll have to pass it the connection object, so I'd rather have:
但是我必须将连接对象传递给它,所以我宁愿拥有:
@pytest.fixture
def db_updater():
mock_connection = Mock(spec=Connection)
return DbUpdater(mock_connection)
def test_update_db(db_updater):
db_updater.run("some parameter")
mock_connection.gna.assert_called_with("some different parameter")
Much nicer test function with one problem: mock_connection doesn't exist there... How can I solve this? 一个更好的测试功能,但有一个问题:在那里不存在模拟连接...如何解决此问题?
You can define a fixture to depend on another fixture, then have them both be args in your test. 您可以定义一个夹具来依赖另一个夹具,然后在测试中将它们都设为arg。 This should work:
这应该工作:
import pytest
@pytest.fixture
def conn():
return Mock(spec=Connection)
@pytest.fixture
def db_updater(conn):
return DbUpdater(conn)
def test_update_db(conn, db_updater):
db_updater.run("some parameter")
conn.gna.assert_called_with("some different parameter")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.