Skip to content

Instantly share code, notes, and snippets.

@jacobbridges
Created January 26, 2017 20:05
Show Gist options
  • Save jacobbridges/6a800f66c847703828cacc74e8d536f3 to your computer and use it in GitHub Desktop.
Save jacobbridges/6a800f66c847703828cacc74e8d536f3 to your computer and use it in GitHub Desktop.
Testing async code
class PersonClass(object):
def __init__(self, name=None, cursor=None):
"""Constructor for PersonClass."""
self.name = name
self.cursor = cursor
self.insert_sql = 'INSERT INTO person VALUES ?;'
async def create(self):
"""Persist the person to the database."""
return await self.cursor.execute(self.insert_sql, (self.name,))
import asyncio
import pytest
from unittest.mock import MagicMock
from my_code import PersonClass
class TestPersonModule(object):
@pytest.mark.asyncio
async def test_send_query_on_create(self):
"""Should send insert query to database on create()"""
# Stub the database cursor
database_cursor = MagicMock()
# Create a future to stub the results from the database cursor
result_future = asyncio.Future()
result_future.set_result('future result!')
database_cursor.execute.return_value = result_future
# Instantiate new person obj
person = PersonClass(name='Johnny', cursor=database_cursor)
# Call person.create() to trigger the database call
person_create_response = await person.create()
# Assert the response from person.create() is our predefined future
assert person_create_response == 'future result!'
# Assert the database cursor was called once
database_cursor.execute.assert_called_once_with(person.insert_sql, ('Johnny',))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment