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",
"pinax_news",
*args
)
python类configure()的实例源码
def pytest_configure():
settings.configure(DATABASES=seekconnection_settings.DATABASES)
def pytest_configure():
settings.configure(INSTALLED_APPS=[
'django.contrib.contenttypes',
])
django.setup()
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",
"pinax_cohorts",
*args
)
def main(args):
# Since this test suite is designed to be ran outside of ./manage.py test, we need to do some setup first.
import django
from django.conf import settings
settings.configure(INSTALLED_APPS=['testapp'], DATABASES=DATABASES_FOR_DB[args.db])
django.setup()
from django.test.runner import DiscoverRunner
test_runner = DiscoverRunner(top_level=TESTS_DIR, interactive=False, keepdb=False)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
def test_01_overwrite_detection(self):
"test detection of foreign monkeypatching"
# NOTE: this sets things up, and spot checks two methods,
# this should be enough to verify patch manager is working.
# TODO: test unpatch behavior honors flag.
# configure plugin to use sample context
config = "[passlib]\nschemes=des_crypt\n"
self.load_extension(PASSLIB_CONFIG=config)
# setup helpers
import django.contrib.auth.models as models
from passlib.ext.django.models import _manager
def dummy():
pass
# mess with User.set_password, make sure it's detected
orig = models.User.set_password
models.User.set_password = dummy
with self.assertWarningList("another library has patched.*User\.set_password"):
_manager.check_all()
models.User.set_password = orig
# mess with models.check_password, make sure it's detected
orig = models.check_password
models.check_password = dummy
with self.assertWarningList("another library has patched.*models:check_password"):
_manager.check_all()
models.check_password = orig
def main():
if not settings.configured:
module_root = path.dirname(path.realpath(__file__))
settings.configure(
DEBUG = False,
INSTALLED_APPS = (
'private_storage',
),
)
if django.VERSION >= (1,7):
django.setup()
makemessages()
def setup():
DB_FILE = NAME + '.db'
with open(DB_FILE, 'w'):
pass # wipe the database
settings.configure(
DEBUG=True,
DATABASES={
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_FILE}},
LOGGING={'version': 1,
'disable_existing_loggers': False,
'formatters': {
'debug': {
'format': '%(asctime)s[%(levelname)s]'
'%(name)s.%(funcName)s(): %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'}},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'debug'}},
'root': {
'handlers': ['console'],
'level': 'WARN'},
'loggers': {
"django.db": {"level": "WARN"}}})
app_config = AppConfig(NAME, sys.modules['__main__'])
apps.populate([app_config])
django.setup()
original_new_func = ModelBase.__new__
@staticmethod
def patched_new(cls, name, bases, attrs):
if 'Meta' not in attrs:
class Meta:
app_label = NAME
attrs['Meta'] = Meta
return original_new_func(cls, name, bases, attrs)
ModelBase.__new__ = patched_new
def setup():
DB_FILE = NAME + '.db'
with open(DB_FILE, 'w'):
pass # wipe the database
settings.configure(
DEBUG=True,
DATABASES={
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_FILE}},
LOGGING={'version': 1,
'disable_existing_loggers': False,
'formatters': {
'debug': {
'format': '%(asctime)s[%(levelname)s]'
'%(name)s.%(funcName)s(): %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'}},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'debug'}},
'root': {
'handlers': ['console'],
'level': 'WARN'},
'loggers': {
"django.db": {"level": "WARN"}}})
app_config = AppConfig(NAME, sys.modules['__main__'])
apps.populate([app_config])
django.setup()
original_new_func = ModelBase.__new__
@staticmethod
def patched_new(cls, name, bases, attrs):
if 'Meta' not in attrs:
class Meta:
app_label = NAME
attrs['Meta'] = Meta
return original_new_func(cls, name, bases, attrs)
ModelBase.__new__ = patched_new
def setup():
DB_FILE = NAME + '.db'
with open(DB_FILE, 'w'):
pass # wipe the database
settings.configure(
DEBUG=True,
DATABASES={
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_FILE}},
LOGGING={'version': 1,
'disable_existing_loggers': False,
'formatters': {
'debug': {
'format': '%(asctime)s[%(levelname)s]'
'%(name)s.%(funcName)s(): %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'}},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'debug'}},
'root': {
'handlers': ['console'],
'level': 'WARN'},
'loggers': {
"django.db": {"level": "WARN"}}})
app_config = AppConfig(NAME, sys.modules['__main__'])
apps.populate([app_config])
django.setup()
original_new_func = ModelBase.__new__
@staticmethod
def patched_new(cls, name, bases, attrs):
if 'Meta' not in attrs:
class Meta:
app_label = NAME
attrs['Meta'] = Meta
return original_new_func(cls, name, bases, attrs)
ModelBase.__new__ = patched_new
def pytest_configure():
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
USE_L10N=True,
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'tests',
),
ROOT_URLCONF='tests.urls',
MIDDLEWARE_CLASSES=(
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader'
],
},
},
]
)
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SECRET_KEY="not very secret in tests",
USE_I18N=True,
USE_L10N=True,
USE_TZ=True,
INSTALLED_APPS=(
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.admin",
"django.contrib.sites",
"rest_framework",
"aa_stripe"
),
ROOT_URLCONF="aa_stripe.api_urls",
TESTING=True,
ENV_PREFIX="test-env",
STRIPE_SETTINGS_API_KEY="apikey",
STRIPE_SETTINGS_WEBHOOK_ENDPOINT_SECRET="fake"
)
def pytest_configure():
# configure django settings
settings.configure(**DJANGO_SETTINGS_DICT)
def test_01_overwrite_detection(self):
"""test detection of foreign monkeypatching"""
# NOTE: this sets things up, and spot checks two methods,
# this should be enough to verify patch manager is working.
# TODO: test unpatch behavior honors flag.
# configure plugin to use sample context
config = "[passlib]\nschemes=des_crypt\n"
self.load_extension(PASSLIB_CONFIG=config)
# setup helpers
import django.contrib.auth.models as models
from passlib.ext.django.models import _manager
def dummy():
pass
# mess with User.set_password, make sure it's detected
orig = models.User.set_password
models.User.set_password = dummy
with self.assertWarningList("another library has patched.*User\.set_password"):
_manager.check_all()
models.User.set_password = orig
# mess with models.check_password, make sure it's detected
orig = models.check_password
models.check_password = dummy
with self.assertWarningList("another library has patched.*models:check_password"):
_manager.check_all()
models.check_password = orig
def setup_django_template_system():
"""Initialises the Django templating system as to be used standalone.
"""
settings.configure()
settings.TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates'
}
]
django.setup()
test_middleware.py 文件源码
项目:opencensus-python
作者: census-instrumentation
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def setUp(self):
from django.conf import settings as django_settings
from django.test.utils import setup_test_environment
if not django_settings.configured:
django_settings.configure()
setup_test_environment()
def setUp(self):
from django.conf import settings as django_settings
from django.test.utils import setup_test_environment
if not django_settings.configured:
django_settings.configure()
setup_test_environment()
def get_settings():
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"django_elasticsearch_dsl",
"tests",
],
SITE_ID=1,
MIDDLEWARE_CLASSES=(),
ELASTICSEARCH_DSL={
'default': {
'hosts': os.environ.get('ELASTICSEARCH_URL',
'localhost:9200')
},
},
)
try:
import django
setup = django.setup
except AttributeError:
pass
else:
setup()
return settings
def pytest_configure():
from django.conf import settings
settings.configure()
def _old_tests(self):
"""
Fire up the Django test suite from before version 1.2
"""
settings.configure(DEBUG = True,
DATABASE_ENGINE = 'sqlite3',
DATABASE_NAME = os.path.join(self.DIRNAME, 'database.db'),
INSTALLED_APPS = self.INSTALLED_APPS + self.apps
)
from django.test.simple import run_tests
failures = run_tests(self.apps, verbosity=1)
if failures:
sys.exit(failures)