I’ve tried multiple ways and just can’t get the result I’m looking for. It seems like a lost of questions use a different type of mocking with the whole @patch decorators but I’ve been using this more simplified version. I just can’t figure out how to mock one function
Main class
from databaseClass import scan_all
class JobsDB:
def __init__(self, jobs_table):
self.jobs_table = jobs_table
async def get_all_jobs(self, include_executions=False):
response = await scan_all(self.jobs_table)
if include_executions:
return [JobWithExecutions(**item) for item in response]
return [Job(**item) for item in response]
Database class
async def scan_all(table, **kwargs):
response = await table.scan(**kwargs)
items = response['Items']
while 'LastEvaluatedKey' in response:
response = await table.scan(**kwargs, ExclusiveStartKey=response['LastEvaluatedKey'])
items = items + response['Items']
return items
Test Class
import pytest
from unittest.mock import AsyncMock, MagicMock
from db import JobsDB, Job
@pytest.fixture
def mock_scan_all():
return AsyncMock()
@pytest.fixture
def jobs_table():
return AsyncMock()
@pytest.fixture
def jobs_db():
return JobsDB(AsyncMock())
@pytest.fixture
def job():
return Job(
id='1839e18a-898b-42d1-8747-9b5495dbb0a6',
status='PENDING',
description='Test',
start_date='2024-01-22T13:00:00.000Z',
end_date='2024-01-22T14:00:00.000Z',
@pytest.mark.database
@pytest.mark.asyncio
async def test_get_all_jobs(jobs_db, jobs_table, mock_scan_all, job):
# This used a mock_scan_all fixture in the parameters
mock_scan_all.return_value = [vars(job)]
jobs_table.scan_all = mock_scan_all
# Call the get_all_jobs method
result = await jobs_db.get_all_jobs()
# jobs_db.scan_all.assert_called_once_with(jobs_db.jobs_table)
# Assert that the result is a list containing the expected Job object
assert result == [job]
What I Tried:
# Didn't work
# jobs_db.jobs_table.scan_all = AsyncMock(return_value=[vars(job)])
# Didn't work
# jobs_db.scan_all.return_value = [vars(job)]
# Didn't work
# scan_all = AsyncMock()
# scan_all.return_value = [vars(job)]
# Didn't work
# mock = AsyncMock()
# mock.scan_all.return_value = [vars(job)]
# Didn't work
# mock_scan_all = AsyncMock()
# mock_scan_all.return_value = [vars(job)]
# jobs_table = MagicMock()
# jobs_table.scan_all = mock_scan_all
# Didn't work
# jobs_table.scan.return_value = {'Items': [vars(job) for job in jobs]}
I’m consistently getting a Failed message saying the right side contains more items than the left. The left contains none.
assert [] == [Job]
I’ve also tried to assert if it’s ever been called once and it’s always returned a result of 0.
Darius Fiallo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.