django unit tests without a db

前端 未结 11 1500
醉梦人生
醉梦人生 2020-11-29 16:11

Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn\'t require the db to set up. And while it is fast to setu

11条回答
  •  暖寄归人
    2020-11-29 16:55

    As an alternative to modifying your settings to make NoDbTestRunner "safe", here's a modified version of NoDbTestRunner that closes the current database connection and removes the connection information from settings and the connection object. Works for me, test it in your environment before relying on it :)

    class NoDbTestRunner(DjangoTestSuiteRunner):
        """ A test runner to test without database creation """
    
        def __init__(self, *args, **kwargs):
            # hide/disconnect databases to prevent tests that 
            # *do* require a database which accidentally get 
            # run from altering your data
            from django.db import connections
            from django.conf import settings
            connections.databases = settings.DATABASES = {}
            connections._connections['default'].close()
            del connections._connections['default']
            super(NoDbTestRunner,self).__init__(*args,**kwargs)
    
        def setup_databases(self, **kwargs):
            """ Override the database creation defined in parent class """
            pass
    
        def teardown_databases(self, old_config, **kwargs):
            """ Override the database teardown defined in parent class """
            pass
    

提交回复
热议问题