"""Tests for database module.""" from unittest.mock import Mock from pytest import raises from api.utils import database def test_context(): """Test context function.""" cursor = Mock() connection = Mock() connection.cursor.return_value = cursor with database.context(connection) as (tcursor, tconnection): # these asserts also guarantee rollbacks and explicit commits are # called assert tcursor == cursor assert tconnection == connection tcursor.execute('foo') assert not tconnection.commit.called cursor.execute.assert_called_once_with('foo') assert cursor.close.called assert connection.commit.called assert connection.close.called def test_context_exception(): """Test context function when an exception is raised.""" cursor = Mock() connection = Mock() connection.cursor.return_value = cursor with raises(BaseException): with database.context(connection) as (tcursor, tconnection): tcursor.execute('foo bar baz') raise BaseException() assert not connection.commit.called cursor.execute.assert_called_once_with('foo bar baz') assert connection.rollback.called