I'm trying to test a function that looks like this that calls an SDK.
FUNCTION TO BE TESTED
def create_folder_if_not_exists(
sdk: looker_sdk,
folder_name: str,
parent_id: str) -> dict:
folder = sdk.search_folders(name=folder_name)
if folder or parent_id == '1':
folder = folder[0]
raise Exception(
f"Folder {folder_name} already exists or is a reserved folder")
else:
parent_id = sdk.search_folders(name=parent_id)[0].id
logger.info(f'Creating folder "{folder_name}"')
folder = sdk.create_folder(
body=models.CreateFolder(
name=folder_name,
parent_id=parent_id
)
)
return folder
The test that i'm writing has to be able to mock the search_folders
endpoint in two different ways, first passing no value, then passing a value for the else condition, which should return an id
field. The library i've been using is pytest and trying to use side effects but i'm fairly new to testing and not sure how to do this. My current code is as follows
Creating a few mock objects that mimic the api structure
class MockSDK():
def search_folders(self):
pass
def create_folder(self):
pass
class MockSearchFolder():
def __init__(self, parent_id, name):
self.parent_id = parent_id
self.name = name
class MockCreateFolder():
def __init__(self, parent_id, folder_name):
self.parent_id = parent_id
self.folder_name = folder_name
Defining a side_effect with two values where I return the side effects
def mock_search_folder(**kwargs):
if kwargs.get('folder_name') == 'googn':
return None
else:
return MockSearchFolder(parent_id='frankie fish', name='nice guy eddie')
def test_create_folder_if_not_exists():
# Tests the creation of a folder if it doesn't exist or have a parent id of 1
sdk = MockSDK()
tt = MockSearchFolder(name='dd', parent_id='dddd')
with unittest.mock.patch.object(sdk, 'search_folders', side_effect=mock_search_folder) as sf:
test = fc.create_folder_if_not_exists(
sdk=sdk, folder_name='googn', parent_folder_name='4')
assert test == 'frank'
I don't think i'm passing return values in the with statement, but perhaps i'm wrong.
Would anyone be able to take a glance at this and tell me what i'm doing wrong ? Thank you!