def main(): import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.conf import settings from django.utils import translation from django.core import management import django django.setup() django.utils.translation.activate("it") import random lon=11.36992 lat=44.48906 host="rmap.cc" anavar={ "B07030":{"v": "400"} } try: rmap=rmapmqtt(lon=lon,lat=lat,host=host) rmap.loop_start() rmap.ana(anavar) time.sleep(5) #rmap.loop() reptime=datetime.now() endtime=reptime+timedelta(days=1) while reptime <= endtime: print "connect status: ",rmap.connected timerange="254,0,0" # dati istantanei level="103,2000,-,-" # 2m dal suolo value=random.randint(25315,30000) # tempertaure in cent K datavar={"B12101": { "t": reptime, "v": str(value), "a": { "B33194": "90", # attributi di qualita' del dato "B33195": "85" } }} rmap.data(timerange,level,datavar) time.sleep(5) #rmap.loop() reptime=datetime.now() rmap.disconnect() rmap.loop_stop() print "work is done OK" except: print "terminated with error" raise
def main(): ''' Network management system class #9 ''' django.setup() verbose = True time.sleep(3) print while True: if verbose: print "### Gather inventory from devices ###" inventory_dispatcher() if verbose: print "\n### Retrieve config from devices ###" retrieve_config() if verbose: print "Sleeping for {} seconds".format(LOOP_DELAY) time.sleep(LOOP_DELAY)
def run_tests(): os.environ['DJANGO_SETTINGS_MODULE'] = 'simple_contact.tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["simple_contact.tests"]) sys.exit(bool(failures))
def runtests(): if hasattr(django, 'setup'): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(['scribbler', ]) sys.exit(failures)
def main(args): django.setup() logger = setup_error_handler() parser = argparse.ArgumentParser() parse_lock = None def list_logging_levels(): """Give a summary of all available logging levels.""" return sorted(list(VERBOSITY_LEVELS.keys()), key=lambda x: VERBOSITY_LEVELS[x]) parser.add_argument('--verbosity', choices=list_logging_levels(), help='logging level', default='info') args = vars(parser.parse_args()) logging.basicConfig(level=VERBOSITY_LEVELS[args['verbosity']]) mail = message_from_file(sys.stdin) try: parse_lock = lock() return parse_mail(mail) except: if logger: logger.exception('Error when parsing incoming email', extra={ 'mail': mail.as_string(), }) raise finally: release(parse_lock)
def _tests_1_7(self): """ Fire up the Django test suite developed for version 1.7 and up """ INSTALLED_APPS, settings_test = self.get_custom_settings() settings.configure( DEBUG=True, DATABASES=self.get_database(), MIDDLEWARE_CLASSES=( "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", ), INSTALLED_APPS=self.INSTALLED_APPS + INSTALLED_APPS + self.apps, **settings_test ) try: # Django <= 1.8 from django.test.simple import DjangoTestSuiteRunner test_runner = DjangoTestSuiteRunner(verbosity=1) except ImportError: # Django >= 1.8 from django.test.runner import DiscoverRunner test_runner = DiscoverRunner(verbosity=1) import django django.setup() failures = test_runner.run_tests(self.apps, verbosity=1) if failures: sys.exit(failures)
def main(): os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures))
def run_tests(self): from django.conf import settings db_engine = os.environ.get('DJANGO_DB_ENGINE', 'sqlite') if db_engine == 'mysql': db_settings = { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DJANGO_DB_NAME'], 'USER': os.environ['DJANGO_DB_USER'], } elif db_engine == 'postgres': db_settings = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DJANGO_DB_NAME'], 'USER': os.environ['DJANGO_DB_USER'], } elif db_engine == 'sqlite': db_settings = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(self.DIRNAME, 'database.db'), } else: raise ValueError("Unknown DB engine: %s" % db_engine) # Common settings. settings.configure( DEBUG=True, DATABASES={'default': db_settings}, CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}, INSTALLED_APPS=self.APPS) import django import pytest django.setup() sys.exit(pytest.main(["tests/"]))
def main(): django.setup() brocade_rtr1 = NetworkDevice( device_name='Brocade-rtr1', device_type='fc_san', ip_address='50.76.53.28', port=8022, ) hp_sw1 = NetworkDevice( device_name='HP-sw1', device_type='stratus', ip_address='50.76.53.29', port=8022, ) # Save new device information in database brocade_rtr1.save() hp_sw1.save() # Print out devices just added for a_dev in (brocade_rtr1, hp_sw1): print a_dev print "Display devices in the database" devices = NetworkDevice.objects.all() for a_device in devices: print a_device.device_name
def pytest_configure(): importer.install() # Setup command is only available in Django 1.7+ but is required # to properly initialise the Django app config. if django.VERSION[1] >= 7: django.setup()
def set_up_django(external_host): # type: (str) -> None os.environ['EXTERNAL_HOST'] = external_host os.environ["TORNADO_SERVER"] = "http://127.0.0.1:9983" os.environ['DJANGO_SETTINGS_MODULE'] = 'zproject.test_settings' django.setup() os.environ['PYTHONUNBUFFERED'] = 'y'
def add_transient(obj): import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'torosweb.settings') import django django.setup() from winnow.models import TransientCandidate t = TransientCandidate() t.ra = obj['ra'] t.dec = obj['dec'] t.x_pix = obj['x'] t.y_pix = obj['y'] t.height = obj['ymax'] - obj['ymin'] t.width = obj['xmax'] - obj['xmin'] t.filename = obj['filename'] t.dataset_id = obj['dataset'] try: lastTC = TransientCandidate.objects.filter(dataset_id=dataset).order_by('-object_id')[0] last_id = lastTC.object_id except IndexError: last_id = 0 t.object_id = last_id + 1 t.save() t.refImg = 'object_images/%s_ref.png' % (t.slug) t.subtImg = 'object_images/%s_subt.png' % (t.slug) t.origImg = 'object_images/%s_orig.png' % (t.slug) t.save() return t
def main(): django.setup() p_list = [] q = multiprocessing.Queue(maxsize=20) devices = net_system.models.NetworkDevice.objects.all() start_time = datetime.datetime.now() for a_device in devices: a_process = multiprocessing.Process(target=show_version_q, args=(a_device, q)) a_process.start() p_list.append(a_process) for p in p_list: p.join() print print "*" * 80 out_dic = q.get() for k, v in out_dic.iteritems(): print v end_time = datetime.datetime.now() print print "*" * 80 print "Run time: ", end_time - start_time
def _validate_database_url(self, question, url): # Ensure django is setup django.setup() try: db = dj_database_url.parse(url) except KeyError: return False, 'Failed to parse database URL.\n' options = {} if 'sqlite' not in db['ENGINE']: options['connect_timeout'] = 3 db['OPTIONS'] = options # These are django defaults - the cursor() call craps out if these are missing. db['AUTOCOMMIT'] = True db['TIME_ZONE'] = None try: engine = load_backend(db['ENGINE']).DatabaseWrapper(db) engine.cursor() except KeyError: return False, 'Invalid database URL provided.\n' except Exception as e: return False, '{0}\n'.format(str(e)) return True, ''
def setUp(self): self.connection = connect_db() self.cached_rows = {} ''' Let's create some simple data. ''' create_model( self.connection, SimpleTestModel ) field_names = [ field.name if field.get_internal_type() != 'AutoField' else None for field in SimpleTestModel._meta.fields ] field_values = ['foo', 'bar', 'raw', 'awk', 'lik', 'sik', 'dik', 'doc'] self.total_rows = 10 for x in xrange(self.total_rows): test_data = {} i = 0 for name in field_names: if not name: continue test_data[name] = field_values[i] i += 1 created_instance = SimpleTestModel.objects.create(**test_data) self.cached_rows[created_instance.pk] = created_instance import django django.setup()
def _tests(self): settings.configure( DEBUG = True, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(self.DIRNAME, 'database.db'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }, SHIBBOLETH_LOGIN_URL = 'https://your_domain.edu/Shibboleth.sso/Login', SHIBBOLETH_LOGOUT_URL = 'https://your_domain.edu/Shibboleth.sso/Logout', LOGIN_URL = '/shib/login/', INSTALLED_APPS = self.INSTALLED_APPS + self.apps, ROOT_URLCONF = 'shib.urls', ) try: django.setup() except AttributeError: #before django 1.6 this was not necessary pass from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1) if failures: sys.exit(failures)
def rating_json(): setup() comp_dict = {} for r in ratings.objects.raw('SELECT * FROM comp_ratings'): print(r.id) rating = ratings.objects.filter(id = r.id) rating_values = rating.values() print(rating_values) fields = ratings._meta.get_all_field_names() node_list = [] for field in ratings._meta.get_all_field_names(): if field == "id": continue elif field == "company" : continue elif field == "FB_likes" : continue elif field == "FB_likes_score": continue elif field == "recommend_to_friend_rating": continue node = {} node["label"] = field node["n"] = float(rating_values[0][field]) node_list.append(node) comp_dict[r.id] = node_list print(comp_dict) comp_dict = json.dumps(comp_dict, indent=4) with open('/Users/vickyzhang/Documents/python/chart/jobchart/comp/static/comp/rating.json', 'w') as outfile: outfile.write(str(comp_dict))
def for_bubble_chart(): setup() wrapper_dict = {} wrapper_dict["name"] = "companies" wrapper_dict["children"] = [] for r in ratings.objects.raw('SELECT * FROM comp_ratings'): words = review_summary.objects.filter(company_id = r.id) words_list = words.values() comp_dict = {} print(words_list) try: comp_dict["name"] = words_list[0]["company"] except: continue comp_dict["children"] = [] for word in words_list: node_dict = {} node_dict["name"] = word["word"] node_dict["size"] = word["frequency"] comp_dict["children"].append(node_dict) wrapper_dict["children"].append(comp_dict) print(wrapper_dict) wrapper_dict = json.dumps(wrapper_dict, indent=4) with open('/Users/vickyzhang/Documents/python/chart/jobchart/comp/static/comp/for_bubble.json', 'w') as outfile: outfile.write(str(wrapper_dict))
def complete(request): if request.method == "POST": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'choice.settings') django.setup() compType = request.POST["compType"] print 'type ' + compType matchupNames = request.POST["matchupNames"] choices = request.POST['choices'] TTChoose = request.POST["TTChoose"] Time = request.POST['Time'] username = request.POST['username'] familiarity = int(json.loads(request.POST["familiarity"])) print "familiarity", familiarity if get_real_ip(request) is not None: ip = get_real_ip(request) print 'ip: ', ip c = choiceData(username=username, compType=compType, matchupNames=matchupNames, choices=choices, TTChoose=TTChoose, CTime=Time, ip=ip, familiarity=familiarity) c.save() results = ['test1', 'test2'] # valid = validateHuman( ctype, num_ctype, next_ctype_index = get_next_ctype(compType) # set validation data for Amazon payment if ctype == "end": secret_code = set_user_info(username) context_dict = {'results': results, 'next_ctype': ctype, 'username': username, 'num_ctype': num_ctype, 'completed': next_ctype_index, 'secret_code': secret_code} return render(request, 'app/complete_ajax.html', context_dict) context_dict = {'results': results, 'next_ctype': ctype, 'username': username, 'num_ctype': num_ctype, 'completed': next_ctype_index} return render(request, 'app/complete_ajax.html', context_dict)
def data(request): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'choice.settings') django.setup() if request.method == "POST": compType = request.POST["compType"] if compType[-1] == ' ': compType = compType[:len(compType)-1] # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{0}.csv"'.format(compType) writer = csv.writer(response) # retrieve the correct dataset samples = choiceData.objects.filter(compType=compType) writer.writerow(['ID', 'Username', 'Type', 'Choice1', 'Choice2', 'Selection', 'TTChoose', 'Familiar', 'Time of Survey Completion', 'IP']) count = 0 for sample in samples: count += 1 username = str(sample.username).replace('"','') CType = str(sample.compType).replace('"','') matchups = ast.literal_eval(sample.matchupNames) selection = ast.literal_eval(sample.choices) TTChoose = ast.literal_eval(sample.TTChoose) familiarity = sample.familiarity CTime = ast.literal_eval(sample.CTime) ip = sample.ip for i in range(len(selection)): row = [count, username, CType, matchups[i][0], matchups[i][1], selection[i], TTChoose[i], familiarity, CTime, ip] writer.writerow(row) return response
def main(): try: django.setup() except AttributeError: pass TestRunner = get_runner(settings) test_runner = TestRunner() if len(sys.argv) == 2: test_case = '.' + sys.argv[1] elif len(sys.argv) == 1: test_case = '' else: print(usage()) sys.exit(1) test_module_name = 'unsubscribe.tests' if django.VERSION[0] == 1 and django.VERSION[1] < 6: test_module_name = 'tests' failures = test_runner.run_tests( [test_module_name + test_case], verbosity=1, interactive=True) sys.exit(failures)
def setup(cls, options=None, args=None, **kwargs): """Adds Django initialisation .. warning:: The Django system can only be initialised once, so you can only ever setup one class that uses DjangoApp as a base. In practice, subsequent calls to setup will simply ignore the Django configuration step, ignoring any debug setting and template directory locations. This restriction may be removed in future versions as this area of Django appears to be evolving.""" super(DjangoApp, cls).setup(options, args, **kwargs) if options: cls.debug = options.debug dsettings = cls.settings.setdefault('DjangoApp', {}) template_urls = dsettings.setdefault('template_dirs', ['templates']) template_paths = [] for t in template_urls: template_paths.append(cls.resolve_setup_path(t)) if not DjangoApp.configured: settings.configure( DEBUG=cls.debug, TEMPLATE_DEBUG=cls.debug, TEMPLATE_DIRS=template_paths) django.setup() DjangoApp.configured = True else: logging.warning("DjangoApp: setup ignored for %s" % cls.__name__) cls.template_dirs = template_paths
def prepare_test_runner(*args, **kwargs): """ Configures a test runner based on Django version to maintain backward compatibility. """ import django test_runner = None if django_17(): django.setup() from django.test.runner import DiscoverRunner test_runner = DiscoverRunner( pattern='test*.py', verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast'), ) else: from django.test.simple import DjangoTestSuiteRunner test_runner = DjangoTestSuiteRunner( verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast') ) return test_runner
def startup(settings_module=None): """Start up Django and Lino. Until Django 1.6 this was called automatically (by :mod:`lino.modlib.lino_startup`), but this trick no longer worked after 1.7. This is called automatically when a process is invoked by an *admin command*. For testable documents you need to call it manually using e.g.: >>> import lino >>> lino.startup('my.project.settings') Note that above two lines are recommended over the old-style method (which works only under Django 1.6):: >>> import os >>> os.environ['DJANGO_SETTINGS_MODULE'] = 'my.project.settings' """ # print("20160711 startup") # logger.info("20160711 startup") if settings_module: import os os.environ['DJANGO_SETTINGS_MODULE'] = settings_module if AFTER17: import django django.setup()
def main(): sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) if not settings.configured: settings.configure( INSTALLED_APPS=('django.contrib.auth', 'django.contrib.contenttypes', APP_NAME), DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3'}}, ROOT_URLCONF = 'sitetree.tests', MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES, # Prevents Django 1.7 warning. TEMPLATE_CONTEXT_PROCESSORS=tuple(global_settings.TEMPLATE_CONTEXT_PROCESSORS) + ( 'django.core.context_processors.request', ) ) try: # Django 1.7 + from django import setup setup() except ImportError: pass from django.test.utils import get_runner runner = get_runner(settings)() failures = runner.run_tests((APP_NAME,)) sys.exit(failures)
def main(): django.setup() net_devices = NetworkDevice.objects.all() creds = Credentials.objects.all() cisco_creds = creds[0] arista_creds = creds[1] for device in net_devices: if 'arista' in device.device_type: device.credentials = arista_creds else: device.credentials = cisco_creds device.save() for device in net_devices: if device.device_type == 'arista_eos': device.vendor = "Arista" if device.device_type == 'cisco_ios': device.vendor = "Cisco" if device.device_type == 'juniper': device.vendor = "Juniper" device.save() for device in net_devices: print device.device_name, device.vendor
def test_django(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") sys.path.append( os.path.join( os.path.abspath(os.path.dirname(__file__)), 'django_test_env' ) ) from django.test.utils import setup_test_environment setup_test_environment() from django.test.client import Client from werobot.parser import parse_xml, process_message import django django.setup() client = Client() token = 'TestDjango' timestamp = str(time.time()) nonce = str(random.randint(0, 10000)) signature = get_signature(token, timestamp, nonce) echostr = generate_token() response = client.get( '/robot/', { 'signature': signature, 'timestamp': timestamp, 'nonce': nonce, 'echostr': echostr } ) assert response.status_code == 200 assert response.content.decode('utf-8') == echostr xml = """ <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> </xml>""" params = "?timestamp=%s&nonce=%s&signature=%s" % \ (timestamp, nonce, signature) url = '/robot/' response = client.post(url, data=xml, content_type="text/xml") assert response.status_code == 403 assert response.content.decode('utf-8') == u'喵' url += params response = client.post(url, data=xml, content_type="text/xml") assert response.status_code == 200 response = process_message(parse_xml(response.content)) assert response.content == 'hello' response = client.options(url) assert response.status_code == 405
def pytest_configure(): global _SETTINGS try: import django from django.conf import settings settings.configure(POOL_OF_RAMOS=POOL_OF_RAMOS) django.setup() _SETTINGS = settings except ImportError: try: import os os.environ.setdefault('SIMPLE_SETTINGS', 'conftest') from simple_settings import settings settings.configure(POOL_OF_RAMOS=POOL_OF_RAMOS) _SETTINGS = settings except ImportError: import ramos ramos.configure(pools=POOL_OF_RAMOS)
def setUp(self): django.setup() self.workspace = storage_test_utils.create_workspace() self.workspace.upload_files = MagicMock() self.workspace.delete_files = MagicMock() self.upload_dir = os.path.join('upload', 'dir') self.work_dir = os.path.join('work', 'dir') self.workspace_work_dir = ScaleFile.objects._get_workspace_work_dir(self.work_dir, self.workspace) self.source_file = source_test_utils.create_source(file_name=u'input1.txt', workspace=self.workspace) self.job_exe = job_test_utils.create_job_exe() self.job_exe_no = job_test_utils.create_job_exe() with transaction.atomic(): self.job_exe_no.job.is_operational = False self.job_exe_no.job.job_type.is_operational = False self.job_exe_no.job.save() self.job_exe_no.job.job_type.save() self.files = [ (u'local/1/file.txt', u'remote/1/file.txt', None), (u'local/2/file.json', u'remote/2/file.json', u'application/x-custom-json'), ] self.files_no = [ (u'local/3/file.h5', u'remote/3/file.h5', u'image/x-hdf5-image'), ]
def setUp(self): django.setup() self.src_file_1 = source_test_utils.create_source() self.src_file_2 = source_test_utils.create_source() self.src_file_3 = source_test_utils.create_source() self.src_file_4 = source_test_utils.create_source() self.job_exe_1 = job_test_utils.create_job_exe() self.recipe_job_1 = recipe_test_utils.create_recipe_job(job=self.job_exe_1.job) self.product_1 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True) self.product_2 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True) FileAncestryLink.objects.create(ancestor=self.src_file_1, descendant=self.product_1, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_1, descendant=self.product_2, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_2, descendant=self.product_1, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_2, descendant=self.product_2, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) self.job_exe_2 = job_test_utils.create_job_exe() self.recipe_job_2 = recipe_test_utils.create_recipe_job(job=self.job_exe_2.job) self.product_3 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True) FileAncestryLink.objects.create(ancestor=self.src_file_3, descendant=self.product_3, job_exe=self.job_exe_2, job=self.job_exe_2.job, recipe=self.recipe_job_2.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_4, descendant=self.product_3, job_exe=self.job_exe_2, job=self.job_exe_2.job, recipe=self.recipe_job_2.recipe)
def configure_workers(*args, **kwargs): import django django.setup()
def setUpClass(cls): super(Test_Api_Complex, cls).setUpClass() django.setup()
def setup(verbosity, test_labels, parallel): # Reduce the given test labels to just the app module path. test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname( django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, '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', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ 'fields.W342', # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # It would be nice to put this validation earlier but it must come after # django.setup() so that connection.features.gis_enabled can be accessed # without raising AppRegistryNotReady when running gis_tests in isolation # on some backends (e.g. PostGIS). if 'gis_tests' in test_labels_set and not connection.features.gis_enabled: raise SystemExit( 'Aborting: A GIS database backend is required to run gis_tests.') # Load all the test model apps. test_modules = get_test_modules() installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = modpath + '.' + module_name else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. module_found_in_labels = not test_labels or any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import json from django.test import TestCase from django.test import Client import django django.setup() from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser from rest_framework import status from . import fakedata from .models.CurrentUserViewModel import CurrentUserViewModel from .serializers import CurrentUserViewModelSerializer from .models.DoingBusinessAs import DoingBusinessAs from .serializers import DoingBusinessAsSerializer from .models.InactiveClaimReason import InactiveClaimReason from .serializers import InactiveClaimReasonSerializer from .models.IssuerService import IssuerService from .serializers import IssuerServiceSerializer from .models.Jurisdiction import Jurisdiction
import os import shutil import json import logging from copy import deepcopy from collections import defaultdict, namedtuple from glob import glob os.environ['DJANGO_SETTINGS_MODULE'] = 'pupa.settings' from django import setup setup() from django.db import transaction from django.conf import settings from opencivicdata.models import (Organization, OrganizationName, Person, PersonName, Membership) from pupa.utils.model_ops import merge_model_objects from pupa.utils import combine_dicts DEDUPE_BIN = os.path.join(settings.BIN_DIR, 'echelon-0.1.0-SNAPSHOT-standalone.jar') API_URL = settings.API_URL logger = logging.getLogger("") def consolidate_other_names(all_other_names, name_model):
def initialize_app(config, skip_service_validation=False): settings = config["settings"] if settings.DEBUG: # Enable line buffering for stderr, TODO(py3.9) can be removed after py3.9, see bpo-13601 sys.stderr = os.fdopen(sys.stderr.fileno(), "w", 1) sys.stdout = os.fdopen(sys.stdout.fileno(), "w", 1) # Just reuse the integration app for Single Org / Self-Hosted as # it doesn't make much sense to use 2 separate apps for SSO and # integration. if settings.SENTRY_SINGLE_ORGANIZATION: options_mapper.update({ "github-app.client-id": "GITHUB_APP_ID", "github-app.client-secret": "GITHUB_API_SECRET", }) bootstrap_options(settings, config["options"]) configure_structlog() # Commonly setups don't correctly configure themselves for production envs # so lets try to provide a bit more guidance if settings.CELERY_ALWAYS_EAGER and not settings.DEBUG: warnings.warn( "Sentry is configured to run asynchronous tasks in-process. " "This is not recommended within production environments. " "See https://docs.sentry.io/on-premise/server/queue/ for more information." ) if settings.SENTRY_SINGLE_ORGANIZATION: settings.SENTRY_FEATURES["organizations:create"] = False if not hasattr(settings, "SUDO_COOKIE_SECURE"): settings.SUDO_COOKIE_SECURE = getattr(settings, "SESSION_COOKIE_SECURE", False) if not hasattr(settings, "SUDO_COOKIE_DOMAIN"): settings.SUDO_COOKIE_DOMAIN = getattr(settings, "SESSION_COOKIE_DOMAIN", None) if not hasattr(settings, "SUDO_COOKIE_PATH"): settings.SUDO_COOKIE_PATH = getattr(settings, "SESSION_COOKIE_PATH", "/") if not hasattr(settings, "CSRF_COOKIE_SECURE"): settings.CSRF_COOKIE_SECURE = getattr(settings, "SESSION_COOKIE_SECURE", False) if not hasattr(settings, "CSRF_COOKIE_DOMAIN"): settings.CSRF_COOKIE_DOMAIN = getattr(settings, "SESSION_COOKIE_DOMAIN", None) if not hasattr(settings, "CSRF_COOKIE_PATH"): settings.CSRF_COOKIE_PATH = getattr(settings, "SESSION_COOKIE_PATH", "/") for key in settings.CACHES: if not hasattr(settings.CACHES[key], "VERSION"): settings.CACHES[key]["VERSION"] = 2 settings.ASSET_VERSION = get_asset_version(settings) settings.STATIC_URL = settings.STATIC_URL.format( version=settings.ASSET_VERSION) if getattr(settings, "SENTRY_DEBUGGER", None) is None: settings.SENTRY_DEBUGGER = settings.DEBUG monkeypatch_model_unpickle() import django django.setup() monkeypatch_django_migrations() apply_legacy_settings(settings) bind_cache_to_option_store() register_plugins(settings) initialize_receivers() validate_options(settings) validate_snuba() configure_sdk() setup_services(validate=not skip_service_validation) from django.utils import timezone from sentry.app import env from sentry.runner.settings import get_sentry_conf env.data["config"] = get_sentry_conf() env.data["start_date"] = timezone.now()
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False) parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. no_settings_commands = [ 'help', 'version', '--help', '--version', '-h', 'compilemessages', 'makemessages', 'startapp', 'startproject', ] try: settings.INSTALLED_APPS except ImproperlyConfigured as exc: self.settings_exception = exc # A handful of built-in management commands work without settings. # Load the default settings -- where INSTALLED_APPS is empty. if subcommand in no_settings_commands: settings.configure() if settings.configured: # Start the auto-reloading dev server even if the code is broken. # The hardcoded condition is a code smell but we can't rely on a # flag on the command class because we haven't located it yet. if subcommand == 'runserver' and '--noreload' not in self.argv: try: autoreload.check_errors(django.setup)() except Exception: # The exception will be raised later in the child process # started by the autoreloader. Pretend it didn't happen by # loading an empty list of applications. apps.all_models = defaultdict(OrderedDict) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.ready = True # In all other cases, django.setup() is required to succeed. else: django.setup() self.autocomplete() if subcommand == 'help': if '--commands' in args: sys.stdout.write(self.main_help_text(commands_only=True) + '\n') elif len(options.args) < 1: sys.stdout.write(self.main_help_text() + '\n') else: self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0]) # Special-cases: We want 'django-admin --version' and # 'django-admin --help' to work, for backwards compatibility. elif subcommand == 'version' or self.argv[1:] == ['--version']: sys.stdout.write(django.get_version() + '\n') elif self.argv[1:] in (['--help'], ['-h']): sys.stdout.write(self.main_help_text() + '\n') else: self.fetch_command(subcommand).run_from_argv(self.argv)
def setUp(self): # Every test needs a client. self.client = Client() # needed to setup django django.setup()
def setUp(self): django.setup()
#!/usr/bin/env python import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Collecster.settings") django.setup() from advideogame.models import * from advideogame.configuration import * #import string GENERIC_MARKER = 1 base_system_list = [ ( "Master System", "Sega", 3, "H", None, "SMS", [ ("cartridge", False, "SMS-cart"), ("Sega card", False, "SMS-scard"), ("controller", False, "SMS-pad"), ], [ ("% 1 console", { "provides": [1, 1, 2], "requires": [], }),
def main(test_labels=None): django.setup() runner = DiscoverRunner(failfast=True, verbosity=1) failures = runner.run_tests(test_labels or ['testapp'], interactive=True) sys.exit(failures)
from datetime import datetime, timedelta import django from django.test import SimpleTestCase django.setup() # todo: how to run tests from PyCharm without this workaround? from auth.providers.common import Membership from auth.providers.patreon import parse_active_membership class UnitTestsParseActiveMembership(SimpleTestCase): def setUp(self): self.stub_patreon_response_oauth_identity = { "data": { "attributes": { "about": "A Patreon Platform User", "created": "2018-04-01T00:36:26+00:00", "email": "*****@*****.**", "first_name": "Firstname", "full_name": "FullName With Space", "image_url": "https://url.example", "last_name": "Lastname", "social_connections": { "deviantart": None, "discord": None, "facebook": None, "reddit": None, "spotify": None, "twitch": None, "twitter": {
try: import django # noqa django.setup() # noqa finally: pass import time from simple.models import Journal LEVEL_CHOICE = [10, 20, 30, 40, 50] start = time.time() count = 0 for _ in range(10): for level in LEVEL_CHOICE: res = list(Journal.objects.filter(level=level).all()) count += len(res) now = time.time() print(f"Django, D: Rows/sec: {count / (now - start): 10.2f}")
def setUp(self): django.setup() self.node1 = node_test_utils.create_node() self.node2 = node_test_utils.create_node()
def setUp(self): django.setup() self.view = LTIToolConfigView() self.view.request = RequestFactory().get('/lti/config') self.view.request.session = {}
def setUpClass(cls): super(TestHttpConfig, cls).setUpClass() django.setup()