Skip to content

Commit

Permalink
Add transactionSubTest (#36)
Browse files Browse the repository at this point in the history
Closes #35
  • Loading branch information
RoTranDo authored Nov 30, 2023
1 parent ead5892 commit 7fdf60c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
24 changes: 22 additions & 2 deletions anfema_django_testutils/testcases.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,18 +194,38 @@ def assertNotRaises(
raise self.fail(self._formatMessage(msg, standard_msg))


class TransactionTestCaseMixin(TestCaseMixin):
@contextlib.contextmanager
def transactionSubTest(self, msg=None, **params):
"""Like :meth:`unittest.TestCase.subTest`, but runs within a transaction and ensures this transaction
is rolled back afterward.
On database backends with no transaction support, :meth:`transactionSubTest` behaves as
:meth:`unittest.TestCase.subTest`.
:param str msg: Optional message used in case of failure.
:param \\**params: Additional information or context for the subtest.
"""
if databases_support_transactions := self._databases_support_transactions():
atomics = self._enter_atomics()
with self.subTest(**(params | ({} if msg is None else {"msg": msg}))):
yield
if databases_support_transactions:
self._rollback_atomics(atomics)


class SimpleTestCase(TestCaseMixin, DjangoSimpleTestCase):
"""Extends the :class:`django.test.SimpleTestCase` class with a precondition failure status."""


class TransactionTestCase(TestCaseMixin, DjangoTransactionTestCase):
class TransactionTestCase(TransactionTestCaseMixin, DjangoTransactionTestCase):
"""Extends the :class:`django.test.TransactionTestCase` class with a precondition failure status.
.. seealso:: :class:`SimpleTestCase`
"""


class TestCase(TestCaseMixin, DjangoTestCase):
class TestCase(TransactionTestCaseMixin, DjangoTestCase):
"""Extends the :class:`django.test.TestCase` class with a precondition failure status.
.. seealso:: :class:`SimpleTestCase`
Expand Down
4 changes: 2 additions & 2 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ anfema_django_testutils.testcases
:inherited-members:

.. autoclass:: anfema_django_testutils.testcases.TransactionTestCase
:members:
:members: transactionSubTest

.. autoclass:: anfema_django_testutils.testcases.TestCase
:members:
:members: transactionSubTest


anfema_django_testutils.tags
Expand Down

0 comments on commit 7fdf60c

Please sign in to comment.