Esempio n. 1
0
 def test_empty_default_database(self):
     """
     Test that an empty default database in settings does not raise an ImproperlyConfigured
     error when running a unit test that does not use a database.
     """
     testcases.connections = db.ConnectionHandler({"default": {}})
     connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS]
     self.assertEqual(connection.settings_dict["ENGINE"], "django.db.backends.dummy")
     connections_support_transactions()
Esempio n. 2
0
 def test_empty_default_database(self):
     """
     An empty default database in settings does not raise an ImproperlyConfigured
     error when running a unit test that does not use a database.
     """
     testcases.connections = db.ConnectionHandler({'default': {}})
     connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS]
     self.assertEqual(connection.settings_dict['ENGINE'], 'django.db.backends.dummy')
     connections_support_transactions()
Esempio n. 3
0
 def test_empty_default_database(self):
     """
     An empty default database in settings does not raise an ImproperlyConfigured
     error when running a unit test that does not use a database.
     """
     tested_connections = db.ConnectionHandler({"default": {}})
     with mock.patch("django.db.connections", new=tested_connections):
         connection = tested_connections[db.utils.DEFAULT_DB_ALIAS]
         self.assertEqual(connection.settings_dict["ENGINE"],
                          "django.db.backends.dummy")
         connections_support_transactions()
Esempio n. 4
0
File: tests.py Progetto: ATNC/django
 def test_empty_default_database(self):
     """
     Test that an empty default database in settings does not raise an ImproperlyConfigured
     error when running a unit test that does not use a database.
     """
     testcases.connections = db.ConnectionHandler({'default': {}})
     connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS]
     self.assertEqual(connection.settings_dict['ENGINE'], 'django.db.backends.dummy')
     try:
         connections_support_transactions()
     except Exception as e:
         self.fail("connections_support_transactions() unexpectedly raised an error: %s" % e)
Esempio n. 5
0
 def test_transaction_support(self):
     # Assert connections mocking is appropriately applied by preventing
     # any attempts at calling create_test_db on the global connection
     # objects.
     for connection in db.connections.all():
         create_test_db = mock.patch.object(
             connection.creation,
             'create_test_db',
             side_effect=AssertionError("Global connection object shouldn't be manipulated.")
         )
         create_test_db.start()
         self.addCleanup(create_test_db.stop)
     for option_key, option_value in (
             ('NAME', ':memory:'), ('TEST', {'NAME': ':memory:'})):
         tested_connections = db.ConnectionHandler({
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
             'other': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
         })
         with mock.patch('django.test.utils.connections', new=tested_connections):
             other = tested_connections['other']
             DiscoverRunner(verbosity=0).setup_databases()
             msg = (
                 "DATABASES setting '%s' option set to sqlite3's ':memory:' value "
                 "shouldn't interfere with transaction support detection." % option_key
             )
             # Transaction support is properly initialized for the 'other' DB.
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs report that they support transactions.
             self.assertTrue(connections_support_transactions(), msg)
Esempio n. 6
0
    def test_mydb(self, mydb):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        # Check the fixture had access to the db
        item = Item.objects.get(name="spam")
        assert item
Esempio n. 7
0
    def _fixture_setup (self):
        print 'IN VIEWS TESTS BEFORE'
        from django.test.testcases import connections_support_transactions, transaction, disable_transaction_methods, call_command
        if not connections_support_transactions():
            return super(TestCase, self)._fixture_setup()

        assert not self.reset_sequences, 'reset_sequences cannot be used on TestCase instances'

        self.atomics = {}
        for db_name in self._databases_names():
            self.atomics[db_name] = transaction.atomic(using=db_name)
            self.atomics[db_name].__enter__()
        # Remove this when the legacy transaction management goes away.
        disable_transaction_methods()

        for db_name in self._databases_names(include_mirrors=False):
            if self.fixtures:
                try:
                    call_command('loaddata', *self.fixtures,
                                 **{
                                     'verbosity': 1,
                                     'commit': False,
                                     'database': db_name,
                                     'skip_checks': False,
                                 })
                except Exception, e:
                    print 'DBNAME', db_name
                    self._fixture_teardown()

                    if breakpoint:
                      from IPython import embed
                      embed()  # breaks into an ipython shell here!

                    raise
Esempio n. 8
0
    def _fixture_setup(self):
        if not connections_support_transactions():
            raise

        # If the test case has a multi_db=True flag, setup all databases.
        # Otherwise, just use default.
        if getattr(self, 'multi_db', False):
            databases = connections
        else:
            databases = [DEFAULT_DB_ALIAS]

        for db in databases:
            transaction.enter_transaction_management(using=db)
            transaction.managed(True, using=db)
        disable_transaction_methods()

        from django.contrib.sites.models import Site
        Site.objects.clear_cache()

        

        for db in databases:
            if hasattr(self, 'fixtures'):
                fixtures = [ __package__+'_'+fixture for fixture in self.fixtures]
                call_command('loaddata', *fixtures, **{
                                                            'verbosity': 1,
                                                            'commit': False,
                                                            'database': db
                                                            })
Esempio n. 9
0
File: tests.py Progetto: ATNC/django
 def test_transaction_support(self):
     """Ticket #16329: sqlite3 in-memory test databases"""
     old_db_connections = db.connections
     for option_key, option_value in (
             ('NAME', ':memory:'), ('TEST', {'NAME': ':memory:'})):
         try:
             db.connections = db.ConnectionHandler({
                 'default': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option_key: option_value,
                 },
                 'other': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option_key: option_value,
                 },
             })
             other = db.connections['other']
             DiscoverRunner(verbosity=0).setup_databases()
             msg = "DATABASES setting '%s' option set to sqlite3's ':memory:' value shouldn't interfere with transaction support detection." % option_key
             # Transaction support should be properly initialized for the 'other' DB
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs should report that they support transactions
             self.assertTrue(connections_support_transactions(), msg)
         finally:
             db.connections = old_db_connections
Esempio n. 10
0
 def test_transaction_support(self):
     for option_key, option_value in (('NAME', ':memory:'), ('TEST', {
             'NAME':
             ':memory:'
     })):
         tested_connections = db.ConnectionHandler({
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
             'other': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
         })
         with mock.patch('django.db.connections', new=tested_connections):
             with mock.patch('django.test.testcases.connections',
                             new=tested_connections):
                 other = tested_connections['other']
                 DiscoverRunner(verbosity=0).setup_databases()
                 msg = (
                     "DATABASES setting '%s' option set to sqlite3's ':memory:' value "
                     "shouldn't interfere with transaction support detection."
                     % option_key)
                 # Transaction support should be properly initialized for the 'other' DB
                 self.assertTrue(other.features.supports_transactions, msg)
                 # And all the DBs should report that they support transactions
                 self.assertTrue(connections_support_transactions(), msg)
Esempio n. 11
0
 def test_transaction_support(self):
     # Assert connections mocking is appropriately applied by preventing
     # any attempts at calling create_test_db on the global connection
     # objects.
     for connection in db.connections.all():
         create_test_db = mock.patch.object(
             connection.creation,
             'create_test_db',
             side_effect=AssertionError("Global connection object shouldn't be manipulated.")
         )
         create_test_db.start()
         self.addCleanup(create_test_db.stop)
     for option_key, option_value in (
             ('NAME', ':memory:'), ('TEST', {'NAME': ':memory:'})):
         tested_connections = db.ConnectionHandler({
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
             'other': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 option_key: option_value,
             },
         })
         with mock.patch('django.test.utils.connections', new=tested_connections):
             other = tested_connections['other']
             DiscoverRunner(verbosity=0).setup_databases()
             msg = (
                 "DATABASES setting '%s' option set to sqlite3's ':memory:' value "
                 "shouldn't interfere with transaction support detection." % option_key
             )
             # Transaction support is properly initialized for the 'other' DB.
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs report that they support transactions.
             self.assertTrue(connections_support_transactions(), msg)
    def test_mydb(self, mydb):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        # Check the fixture had access to the db
        item = Item.objects.get(name="spam")
        assert item
Esempio n. 13
0
 def test_transaction_support(self):
     """Ticket #16329: sqlite3 in-memory test databases"""
     old_db_connections = db.connections
     for option_key, option_value in (('NAME', ':memory:'), ('TEST', {
             'NAME':
             ':memory:'
     })):
         try:
             db.connections = db.ConnectionHandler({
                 'default': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option_key: option_value,
                 },
                 'other': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option_key: option_value,
                 },
             })
             other = db.connections['other']
             DiscoverRunner(verbosity=0).setup_databases()
             msg = "DATABASES setting '%s' option set to sqlite3's ':memory:' value shouldn't interfere with transaction support detection." % option_key
             # Transaction support should be properly initialized for the 'other' DB
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs should report that they support transactions
             self.assertTrue(connections_support_transactions(), msg)
         finally:
             db.connections = old_db_connections
Esempio n. 14
0
    def _fixture_setup(self):
        global loaded_fixtures

        if not connections_support_transactions():
            if hasattr(self, 'perma_fixtures'):
                if not hasattr(self, 'fixtures'):
                    self.fixtures = self.perma_fixtures
                else:
                    self.fixtures += self.perma_fixtures
            return super(TestCase, self)._fixture_setup()

        # If the test case has a multi_db=True flag, setup all databases.
        # Otherwise, just use default.
        if getattr(self, 'multi_db', False):
            databases = connections
        else:
            databases = [DEFAULT_DB_ALIAS]

        for db in databases:
            if hasattr(self, 'perma_fixtures'):
                fixtures = [ fixture for fixture in self.perma_fixtures if not fixture in loaded_fixtures ]
                if fixtures:
                    call_command('loaddata', *fixtures, **{
                                                            'verbosity': 0,
                                                            'commit': False,
                                                            'database': db
                                                            })
                loaded_fixtures += fixtures

        super(TestCase, self)._fixture_setup()
Esempio n. 15
0
    def _pre_setup(self):
        if not connections_support_transactions():
            fixtures = [
                "sample_users", "sample_site", "sample_languages",
                "sample_data"
            ]
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]
            for db in databases:
                management.call_command('flush',
                                        verbosity=0,
                                        interactive=False,
                                        database=db)
                management.call_command('loaddata', *fixtures, **{
                    'verbosity': 0,
                    'database': db
                })

        else:
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            for db in databases:
                transaction.enter_transaction_management(using=db)
                transaction.managed(True, using=db)
            disable_transaction_methods()
        mail.outbox = []
Esempio n. 16
0
 def _start_test_transaction():
     if connections_support_transactions():
         transaction.enter_transaction_management(using='default')
         transaction.managed(True, using='default')
     else:
         call_command('flush', verbosity=0, interactive=False,
                      database='default')
     disable_transaction_methods()
Esempio n. 17
0
 def _start_test_transaction():
     if connections_support_transactions():
         transaction.enter_transaction_management(using='default')
         transaction.managed(True, using='default')
     else:
         call_command('flush', verbosity=0, interactive=False,
                      database='default')
     disable_transaction_methods()
Esempio n. 18
0
    def test_transactions_enabled_via_reset_seq(
        self,
        django_db_reset_sequences: None,
    ) -> None:
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block
Esempio n. 19
0
        def fast_fixture_setup(instance):
            if not connections_support_transactions():
                return super(TestCase, instance)._fixture_setup()

            fixtures = getattr(instance, 'fixtures', [])

            loaddata = fixtures
            flush_db = True
            if len(self.currernt_fixtures) <= len(fixtures):
                if fixtures[:len(self.currernt_fixtures
                                 )] == self.currernt_fixtures:
                    # current fixtures are still OK
                    loaddata = fixtures[len(self.currernt_fixtures):]
                    self.fixtures_prevented += len(self.currernt_fixtures)
                    flush_db = False

            if flush_db:
                ContentType.objects.clear_cache()
                self.flushes += 1
                self.currernt_fixtures = []
                for db in connections:
                    call_command('flush',
                                 verbosity=0,
                                 interactive=False,
                                 database=db)

            if len(loaddata):
                self.fixtures += len(loaddata)
                self.fixtures_sets.append(self.currernt_fixtures + loaddata)
                for db in connections:
                    call_command(
                        'loaddata', *loaddata, **{
                            'verbosity': 0,
                            'commit': True,
                            'database': db
                        })
            self.currernt_fixtures = fixtures

            # If the test case has a multi_db=True flag, setup all databases.
            # Otherwise, just use default.
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            instance.atomics = {}

            for db in databases:
                instance.atomics[db] = transaction.atomic(using=db)
                instance.atomics[db].__enter__()
            disable_transaction_methods()

            from django.contrib.sites import get_site_model
            Site = get_site_model()
            Site.objects.clear_cache()
Esempio n. 20
0
    def _post_teardown(self):
        if connections_support_transactions():
            # If the test case has a multi_db=True flag, teardown all databases.
            # Otherwise, just teardown default.
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            restore_transaction_methods()
            for db in databases:
                transaction.rollback(using=db)
                transaction.leave_transaction_management(using=db)
        for connection in connections.all():
            connection.close()
Esempio n. 21
0
    def _post_teardown(self):
        if connections_support_transactions():
            # If the test case has a multi_db=True flag, teardown all databases.
            # Otherwise, just teardown default.
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            restore_transaction_methods()
            for db in databases:
                transaction.rollback(using=db)
                transaction.leave_transaction_management(using=db)
        for connection in connections.all():
            connection.close()
Esempio n. 22
0
        def fast_fixture_setup(instance):
            if not connections_support_transactions():
                return super(TestCase, instance)._fixture_setup()

            fixtures = getattr(instance, 'fixtures', [])

            loaddata = fixtures
            flush_db = True
            if len(self.currernt_fixtures) <= len(fixtures):
                if fixtures[:len(self.currernt_fixtures)] == self.currernt_fixtures:
                    # current fixtures are still OK
                    loaddata = fixtures[len(self.currernt_fixtures):]
                    self.fixtures_prevented += len(self.currernt_fixtures)
                    flush_db = False

            if flush_db:
                ContentType.objects.clear_cache()
                self.flushes += 1
                self.currernt_fixtures = []
                for db in connections:
                    call_command('flush', verbosity=0, interactive=False, database=db)

            if len(loaddata):
                self.fixtures += len(loaddata)
                self.fixtures_sets.append(self.currernt_fixtures + loaddata)
                for db in connections:
                    call_command('loaddata', *loaddata, **{
                                                        'verbosity': 0,
                                                        'commit': True,
                                                        'database': db
                                                        })
            self.currernt_fixtures = fixtures

            # If the test case has a multi_db=True flag, setup all databases.
            # Otherwise, just use default.
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            for db in databases:
                transaction.enter_transaction_management(using=db)
                transaction.managed(True, using=db)
            disable_transaction_methods()

            from django.contrib.sites.models import Site
            Site.objects.clear_cache()
Esempio n. 23
0
        def fast_fixture_setup(instance):
            if not connections_support_transactions():
                return super(TestCase, instance)._fixture_setup()

            fixtures = getattr(instance, "fixtures", [])

            loaddata = fixtures
            flush_db = True
            if len(self.currernt_fixtures) <= len(fixtures):
                if fixtures[: len(self.currernt_fixtures)] == self.currernt_fixtures:
                    # current fixtures are still OK
                    loaddata = fixtures[len(self.currernt_fixtures) :]
                    self.fixtures_prevented += len(self.currernt_fixtures)
                    flush_db = False

            if flush_db:
                ContentType.objects.clear_cache()
                self.flushes += 1
                self.currernt_fixtures = []
                for db in connections:
                    call_command("flush", verbosity=0, interactive=False, database=db)

            if len(loaddata):
                self.fixtures += len(loaddata)
                self.fixtures_sets.append(self.currernt_fixtures + loaddata)
                for db in connections:
                    call_command("loaddata", *loaddata, **{"verbosity": 0, "commit": True, "database": db})
            self.currernt_fixtures = fixtures

            # If the test case has a multi_db=True flag, setup all databases.
            # Otherwise, just use default.
            if getattr(self, "multi_db", False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            instance.atomics = {}

            for db in databases:
                instance.atomics[db] = transaction.atomic(using=db)
                instance.atomics[db].__enter__()
            disable_transaction_methods()

            from django.contrib.sites import get_site_model

            Site = get_site_model()
            Site.objects.clear_cache()
Esempio n. 24
0
 def test_transaction_support(self):
     """Ticket #16329: sqlite3 in-memory test databases"""
     for option_key, option_value in (("NAME", ":memory:"), ("TEST", {"NAME": ":memory:"})):
         tested_connections = db.ConnectionHandler(
             {
                 "default": {"ENGINE": "django.db.backends.sqlite3", option_key: option_value},
                 "other": {"ENGINE": "django.db.backends.sqlite3", option_key: option_value},
             }
         )
         with mock.patch("django.db.connections", new=tested_connections):
             with mock.patch("django.test.testcases.connections", new=tested_connections):
                 other = tested_connections["other"]
                 DiscoverRunner(verbosity=0).setup_databases()
                 msg = (
                     "DATABASES setting '%s' option set to sqlite3's ':memory:' value "
                     "shouldn't interfere with transaction support detection." % option_key
                 )
                 # Transaction support should be properly initialized for the 'other' DB
                 self.assertTrue(other.features.supports_transactions, msg)
                 # And all the DBs should report that they support transactions
                 self.assertTrue(connections_support_transactions(), msg)
Esempio n. 25
0
    def setUpClass(cls):
        super(TestCase, cls).setUpClass()
        if not connections_support_transactions():
            return
        cls.cls_atomics = cls._enter_atomics()

        if cls.fixtures:
            for db_name in cls._databases_names(include_mirrors=False):
                    try:
                        call_command('loaddatabulk', *cls.fixtures, **{
                            'verbosity': 0,
                            'commit': False,
                            'database': db_name,
                        })
                    except Exception:
                        cls._rollback_atomics(cls.cls_atomics)
                        raise
        try:
            cls.setUpTestData()
        except Exception:
            cls._rollback_atomics(cls.cls_atomics)
            raise
Esempio n. 26
0
 def test_transaction_support(self):
     """Ticket #16329: sqlite3 in-memory test databases"""
     old_db_connections = db.connections
     for option in ("NAME", "TEST_NAME"):
         try:
             db.connections = db.ConnectionHandler(
                 {
                     "default": {"ENGINE": "django.db.backends.sqlite3", option: ":memory:"},
                     "other": {"ENGINE": "django.db.backends.sqlite3", option: ":memory:"},
                 }
             )
             other = db.connections["other"]
             DjangoTestSuiteRunner(verbosity=0).setup_databases()
             msg = (
                 "DATABASES setting '%s' option set to sqlite3's ':memory:' value shouldn't interfere with transaction support detection."
                 % option
             )
             # Transaction support should be properly initialised for the 'other' DB
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs should report that they support transactions
             self.assertTrue(connections_support_transactions(), msg)
         finally:
             db.connections = old_db_connections
Esempio n. 27
0
    def setUpClass(cls):
        super(TestCase, cls).setUpClass()
        if not connections_support_transactions():
            return
        cls.cls_atomics = cls._enter_atomics()

        if cls.fixtures:
            for db_name in cls._databases_names(include_mirrors=False):
                try:
                    call_command(
                        'loaddatabulk', *cls.fixtures, **{
                            'verbosity': 0,
                            'commit': False,
                            'database': db_name,
                        })
                except Exception:
                    cls._rollback_atomics(cls.cls_atomics)
                    raise
        try:
            cls.setUpTestData()
        except Exception:
            cls._rollback_atomics(cls.cls_atomics)
            raise
Esempio n. 28
0
    def _pre_setup(self):
        if not connections_support_transactions():
            fixtures = ["sample_users", "sample_site", "sample_languages", "sample_data"]
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]
            for db in databases:
                management.call_command('flush', verbosity=0,
                interactive=False, database=db)
                management.call_command('loaddata', *fixtures, **{
                    'verbosity': 0, 'database': db})

        else:
            if getattr(self, 'multi_db', False):
                databases = connections
            else:
                databases = [DEFAULT_DB_ALIAS]

            for db in databases:
                transaction.enter_transaction_management(using=db)
                transaction.managed(True, using=db)
            disable_transaction_methods()
        mail.outbox = []
Esempio n. 29
0
    def test_transactions_disabled_explicit(self):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert noop_transactions()
Esempio n. 30
0
 def _end_test_transaction():
     restore_transaction_methods()
     if connections_support_transactions():
         transaction.rollback(using='default')
         transaction.leave_transaction_management(using='default')
Esempio n. 31
0
    def test_transactions_enabled_via_reset_seq(
            self, django_db_reset_sequences):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not connection.in_atomic_block
Esempio n. 32
0
    def test_transactions_disabled(self, db):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert noop_transactions()
Esempio n. 33
0
    def test_transactions_disabled_explicit(self):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert connection.in_atomic_block
Esempio n. 34
0
    def test_transactions_enabled(self, transactional_db):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not connection.in_atomic_block
Esempio n. 35
0
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """
    worsk exactly as per normal test
    but only creates the test_db if it doesn't yet exist
    and does not destroy it when done
    tables are flushed and fixtures loaded between tests as per usual
    but if your schema has not changed then this saves significant amounts of time
    and speeds up the test cycle

    Run the unit tests for all the test labels in the provided list.
    Labels must be of the form:
     - app.TestClass.test_method
        Run a single specific test method
     - app.TestClass
        Run all the test methods in a given class
     - app
        Search for doctests and unittests in the named application.

    When looking for tests, the test runner will look in the models and
    tests modules for the application.

    A list of 'extra' tests may also be provided; these tests
    will be added to the test suite.

    Returns the number of tests that failed.
    """
    setup_test_environment()

    settings.DEBUG = False
    suite = unittest.TestSuite()

    if test_labels:
        for label in test_labels:
            if '.' in label:
                suite.addTest(build_test(label))
            else:
                app = apps.get_app(label)
                suite.addTest(build_suite(app))
    else:
        for app in apps.get_apps():
            suite.addTest(build_suite(app))

    for test in extra_tests:
        suite.addTest(test)

    suite = reorder_suite(suite, (TestCase, ))

    old_name = settings.DATABASES['default']['NAME']

    # Everything up to here is from django.test.simple

    from django.db.backends import creation
    from django.db import connection, DatabaseError

    if settings.DATABASES['default']['TEST_NAME']:
        settings.DATABASES['default']['NAME'] = settings.DATABASES['default'][
            'TEST_NAME']
    else:
        settings.DATABASES['default'][
            'NAME'] = creation.TEST_DATABASE_PREFIX + settings.DATABASES[
                'default']['NAME']
    connection.settings_dict["DATABASE_NAME"] = settings.DATABASES['default'][
        'NAME']

    # does test db exist already ?
    try:
        if settings.DATABASES['default']['ENGINE'] == 'sqlite3':
            if not os.path.exists(settings.DATABASES['default']['NAME']):
                raise DatabaseError
        cursor = connection.cursor()
    except Exception:
        # db does not exist
        # juggling !  create_test_db switches the DATABASE_NAME to the TEST_DATABASE_NAME
        settings.DATABASES['default']['NAME'] = old_name
        connection.settings_dict["DATABASE_NAME"] = old_name
        connection.creation.create_test_db(verbosity, autoclobber=True)
    else:
        connection.close()

    settings.DATABASES['default'][
        'SUPPORTS_TRANSACTIONS'] = connections_support_transactions()

    result = unittest.TextTestRunner(verbosity=verbosity).run(suite)

    # Since we don't call destory_test_db, we need to set the db name back.
    settings.DATABASES['default']['NAME'] = old_name
    connection.settings_dict["DATABASE_NAME"] = old_name
    teardown_test_environment()

    return len(result.failures) + len(result.errors)
    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not noop_transactions()
Esempio n. 37
0
 def _end_test_transaction():
     restore_transaction_methods()
     if connections_support_transactions():
         transaction.rollback(using='default')
         transaction.leave_transaction_management(using='default')
    def test_transactions_disabled_explicit(self):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert connection.in_atomic_block
Esempio n. 39
0
    def test_transactions_enabled(self, transactional_db):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert not noop_transactions()
Esempio n. 40
0
    def test_transactions_disabled_explicit(self):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert noop_transactions()
Esempio n. 41
0
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """
    worsk exactly as per normal test
    but only creates the test_db if it doesn't yet exist
    and does not destroy it when done
    tables are flushed and fixtures loaded between tests as per usual
    but if your schema has not changed then this saves significant amounts of time
    and speeds up the test cycle

    Run the unit tests for all the test labels in the provided list.
    Labels must be of the form:
     - app.TestClass.test_method
        Run a single specific test method
     - app.TestClass
        Run all the test methods in a given class
     - app
        Search for doctests and unittests in the named application.

    When looking for tests, the test runner will look in the models and
    tests modules for the application.

    A list of 'extra' tests may also be provided; these tests
    will be added to the test suite.

    Returns the number of tests that failed.
    """
    setup_test_environment()

    settings.DEBUG = False
    suite = unittest.TestSuite()

    if test_labels:
        for label in test_labels:
            if '.' in label:
                suite.addTest(build_test(label))
            else:
                app = get_app(label)
                suite.addTest(build_suite(app))
    else:
        for app in get_apps():
            suite.addTest(build_suite(app))

    for test in extra_tests:
        suite.addTest(test)

    suite = reorder_suite(suite, (TestCase,))

    old_name = settings.DATABASES['default']['NAME']

    ###Everything up to here is from django.test.simple

    from django.db.backends import creation
    from django.db import connection, DatabaseError

    if settings.DATABASES['default']['TEST_NAME']:
        settings.DATABASES['default']['NAME'] = settings.DATABASES['default']['TEST_NAME']
    else:
        settings.DATABASES['default']['NAME'] = creation.TEST_DATABASE_PREFIX + settings.DATABASES['default']['NAME']
    connection.settings_dict["DATABASE_NAME"] = settings.DATABASES['default']['NAME']

    # does test db exist already ?
    try:
        if settings.DATABASES['default']['ENGINE'] == 'sqlite3':
            if not os.path.exists(settings.DATABASES['default']['NAME']):
                raise DatabaseError
        cursor = connection.cursor()
    except Exception:
        # db does not exist
        # juggling !  create_test_db switches the DATABASE_NAME to the TEST_DATABASE_NAME
        settings.DATABASES['default']['NAME'] = old_name
        connection.settings_dict["DATABASE_NAME"] = old_name
        connection.creation.create_test_db(verbosity, autoclobber=True)
    else:
        connection.close()

    settings.DATABASES['default']['SUPPORTS_TRANSACTIONS'] = connections_support_transactions()

    result = unittest.TextTestRunner(verbosity=verbosity).run(suite)

    #Since we don't call destory_test_db, we need to set the db name back.
    settings.DATABASES['default']['NAME'] = old_name
    connection.settings_dict["DATABASE_NAME"] = old_name
    teardown_test_environment()

    return len(result.failures) + len(result.errors)
Esempio n. 42
0
    def test_transactions_disabled(self, db: None) -> None:
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert connection.in_atomic_block
Esempio n. 43
0
    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not noop_transactions()
    def test_transactions_enabled(self, transactional_db):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block
Esempio n. 45
0
    def test_transactions_enabled(self, transactional_db):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not noop_transactions()
Esempio n. 46
0
    def test_transactions_disabled(self, db):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert connection.in_atomic_block
Esempio n. 47
0
    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block