Search code examples
djangodjango-testing

How to test/simulate broken database connection


I have written logic to return custom errors when my application cannot connect to the database (why that can happen is out of the scope for this question). I wish to write unit tests for this, specifically to see the response status codes when:

  1. there is a valid connection to the database. This is easy as Django automatically creates a "test" database whenever I run any tests.
  2. there isn't a valid connection to the database. Unfortunately, I cannot find any documentation about this.

Is it possible to run that test by somehow simulating that something has gone wrong with the database connection?


Solution

  • Rather than simulating a failed connection, you could simply raise your custom error during the test.

    raise customConnectionError('oops')
    

    Another possibility is using the destroy_test_db method from django.db.connection.creation to close the connection to your database.

    from django.db.connection.creation import destroy_test_db
    
    
    destroy_test_db('your_database_name', keepdb=True)
    

    For more information please consult Django Docs: destroy_test_db.