To be specific, I'm using the python O365 library in a custom SharePoint repository. It heavily relies on some classes from this library and I need to mock out functionalities since I can't just connect to any real resources in my tests.
Here is the key part of my repository.
class SharepointRepository():
def __init__(self, app=None):
self._account = Account(
...
) # O365.account.Account
sites = self._account.sharepoint().search_site(app.config.get("SP_SITE"))
self._site = sites[0] # O365.sharepoint.Site
def _get_drive_by_name(self, drive_name):
for drive in self._site.list_document_libraries():
if drive.name == drive_name:
return drive
def delete_file(self, drive, path):
item = drive.get_item_by_path(path) # O365.drive.Drive
if not item.delete(): # O365.drive.DriveItem
raise Exception(
I've tried to monkeypatch
the called methods from the library one by one, but the problem is that these attribute objects are created by the library itself and would already make real connections. So I can't just create or inject them myself.
import pytest
from O365.account import Account
from O365.sharepoint import Site
from O365.drive import Drive
class TestSharePoint:
@pytest.fixture(autouse=True)
def setup(self):
self.client = SharepointRepository()
self.drive_name = "test drive"
self.path = "test path"
self._account = Account() # This does not work, I need to mock this.
self._site = Site() # This does not work, I need to mock this.
def test_sharepoint_file_delete(self, monkeypatch):
def get_drive(drive_name):
assert drive_name == self.drive_name
def get_item(drive, path):
assert drive == self.drive_name
assert path == self.path
with NamedTemporaryFile() as file:
monkeypatch.setattr(Site, "list_document_libraries", get_drive)
monkeypatch.setattr(Drive, "get_item_by_path", get_item)
self.client.delete_file(file, self.drive_name, self.path)
How can I mock these library classes with their methods instead of trying to patch every single method this way?