Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test manual DB transaction code in Django?

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
like image 269
strongriley Avatar asked Apr 11 '13 17:04

strongriley


People also ask

How do I run a test in Django?

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.

What is the correct way to manage database transactions during an HTTP request?

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.

Where does Django store test database?

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.


1 Answers

I believe you are looking for TransactionTestCase which handles setup and teardown differently then the normal TestCase.

like image 102
Ngenator Avatar answered Nov 10 '22 13:11

Ngenator