4

Here is my class under test:

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

My unit test looks like the following:

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

This all works correctly.

However, I'd prefer not to monkeypatch on every test. Is there a way that I can apply the same patch to all tests?

Thanks!

SOLVED

In case anyone else finds this, I ended up with:

@pytest.fixture(scope="session", autouse=True)
def mock_auth_fixture(monkeypatch):
    monkeypatch.setattr(services.UnderTest, "_auth", mock_auth)
a11smiles
  • 1,190
  • 1
  • 9
  • 21

0 Answers0