2

这是我正在测试的课程:

class UnderTest():

    def __init__(self, url, token):
        self.paths = self._auth(url, token)

    def _auth(self, url, token):
        creds = BasicAuthentication(token=token)
        connection = Connection(url, creds)

        return connection.paths

    def _get_team(self, project, name):
        path = self.path.get_path()
        teams = path.get_teams(project.id)
        for team in teams:
            if team.name == name + " team":
                return team

        return None

我的单元测试如下所示:

def mock_auth(*args, **kwargs):
    def mock_teams(*args, **kwargs):
        return [
            SimpleNamespace(id=1, name='foo team'),
            SimpleNamespace(id=2, name='bar team')
        ]

    def mock_path(*args, **kwargs):
        mock = MagicMock()
        mock.get_teams.return_value = mock_teams()
        return mock

    mock = MagicMock(spec=PathFactory)
    mock.get_path.return_value = mock_path()
    return mock

def test_get_team(monkeypatch):
    monkeypatch.setattr(services.UnderTest, '_auth', mock_auth)     # <------ Do this on all tests
    ut = UnderTest(url='http://fooz.com', token='bar')
    
    project = SimpleNamespace(id=1)

    result = ut._get_team(project, 'foo')    

    assert result.id == 1
    assert ut._get_team(project, 'something') is None

这一切正常。

但是,我不希望每次测试都monkeypatch进行。有没有办法可以将相同的补丁应用于所有测试?

谢谢!

解决了

万一其他人发现了这个,我最终得到:

@pytest.fixture(scope="session", autouse=True)
def mock_auth_fixture(monkeypatch):
    monkeypatch.setattr(services.UnderTest, "_auth", mock_auth)
4

0 回答 0