Python django.setup() Examples

The following are 30 code examples for showing how to use django.setup(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django , or try the search function .

Example 1
Project: django-classified   Author: slyapustin   File: quicktest.py    License: MIT License 6 votes vote down vote up
def _tests(self):
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(self.DIRNAME, 'database.db'),
                }
            },
            INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
            MIDDLEWARE=self.MIDDLEWARE,
            ROOT_URLCONF='django_classified.tests.urls',
            STATIC_URL='/static/',
            TEMPLATES=self.TEMPLATES,
            SITE_ID=1
        )

        from django.test.runner import DiscoverRunner
        test_runner = DiscoverRunner()
        django.setup()

        failures = test_runner.run_tests(self.apps)
        if failures:
            sys.exit(failures) 
Example 2
Project: pinax-documents   Author: pinax   File: runtests.py    License: MIT License 6 votes vote down vote up
def runtests(*test_args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    # Compatibility with Django 1.7's stricter initialization
    if hasattr(django, "setup"):
        django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        test_args = ["pinax.documents.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ["tests"]

    failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example 3
Project: py2swagger   Author: Arello-Mobile   File: __init__.py    License: MIT License 6 votes vote down vote up
def run(self, arguments, *args, **kwargs):
        try:
            os.environ.setdefault(
                'DJANGO_SETTINGS_MODULE', arguments.django_settings)
            import django
            if hasattr(django, 'setup'):
                django.setup()
        except ImportError:
            raise Py2SwaggerPluginException('Invalid django settings module')

        from .introspectors.api import ApiIntrospector
        from .urlparser import UrlParser

        # Patch Djago REST Framework, to make inspection process slightly easier
        from . import injection

        apis = UrlParser().get_apis(filter_path=arguments.filter)
        a = ApiIntrospector(apis)

        return a.inspect() 
Example 4
Project: botbuilder-python   Author: microsoft   File: tests.py    License: MIT License 6 votes vote down vote up
def test_log_error(self):
        """Tests an error trace telemetry is properly sent"""
        django.setup()
        logger = logging.getLogger(__name__)
        msg = "An error log message"
        logger.error(msg)

        event = self.get_events(1)
        data = event["data"]["baseData"]
        props = data["properties"]
        self.assertEqual(
            event["name"], "Microsoft.ApplicationInsights.Message", "Event type"
        )
        self.assertEqual(event["iKey"], TEST_IKEY)
        self.assertEqual(data["message"], msg, "Log message")
        self.assertEqual(data["severityLevel"], 3, "Severity level")
        self.assertEqual(props["fileName"], "tests.py", "Filename property")
        self.assertEqual(props["level"], "ERROR", "Level property")
        self.assertEqual(props["module"], "tests", "Module property") 
Example 5
Project: botbuilder-python   Author: microsoft   File: tests.py    License: MIT License 6 votes vote down vote up
def test_log_info(self):
        """Tests an info trace telemetry is properly sent"""
        django.setup()
        logger = logging.getLogger(__name__)
        msg = "An info message"
        logger.info(msg)

        event = self.get_events(1)
        data = event["data"]["baseData"]
        props = data["properties"]
        self.assertEqual(
            event["name"], "Microsoft.ApplicationInsights.Message", "Event type"
        )
        self.assertEqual(event["iKey"], TEST_IKEY)
        self.assertEqual(data["message"], msg, "Log message")
        self.assertEqual(data["severityLevel"], 1, "Severity level")
        self.assertEqual(props["fileName"], "tests.py", "Filename property")
        self.assertEqual(props["level"], "INFO", "Level property")
        self.assertEqual(props["module"], "tests", "Module property") 
Example 6
Project: django-taxii-services   Author: TAXIIProject   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def runtests():
    os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
    django.setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner()

    # By default, run all of the tests
    tests = ['tests']

    # Allow running a subset of tests via the command line.
    if len(sys.argv) > 1:
        tests = sys.argv[1:]

    failures = test_runner.run_tests(tests, verbosity=3)
    if failures:
        sys.exit(failures) 
Example 7
Project: django-cryptography   Author: georgemarshall   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests(self):
        import django
        django.setup()

        from django.conf import settings
        from django.test.utils import get_runner

        TestRunner = get_runner(settings, self.testrunner)

        test_runner = TestRunner(
            pattern=self.pattern,
            top_level=self.top_level_directory,
            verbosity=self.verbose,
            interactive=(not self.noinput),
            failfast=self.failfast,
            keepdb=self.keepdb,
            reverse=self.reverse,
            debug_sql=self.debug_sql,
            output_dir=self.output_dir)
        failures = test_runner.run_tests(self.test_labels)

        sys.exit(bool(failures)) 
Example 8
Project: django-rest-framework-docs   Author: manosim   File: runtests.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run_tests_coverage():
    if __name__ == "__main__":
        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
        django.setup()
        TestRunner = get_runner(settings)
        test_runner = TestRunner()

        # Setup Coverage
        cov = coverage(source=["rest_framework_docs"], omit=["rest_framework_docs/__init__.py"])
        cov.start()

        failures = test_runner.run_tests(["tests"])

        if bool(failures):
            cov.erase()
            sys.exit("Tests Failed. Coverage Cancelled.")

        # If success show coverage results
        cov.stop()
        cov.save()
        cov.report()
        cov.html_report(directory='covhtml') 
Example 9
Project: pwned-passwords-django   Author: ubernostrum   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)

    # Then, call django.setup() to initialize the application registry
    # and other bits:
    import django

    django.setup()

    # Now we instantiate a test runner...
    from django.test.utils import get_runner

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 10
Project: pynet   Author: ktbyers   File: ex1b_link_credentials.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    """Link credentials to devices"""
    django.setup()
    net_devices = NetworkDevice.objects.all()
    creds = Credentials.objects.all()

    std_creds = creds[0]
    arista_creds = creds[1]

    for a_device in net_devices:
        if 'arista' in a_device.device_type:
            a_device.credentials = arista_creds
        else:
            a_device.credentials = std_creds
        a_device.save()

    for a_device in net_devices:
        print a_device, a_device.credentials 
Example 11
Project: pynet   Author: ktbyers   File: ex4_delete_devices.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Remove the two objects created in exercise #3 from the database.
    '''
    django.setup()
    try:
        test_rtr1 = NetworkDevice.objects.get(device_name='test-rtr1')
        test_rtr2 = NetworkDevice.objects.get(device_name='test-rtr2')
        test_rtr1.delete()
        test_rtr2.delete()
    except NetworkDevice.DoesNotExist:
        pass

    # Verify devices that currently exist
    print
    devices = NetworkDevice.objects.all()
    for a_device in devices:
        print a_device
    print 
Example 12
Project: pynet   Author: ktbyers   File: ex2_vendor_field.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Set the vendor field for each NetworkDevice to the appropriate vendor. Save
    this field to the database.
    '''
    django.setup()
    devices = NetworkDevice.objects.all()
    for a_device in devices:
        if 'cisco' in a_device.device_type:
            a_device.vendor = 'Cisco'
        elif 'juniper' in a_device.device_type:
            a_device.vendor = 'Juniper'
        elif 'arista' in a_device.device_type:
            a_device.vendor = 'Arista'
        a_device.save()

    for a_device in devices:
        print a_device, a_device.vendor 
Example 13
Project: pynet   Author: ktbyers   File: ex6_threads_show_ver.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Use threads and Netmiko to connect to each of the devices in the database. Execute
    'show version' on each device. Record the amount of time required to do this.
    '''
    django.setup()
    start_time = datetime.now()
    devices = NetworkDevice.objects.all()

    for a_device in devices:
        my_thread = threading.Thread(target=show_version, args=(a_device,))
        my_thread.start()

    main_thread = threading.currentThread()
    for some_thread in threading.enumerate():
        if some_thread != main_thread:
            print some_thread
            some_thread.join()

    print "\nElapsed time: " + str(datetime.now() - start_time) 
Example 14
Project: django-cassandra-engine   Author: r4fek   File: runtests.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():

    default_cass = import_module('settings.default_cassandra')
    default_only_cass = import_module('settings.default_only_cassandra')
    secondary_cassandra = import_module('settings.secondary_cassandra')
    multi_cassandra = import_module('settings.multi_cassandra')
    metadata_disabled = import_module('settings.metadata_disabled')

    django.setup()

    run_tests(default_cass)
    run_tests(default_only_cass)
    run_tests(secondary_cassandra)
    run_tests(multi_cassandra)
    run_tests(metadata_disabled)
    sys.exit(0) 
Example 15
Project: zulip   Author: zulip   File: generate_integration_bots_avatars.py    License: Apache License 2.0 6 votes vote down vote up
def generate_integration_bots_avatars(check_missing: bool=False) -> None:
    missing = set()
    for webhook in WEBHOOK_INTEGRATIONS:
        if not webhook.logo_path:
            continue

        bot_avatar_path = webhook.get_bot_avatar_path()
        if bot_avatar_path is None:
            continue

        bot_avatar_path = os.path.join(ZULIP_PATH, 'static', bot_avatar_path)
        if check_missing:
            if not os.path.isfile(bot_avatar_path):
                missing.add(webhook.name)
        else:
            create_integration_bot_avatar(static_path(webhook.logo_path), bot_avatar_path)

    if missing:
        print('ERROR: Bot avatars are missing for these webhooks: {}.\n'
              'ERROR: Run ./tools/setup/generate_integration_bots_avatars.py '
              'to generate them.\nERROR: Commit the newly generated avatars to '
              'the repository.'.format(', '.join(missing)))
        sys.exit(1) 
Example 16
Project: django-ftpserver   Author: tokibito   File: conf.py    License: MIT License 6 votes vote down vote up
def setup_django():
    import django
    from django.conf import settings
    if not settings.configured:
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': ':memory:',
                }
            },
            INSTALLED_APPS=(
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django_ftpserver',
            )
        )
    django.setup()
    from django.apps import apps
    if not apps.ready:
        apps.populate() 
Example 17
Project: scale   Author: ngageoint   File: test_models.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        django.setup()

        self.job_exe_1 = job_test_utils.create_job_exe()
        self.job_type_1_id = self.job_exe_1.job.job_type.id
        self.job_exe_2 = job_test_utils.create_job_exe()
        self.job_type_2_id = self.job_exe_2.job.job_type.id

        self.product_1 = prod_test_utils.create_product()
        self.product_2 = prod_test_utils.create_product(has_been_published=True)
        self.product_3 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True)

        time.sleep(0.001)
        self.last_modified_start = now()
        self.product_4 = prod_test_utils.create_product()
        self.product_5 = prod_test_utils.create_product(self.job_exe_2)
        self.product_6 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True)
        time.sleep(0.001)
        self.product_7 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True)
        time.sleep(0.001)
        self.product_8 = prod_test_utils.create_product(has_been_published=True)
        self.last_modified_end = now() 
Example 18
Project: pinax-documents   Author: pinax   File: makemigrations.py    License: MIT License 5 votes vote down vote up
def run(*args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    django.core.management.call_command(
        "makemigrations",
        "documents",
        *args
    ) 
Example 19
Project: django-json-widget   Author: jmrivas86   File: runtests.py    License: MIT License 5 votes vote down vote up
def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
    django.setup()
    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures)) 
Example 20
Project: py2swagger   Author: Arello-Mobile   File: __init__.py    License: MIT License 5 votes vote down vote up
def setup():
    global test_runner
    global old_config

    try:
        # DjangoTestSuiteRunner was deprecated in django 1.8:
        # https://docs.djangoproject.com/en/1.8/internals/deprecation/#deprecation-removed-in-1-8
        from django.test.runner import DiscoverRunner as TestSuiteRunner
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner as TestSuiteRunner

    test_runner = TestSuiteRunner()
    test_runner.setup_test_environment()
    test_runner.setup_databases() 
Example 21
Project: django-river   Author: javrasya   File: environment.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def before_all(context):
    django.setup() 
Example 22
Project: django-hijack-admin   Author: arteria   File: runtests.py    License: MIT License 5 votes vote down vote up
def runtests(*test_args):
    import django
    if django.VERSION >= (1, 7):
        django.setup()
    failures = NoseTestSuiteRunner(verbosity=2,
                                      interactive=True).run_tests(test_args)
    sys.exit(failures) 
Example 23
Project: django-phone-verify   Author: CuriousLearner   File: conftest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pytest_configure():
    from tests import test_settings

    settings.configure(**test_settings.DJANGO_SETTINGS)
    django.setup() 
Example 24
def runtests(*test_args, **kwargs):
    if not test_args:  test_args = ['django_unixdatetimefield']
    import django
    try:
        django.setup()
    except AttributeError:
        pass
    kwargs.setdefault('interactive', False)
    test_runner = django_nose.NoseTestSuiteRunner(**kwargs)
    failures = test_runner.run_tests(test_args)
    sys.exit(failures) 
Example 25
Project: django-mptt-comments   Author: zmrenwu   File: runtests.py    License: MIT License 5 votes vote down vote up
def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
    django.setup()
    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures)) 
Example 26
Project: eventsourcing   Author: johnbywater   File: conf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(app):
    app.connect("autodoc-skip-member", skip) 
Example 27
Project: eventsourcing   Author: johnbywater   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_django() -> None:
    import django

    django.setup() 
Example 28
Project: longclaw   Author: JamesRamm   File: runtests.py    License: MIT License 5 votes vote down vote up
def run_tests(*test_args):
    if not test_args:
        test_args = []

    os.environ['DJANGO_SETTINGS_MODULE'] = 'longclaw.tests.settings'
    django.setup()
    test_runner = get_runner(settings)()
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures)) 
Example 29
Project: django-behaviors   Author: audiolion   File: runtests.py    License: MIT License 5 votes vote down vote up
def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
    django.setup()
    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures)) 
Example 30
Project: behave-django   Author: behave   File: util.py    License: MIT License 5 votes vote down vote up
def run_management_command(self, command, *args, **kwargs):
        django.setup()
        call_command(command, *args, **kwargs)