Search code examples
python-3.xmockingpytestfixtures

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:

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. 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?


Solution

  • You can define a fixture to depend on another fixture, then have them both be args in your test. 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")