I'm transferring data from a legacy system into Django. In order to ensure the current database's integrity, I'm committing everything manually.
However, when writing unit tests, the transactions won't rollback properly. Since TestCase
is probably using transactions, is there any way to properly test code in Django that relies on transactions?
@transaction.commit_manually
def import_records():
# initial prep
try:
import_data()
except Exception as error:
rollback = True
except (KeyboardInterrupt, SystemExit):
sys.stdout.write("Import canceled\n")
rollback = True
if rollback is True:
transaction.rollback()
# save history of import
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
Tying transactions to HTTP requests A common way to handle transactions on the web is to wrap each request in a transaction. Set ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior. It works like this.
from the docs: When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). The TEST dictionary in DATABASES offers a number of settings to configure your test database.
I believe you are looking for TransactionTestCase
which handles setup and teardown differently then the normal TestCase
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With