def setUp(self): setup_test_environment() connector.services = {'btc': ServiceProxyStubBTC()} from django.contrib.auth.models import User user = User.objects.create_user('testing', '*****@*****.**', 'testingpassword') user.save()
def run_tests(verbosity=1, interactive=False): from django.conf import settings from django.core import management from django.db import connection from django.test.utils import setup_test_environment, \ teardown_test_environment setup_test_environment() settings.DEBUG = False if not os.path.exists(settings.EXTENSIONS_MEDIA_ROOT): os.mkdir(settings.EXTENSIONS_MEDIA_ROOT, 0755) old_db_name = 'default' connection.creation.create_test_db(verbosity, autoclobber=not interactive) management.call_command('syncdb', verbosity=verbosity, interactive=interactive) nose_argv = ['runtests.py', '-v', '--with-coverage', '--with-doctest', '--doctest-extension=.txt', '--cover-package=djblets'] if len(sys.argv) > 2: node_argv += sys.argv[2:] nose.main(argv=nose_argv) connection.creation.destroy_test_db(old_name, verbosity) teardown_test_environment()
def run_tests(module_list, verbosity=1, extra_tests=[]): """ Run the unit tests for all the modules in the provided list. This testrunner will search each of the modules in the provided list, looking for doctests and unittests in models.py or tests.py within the module. 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() for module in module_list: suite.addTest(build_suite(module)) for test in extra_tests: suite.addTest(test) old_name = settings.DATABASE_NAME create_test_db(verbosity) result = unittest.TextTestRunner(verbosity=verbosity).run(suite) destroy_test_db(old_name, verbosity) teardown_test_environment() return len(result.failures) + len(result.errors)
def setUp(self): # Set up the django test framework. os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings' from django.conf import settings from django.test.utils import setup_test_environment from django.db import connection from south.management.commands import patch_for_test_db_setup # If DEBUG = True, django will sometimes take different code paths. settings.DEBUG = False self.django_db = settings.DATABASE_NAME setup_test_environment() patch_for_test_db_setup() connection.creation.create_test_db(verbosity=0) # A fake cardstories service just to benefit from settings directories. class FakeService: def __init__(self, settings): self.settings = settings # Instantiate our test subject. self.auth = djangoauth.Plugin(FakeService({'plugins-libdir': '.', 'plugins-confdir': '../fixture'}), []) # Use the fake client in the plugin instead of twisted's getPage. self.auth.getPage = FakeTwistedWebClient().getPage
def setUpModule(): if django is None: # pragma: no cover raise unittest.SkipTest("Django not installed") django_test_utils.setup_test_environment() runner = django_test_simple.DjangoTestSuiteRunner() runner_state = runner.setup_databases() test_state.update({"runner": runner, "runner_state": runner_state})
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 before_testfile(self): # Those imports must be done **after** setup_environ was called from django.test.utils import setup_test_environment from django.test.utils import create_test_db setup_test_environment() create_test_db(verbosity=0) self.dbname = self.settings.TEST_DATABASE_NAME
def test_password_change_with_mail_token(self, reset_mock, cassy_mock): """ Tests the case where a user logs in after receiving gotten a password reset email. """ setup_test_environment() client = Client() username = os.environ.get('LOGIN_USERNAME') old_password = os.environ.get('LOGIN_PASSWORD') new_password = '******' body = { 'token': os.environ.get('LOGIN_SEC_TOKEN'), 'username': username, 'password': new_password, } response = client.post( '/password/change', data=json.dumps(body), content_type='application/json' ) cassy_mock.assert_called_once_with( username, new_password, old_password ) reset_mock.assert_called_once_with( username, new_password ) self.assertEqual(response.status_code, 200)
def get_results_for(test_name, mixin=None, **test_attributes): from instant_coverage import InstantCoverageMixin if mixin is None: class EverythingTest(InstantCoverageMixin, TestCase): pass else: class EverythingTest(mixin, InstantCoverageMixin, TestCase): pass setup_test_environment() test = EverythingTest(test_name) for attribute, value in six.iteritems(test_attributes): setattr(test, attribute, value) result = PickyTestResult() test._pre_setup() test.run(result) if not result.errors == []: # there should only ever be failures; if there's an error we should # throw something useful raise Exception(result.errors[0][1]) return result
def handle(self, url, context, use_pdb, *args, **kwargs): if context: context_dict = eval(context) else: context_dict = {} context = Context(context_dict) if url is not None: setup_test_environment() client = Client() response = client.get(url) if not response.context: print 'Response for given URL contains no context (code %s).' % response.status_code else: if isinstance(response.context, Context): context = response.context elif type(response.context) == list: context = response.context[0] else: try: from django.test.utils import ContextList except ImportError: pass else: if isinstance(response.context, ContextList): # TODO: probably should try to merge all contexts context = response.context[0] if use_pdb: pdb_with_context(context) else: run_shell(context)
def run(self, max_depth=3): for p in self.plugins: p.set_output_dir(self.output_dir) old_DEBUG = settings.DEBUG settings.DEBUG = False setup_test_environment() test_signals.start_run.send(self) # To avoid tainting our memory usage stats with startup overhead we'll # do one extra request for the first page now: self.c.get(self.not_crawled[0][-1]) while self.not_crawled: #Take top off not_crawled and evaluate it current_depth, from_url, to_url = self.not_crawled.pop(0) if current_depth > max_depth: continue transaction.enter_transaction_management() try: resp, returned_urls = self.get_url(from_url, to_url) except HTMLParseError, e: LOG.error("%s: unable to parse invalid HTML: %s", to_url, e) except Exception, e: LOG.exception("%s had unhandled exception: %s", to_url, e) continue
def initial_setup(server): call_command('syncdb', interactive=False, verbosity=0) call_command('flush', interactive=False, verbosity=0) call_command('migrate', interactive=False, verbosity=0) call_command('loaddata', 'all', verbosity=0) setup_test_environment() world.browser = Browser('webdriver.firefox')
def setup(): """ set up test environment """ # add test/src folders to sys path test_folder = os.path.abspath(os.path.dirname(__file__)) src_folder = os.path.abspath(os.path.join(test_folder, os.pardir)) sys.path.insert(0, test_folder) sys.path.insert(0, src_folder) # define settings import django.conf os.environ[django.conf.ENVIRONMENT_VARIABLE] = "settings" # set up environment from django.test.utils import setup_test_environment setup_test_environment() # See https://docs.djangoproject.com/en/dev/releases/1.7/#app-loading-changes import django if django.VERSION >= (1, 7, 0): django.setup() # set up database from django.db import connection connection.creation.create_test_db()
def startTestRun(self, event): """Nose2 hook for the beginning of test running. Init the django environ and re-order the tests according to the django documented test runner behaviour. """ from django.test.simple import DjangoTestSuiteRunner # reorder_suite, from django.test.utils import setup_test_environment # Init the django default runner so we can call it's functions as needed self.dtsr = DjangoTestSuiteRunner() setup_test_environment() # event.suite = reorder_suite(event.suite, (unittest.TestCase,)) self.old_config = self.dtsr.setup_databases() if self.session.verbosity > 1: # ensure that deprecation warnings are displayed during testing # the following state is assumed: # logging.capturewarnings is true # a "default" level warnings filter has been added for # DeprecationWarning. See django.conf.LazySettings._configure_logging self.logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() self.logger.addHandler(handler)
def run_tests(settings): from django.test.utils import get_runner from django.utils.termcolors import colorize from django.test.utils import setup_test_environment version = django.get_version() if version.startswith("1.7"): django.setup() db_conf = settings.DATABASES['default'] setup_test_environment() output = [] msg = "Starting tests for db backend: %s" % db_conf['ENGINE'] embracer = '=' * len(msg) output.append(msg) for key, value in db_conf.iteritems(): if key == 'PASSWORD': value = '****************' line = ' %s: "%s"' % (key, value) output.append(line) embracer = colorize('=' * len(max(output, key=lambda s: len(s))), fg='green', opts=['bold']) output = [colorize(line, fg='blue') for line in output] output.insert(0, embracer) output.append(embracer) print '\n'.join(output) TestRunner = get_runner(settings) test_runner = TestRunner(interactive=False) failures = test_runner.run_tests(['password_policies']) return failures
def test_email_change(self, send_mail_mock): """ Test env data endpoint when temperature data is requested. """ username = "******" old_email = cassy.get_user_email(username) setup_test_environment() client = Client() body = { "auth_token": "securitytoken", "new_email": "*****@*****.**" } response = client.post( '/email_change', data=json.dumps(body), content_type='application/json' ) self.assertEqual(response.status_code, 200) # Reset back to old email body = { "auth_token": "securitytoken", "new_email": old_email } response = client.post( '/email_change', data=json.dumps(body), content_type='application/json' ) self.assertEqual(response.status_code, 200)
def test_health_check_response(self): setup_test_environment() client = Client() response = client.get('/health_check') status = json.loads(response.content.decode('utf-8')) self.assertEqual(status['isAlive'], True) self.assertEqual(response.status_code, 200)
def use_django(tags=[]): # "before all" log.debug("Setting up django environment") from django.test import utils from django.db import connection from django.test import TestCase from django.conf import settings old_name = settings.DATABASE_NAME utils.setup_test_environment() connection.creation.create_test_db(verbosity=0, autoclobber=True) # Annoyingly, django implements a bunch of methods on the testcase class which don't have # anything to do with testcase data, so we have to construct a "proxy" testcase and call # methods on it to avoid pasting parts of django here. class ProxyTestCase(TestCase): def runTest(self): pass proxy = ProxyTestCase() @Before(*tags) def set_up(sc): proxy._pre_setup() @After(*tags) def tear_down(sc): proxy._post_teardown() # "after all" @atexit.register def tear_down(): log.debug("Tearing down django test environment") utils.teardown_test_environment() connection.creation.destroy_test_db(old_name, verbosity=False)
def main(): project_dir = dirname(abspath(__file__)) # setup path sys.path.insert(0, project_dir) # project dir sys.path.insert(0, join(project_dir, 'tests')) # tests dir environ['DJANGO_SETTINGS_MODULE'] = 'testapp.settings' try: # django >= 1.7 from django import setup except ImportError: pass else: setup() # setup test env from django.test.utils import setup_test_environment setup_test_environment() # setup db from django.core.management import call_command, CommandError options = { 'interactive': False, 'verbosity': 1, } try: call_command('migrate', **options) except CommandError: # Django < 1.7 call_command('syncdb', **options) # run tests return nose.main()
def pytest_sessionstart(self, session): setup_test_environment() settings.DEBUG = False if self.database: settings.DATABASE_NAME = self.database management.get_commands() management._commands["syncdb"] = "django.core" if ( "south" in settings.INSTALLED_APPS and hasattr(settings, "SOUTH_TESTS_MIGRATE") and settings.SOUTH_TESTS_MIGRATE ): try: from south.management.commands.syncdb import Command except ImportError: pass else: class MigrateAndSyncCommand(Command): option_list = Command.option_list for opt in option_list: if "--migrate" == opt.get_opt_string(): opt.default = True break management._commands["syncdb"] = MigrateAndSyncCommand() self._old_database_name = settings.DATABASE_NAME create_test_db(self.verbosity, autoclobber=self.noinput, copy_test_db=self.copy_live_db)
def test_01_full(self): self._fixture_teardown() teardown_test_environment() call_command('test', 'localcrawler') call_command('localcrawler') setup_test_environment() self._fixture_setup()
def setUp(self): setup_test_environment() super(IndicatorViewTest, self).setUp() self.variable1 = mommy.make(IndicatorVariable) self.indicator_criteria = mommy.make(IndicatorVariableCriteria) self.form_data = { 'name': 'Health', 'description': 'some description', 'question_set': self.qset.id, 'survey': self.survey.id} self.variable_data = { 'name': 'test_variable', 'validation_test': 'between', 'description': 'test indicator variable', 'var_qset': self.qset.id, 'min': '1', 'max': '10' } User.objects.create_user( username='******', email='*****@*****.**', password='******') self.raj = self.assign_permission_to(User.objects.create_user('demo4', '*****@*****.**', 'demo4'), 'can_view_batches') self.assign_permission_to(self.raj, 'can_view_investigators') self.assign_permission_to(self.raj, 'can_view_household_groups') self.client.login(username='******', password='******')
def setUp(self): #self.patcher1 = patch('testing.original_call',mocked_original_call) #self.MockClass1 = self.patcher1.start() os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.test.utils import setup_test_environment setup_test_environment() pass
def setUp(self): self.client = Client(HTTP_HOST="testing") self.user = User.objects.get(pk=1) self.user.save() setup_test_environment() login = self.client.login(username=self.user.username, password="******") self.assertEqual(login, True)
def handle(self, *args, **options): settings.DEBUG = False setup_test_environment() verbosity = int(options.get('verbosity', 4)) apps_to_run = tuple(options.get('apps', '').split(",")) apps_to_avoid = tuple(options.get('avoid_apps', '').split(",")) run_server = not options.get('no_server', False) paths = self.get_paths(args, apps_to_run, apps_to_avoid) if run_server: server.start() failed = False try: for path in paths: registry.clear() result = Runner(path, options.get('scenarios'), verbosity).run() if not result or result.steps != result.steps_passed: failed = True except Exception, e: import traceback traceback.print_exc(e)
def before_all(context): setup_test_environment() context.db_cfg = setup_databases( verbosity=False, interactive=False, keepdb=not context.config.userdata.getbool('RESETDB') )
def call_unitTests(request): from logincounter.tests import UsersModelsTests import unittest from django.test.utils import setup_test_environment setup_test_environment() if (request.method =="POST" and request.path=='/TESTAPI/unitTests'): content_type = get_content_type(request) response_data = {} if (content_type == 'application/json'): try: suite = unittest.TestLoader().loadTestsFromTestCase(UsersModelsTests) testing_results = unittest.TextTestRunner(verbosity=2).run(suite) response_data['nrFailed'] = len(testing_results.failures) response_Data['totalTests'] = testing_results.testRuns response_data['output'] = "{}{}".format('\n'.join([result[1] for result in test_results.errors]),'\n'.join([result[1] for result in testing_results.failures])) except Exception: response_data['nrFailed'] = 0 response_data['output'] = "Error in running UnitTest" response_Data['totalTests'] = 0 return HttpResponse(json.dumps(response_data), content_type='application/json') else: return HttpResponseServerError("Requests invalid in unitTests")
def setup_django(self): from django.conf import settings # If Django < 1.2 if self.legacy_django: from django.db import connection from django.test.utils import setup_test_environment # Setup Django test environment setup_test_environment() # Create Django test database self.old_database_name = settings.DATABASE_NAME connection.creation.create_test_db(self.verbosity, autoclobber=True) # If Django >= 1.2 else: from django.test.simple import DjangoTestSuiteRunner # Initialize Django tests runner runner = DjangoTestSuiteRunner(interactive=self.interactive, verbosity=self.verbosity) # Setup test environment runner.setup_test_environment() # Setup test databases self.old_config = runner.setup_databases() self.runner = runner
def setUp(self): from django.conf import settings from django.test.utils import setup_test_environment if not settings.configured: settings.configure() setup_test_environment()
def setup(): setup_test_environment() if not hasattr(settings, 'DEBUG'): settings.DEBUG = False from django.db import connection connection.creation.create_test_db(verbosity=0, autoclobber=True) return Client()
#!/usr/bin/env python import os import sys # Set up the environment for our test project. ROOT = os.path.abspath(os.path.dirname(__file__)) os.environ['DJANGO_SETTINGS_MODULE'] = 'tower-project.settings' sys.path.insert(0, os.path.join(ROOT, 'examples')) # This can't be imported until after we've fiddled with the # environment. from django.test.utils import setup_test_environment setup_test_environment() from django.core.management import call_command # Run the equivalent of "django-admin.py test" call_command('test')
def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler()
def __init__(self, parent): super(DjangoContext, self).__init__(parent) from django.test.utils import setup_test_environment #, teardown_test_environment setup_test_environment()
def handle(self, *args, **options): setup_test_environment() verbosity = int(options.get('verbosity', 4)) apps_to_run = tuple(options.get('apps', '').split(",")) apps_to_avoid = tuple(options.get('avoid_apps', '').split(",")) run_server = not options.get('no_server', False) test_database = options.get('test_database', False) smtp_queue = options.get('smtp_queue', False) tags = options.get('tags', None) failfast = options.get('failfast', False) auto_pdb = options.get('auto_pdb', False) threading = options.get('use_threading', True) with_summary = options.get('summary_display', False) if test_database: migrate_south = getattr(settings, "SOUTH_TESTS_MIGRATE", True) try: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() except: migrate_south = False pass from django.test.utils import get_runner self._testrunner = get_runner(settings)(interactive=False) self._testrunner.setup_test_environment() self._old_db_config = self._testrunner.setup_databases() call_command( 'syncdb', verbosity=0, interactive=False, ) if migrate_south: call_command( 'migrate', verbosity=0, interactive=False, ) settings.DEBUG = options.get('debug', False) paths = self.get_paths(args, apps_to_run, apps_to_avoid) server = get_server(port=options['port'], threading=threading) if run_server: try: server.start() except Exception as e: raise SystemExit(e) os.environ['SERVER_NAME'] = str(server.address) os.environ['SERVER_PORT'] = str(server.port) failed = False registry.call_hook('before', 'harvest', locals()) results = [] try: for path in paths: app_module = None if isinstance(path, tuple) and len(path) is 2: path, app_module = path if app_module is not None: registry.call_hook('before_each', 'app', app_module) runner = Runner(path, options.get('scenarios'), verbosity, enable_xunit=options.get('enable_xunit'), enable_subunit=options.get('enable_subunit'), xunit_filename=options.get('xunit_file'), subunit_filename=options.get('subunit_file'), tags=tags, failfast=failfast, auto_pdb=auto_pdb, smtp_queue=smtp_queue) result = runner.run() if app_module is not None: registry.call_hook('after_each', 'app', app_module, result) results.append(result) if not result or result.steps != result.steps_passed: failed = True except SystemExit as e: failed = e.code except Exception as e: failed = True import traceback traceback.print_exc(e) finally: summary = SummaryTotalResults(results) summary.summarize_all() registry.call_hook('after', 'harvest', summary) if test_database: self._testrunner.teardown_databases(self._old_db_config) teardown_test_environment() server.stop(failed) raise SystemExit(int(failed))
def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False
''' was_published_recently() returns True for questions whose pub_date is within the last day. ''' time = timezone.now() - datetime.timedelta( hours=23, minutes=59, seconds=59 ) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) # Use the shell to test a view ------------------------------------------------ # Command Line py manage.py test polls >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') >>> response.status_code # Should be 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) >>> response.status_code # Should be 200 >>> response.content >>> response.context['latest_question_list'] # Update the Index View to exclude future questions & create tests ------------ # /mysite/polls/views.py (Show only past questions) ... from django.utils import timezone
def test_setup_test_environment_calling_more_than_once(self): with self.assertRaisesMessage( RuntimeError, "setup_test_environment() was already called"): setup_test_environment()
def run_tests(verbosity=1, interactive=False): from django.conf import settings from django.core import management from django.db import connection from django.test.utils import (setup_test_environment, teardown_test_environment) try: from django import setup # Django >= 1.7 setup() use_migrations = True except ImportError: # Django < 1.7 use_migrations = False # Restore warnings, if Django turns them off. warnings.simplefilter('default') setup_test_environment() settings.DEBUG = False for path in (settings.MEDIA_ROOT, settings.STATIC_ROOT): if not os.path.exists(path): os.mkdir(path, 0o755) old_db_name = 'default' connection.creation.create_test_db(verbosity, autoclobber=not interactive) if use_migrations: management.call_command('migrate', use_syncdb=True, verbosity=verbosity, interactive=interactive) else: management.call_command('syncdb', verbosity=verbosity, interactive=interactive) nose_argv = [ 'runtests.py', '-v', '--match=^test', '--with-id', ] if '--with-coverage' in sys.argv: sys.argv.remove('--with-coverage') nose_argv += [ '--with-coverage', '--cover-inclusive', '--cover-package=djblets', ] nose_argv += sys.argv[1:] # If the test files are executable on the file system, nose will need the # --exe argument to run them known_file = os.path.join(os.path.dirname(__file__), '..', 'djblets', 'settings.py') if (os.path.exists(known_file) and os.stat(known_file).st_mode & stat.S_IXUSR): nose_argv.append('--exe') nose.main(argv=nose_argv) connection.creation.destroy_test_db(old_db_name, verbosity) teardown_test_environment()
def __init__(self, methodName='runTest'): TestCase.__init__(self, methodName=methodName) setup_test_environment() self.client = Client()
def runtests(): test_runner_path = os.path.dirname(__file__) project_template_path = os.path.join( test_runner_path, 'misago/project_template/project_name') avatars_store_path = os.path.join(test_runner_path, 'misago/project_template/avatar_store') media_path = os.path.join(test_runner_path, 'misago/project_template/media') test_project_path = os.path.join(test_runner_path, "testproject") test_project_avatars_path = os.path.join(test_runner_path, "avatar_store") test_project_media_path = os.path.join(test_runner_path, "media") if not os.path.exists(test_project_path): shutil.copytree(project_template_path, test_project_path) shutil.copytree(avatars_store_path, test_project_avatars_path) shutil.copytree(media_path, test_project_media_path) settings_path = os.path.join(test_project_path, "settings.py") with open(settings_path, "r") as py_file: settings_file = py_file.read() # Do some configuration magic settings_file = settings_file.replace("{{ project_name }}", "testproject") settings_file = settings_file.replace("{{ secret_key }}", "t3stpr0j3ct") settings_file += """ MISAGO_NEW_REGISTRATIONS_VALIDATORS = () EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'uniqu3-sn0wf14k3' } } """ if os.environ.get('TRAVIS'): settings_file += """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'travis_ci_test', 'USER': '******', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '', } } TEST_NAME = 'travis_ci_test' """ else: settings_file += """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'misago_postgres', 'USER': '******', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } """ % pwd.getpwuid(os.getuid())[0] with open(settings_path, "w") as py_file: py_file.write(settings_file) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") setup() setup_test_environment() if __name__ == '__main__': args = sys.argv[1:] else: args = [] from django.core.management.commands import test sys.exit(test.Command().execute(*args, verbosity=1))
def setUp(self): setup_test_environment(debug=True) self.api_document = APIDocument() self.client = doc_client(self.api_document, self.client)
def handle(self, *args, **options): setup_test_environment() verbosity = options['verbosity'] no_color = options.get('no_color', False) apps_to_run = tuple(options['apps'].split(",")) apps_to_avoid = tuple(options['avoid_apps'].split(",")) run_server = not options['no_server'] test_database = options['test_database'] smtp_queue = options['smtp_queue'] tags = options['tags'] failfast = options['failfast'] auto_pdb = options['auto_pdb'] threading = options['use_threading'] if test_database: migrate_south = getattr(settings, "SOUTH_TESTS_MIGRATE", True) try: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() except: migrate_south = False pass from django.test.utils import get_runner self._testrunner = get_runner(settings)(interactive=False) self._testrunner.setup_test_environment() self._old_db_config = self._testrunner.setup_databases() if DJANGO_VERSION < StrictVersion('1.7'): call_command( 'syncdb', verbosity=0, interactive=False, ) if migrate_south: call_command( 'migrate', verbosity=0, interactive=False, ) else: call_command( 'migrate', verbosity=0, interactive=False, ) settings.DEBUG = options.get('debug', False) paths = self.get_paths(args, apps_to_run, apps_to_avoid) server = get_server(port=options['port'], threading=threading) if run_server: try: server.start() except LettuceServerException as e: raise CommandError("Couldn't start Django server: %s" % e) os.environ['SERVER_NAME'] = str(server.address) os.environ['SERVER_PORT'] = str(server.port) failed = False registry.call_hook('before', 'harvest', locals()) results = [] try: for path in paths: app_module = None if isinstance(path, tuple) and len(path) is 2: path, app_module = path if app_module is not None: registry.call_hook('before_each', 'app', app_module) runner = Runner( path, options.get('scenarios'), verbosity, no_color, enable_xunit=options.get('enable_xunit'), enable_subunit=options.get('enable_subunit'), enable_jsonreport=options.get('enable_jsonreport'), xunit_filename=options.get('xunit_file'), subunit_filename=options.get('subunit_file'), jsonreport_filename=options.get('jsonreport_file'), tags=tags, failfast=failfast, auto_pdb=auto_pdb, smtp_queue=smtp_queue) result = runner.run() if app_module is not None: registry.call_hook('after_each', 'app', app_module, result) results.append(result) if not result or result.steps != result.steps_passed: failed = True except LettuceRunnerError: failed = True except Exception as e: failed = True traceback.print_exc(e) finally: summary = SummaryTotalResults(results) summary.summarize_all() registry.call_hook('after', 'harvest', summary) if test_database: self._testrunner.teardown_databases(self._old_db_config) teardown_test_environment() server.stop(failed) if failed: raise CommandError("Lettuce tests failed.")
def pytest_configure(config): if django.VERSION >= (1, 7): django.setup() setup_test_environment() connection.creation.create_test_db(verbosity=2, autoclobber=True)
def setup_package(module): utils.setup_test_environment() module._old_db_name = connection.creation.create_test_db(verbosity=1)
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 setUp(self): super().setUp() setup_test_environment() _django_instrumentor.instrument() Configuration._reset() # pylint: disable=protected-access
def setup_test_environment(self, **kwargs): setup_test_environment()
def setup_module(): utils.setup_test_environment()
def begin(self): from django.test.utils import setup_test_environment setup_test_environment()
def run_suite(self, nose_argv=None): """Test runner that invokes nose.""" # Prepare django for testing. from django.conf import settings utils.setup_test_environment() old_db_name = settings.DATABASE_NAME result_plugin = ResultPlugin() plugins = [ DjangoPlugin(), SeleniumPlugin(), DjangoTranslationPlugin(), result_plugin ] if getattr(settings, 'CHERRYPY_TEST_SERVER', False): plugins.append(CherryPyLiveServerPlugin()) else: plugins.append(DjangoLiveServerPlugin()) # Do not pretend it's a production environment. # settings.DEBUG = False # We pass nose a list of arguments that looks like sys.argv, but customize # to avoid unknown django arguments. for plugin in _get_plugins_from_settings(): plugins_to_add.append(plugin) # activate all required plugins activate_plugin(DjangoPlugin, nose_argv) activate_plugin(SeleniumPlugin, nose_argv) activate_plugin(DjangoTranslationPlugin, nose_argv) # activate_plugin(ResultPlugin, nose_argv) if getattr(settings, 'CHERRYPY_TEST_SERVER', False): activate_plugin(CherryPyLiveServerPlugin, nose_argv) else: activate_plugin(DjangoLiveServerPlugin, nose_argv) # Skip over 'manage.py test' and any arguments handled by django. django_opts = ['--noinput'] for opt in BaseCommand.option_list: django_opts.extend(opt._long_opts) django_opts.extend(opt._short_opts) nose_argv.extend( OPTION_TRANSLATION.get(opt, opt) for opt in sys.argv[1:] if opt.startswith('-') and not any( opt.startswith(d) for d in django_opts)) if self.verbosity >= 2: print ' '.join(nose_argv) test_program = nose.core.TestProgram(argv=nose_argv, exit=False, addplugins=plugins) # FIXME: ResultPlugin is working not exactly as advertised in django-nose # multiple instance problem, find workaround # result = result_plugin.result # return len(result.failures) + len(result.errors) return not test_program.success
def setUp(self): setup_test_environment()
def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False unittest.installHandler()
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[], suite=None): """ This module allows users to run tests for GIS apps that require the creation of a spatial database. Currently, this is only required for PostgreSQL as PostGIS needs extra overhead in test database creation. In order to create a PostGIS database, the DATABASE_USER (or TEST_DATABASE_USER, if defined) will require superuser priviliges. To accomplish this outside the `postgres` user, you have a few options: (A) Make your user a super user: This may be done at the time the user is created, for example: $ createuser --superuser <user_name> Or you may alter the user's role from the SQL shell (assuming this is done from an existing superuser role): postgres# ALTER ROLE <user_name> SUPERUSER; (B) Create your own PostgreSQL database as a local user: 1. Initialize database: `initdb -D /path/to/user/db` 2. If there's already a Postgres instance on the machine, it will need to use a different TCP port than 5432. Edit postgresql.conf (in /path/to/user/db) to change the database port (e.g. `port = 5433`). 3. Start this database `pg_ctl -D /path/to/user/db start` (C) On Windows platforms the pgAdmin III utility may also be used as a simple way to add superuser privileges to your database user. The TEST_RUNNER needs to be set in your settings like so: TEST_RUNNER='django.contrib.gis.tests.run_tests' Note: This test runner assumes that the PostGIS SQL files ('lwpostgis.sql' and 'spatial_ref_sys.sql') are installed in the directory specified by `pg_config --sharedir` (and defaults to /usr/local/share if that fails). This behavior is overridden if POSTGIS_SQL_PATH is set in your settings. Windows users should set POSTGIS_SQL_PATH manually because the output of `pg_config` uses paths like 'C:/PROGRA~1/POSTGR~1/..'. Finally, the tests may be run by invoking `./manage.py test`. """ # The `create_spatial_db` routine abstracts away all the steps needed # to properly construct a spatial database for the backend. from django.contrib.gis.db.backend import create_spatial_db # Setting up for testing. setup_test_environment() settings.DEBUG = False old_name = settings.DATABASE_NAME # The suite may be passed in manually, e.g., when we run the GeoDjango test, # we want to build it and pass it in due to some customizations. Otherwise, # the normal test suite creation process from `django.test.simple.run_tests` # is used to create the test suite. if suite is None: 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) # Creating the test spatial database. create_spatial_db(test=True, verbosity=verbosity) # Executing the tests (including the model tests), and destorying the # test database after the tests have completed. result = unittest.TextTestRunner(verbosity=verbosity).run(suite) connection.creation.destroy_test_db(old_name, verbosity) teardown_test_environment() # Returning the total failures and errors return len(result.failures) + len(result.errors)
def setUpModule(): django_test_utils.setup_test_environment() runner_state = django_test_utils.setup_databases(verbosity=0, interactive=False) test_state['runner_state'] = runner_state
def setUp(self): super().setUp() setup_test_environment() _django_instrumentor.instrument()
def setup_test_environment(self): setup_test_environment() settings.DEBUG = False
def setup_test_environment(self, **kwargs): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = TEST_HOST setup_test_environment() settings.DEBUG = True unittest.installHandler()
def setup_client(self): self.client = Client() setup_test_environment()
def pre_test(self): dutils.setup_test_environment() old_conf = dutils.setup_databases(1, False, aliases='default') self.start_app_threat() self._wait_for_live_app() return old_conf
def handle(self, **options): taskName = options['task'] if not taskName: raise ValueError('required argument --task not specified') async = options['async'] if async: D = Detacher() if sys.platform == 'win32': if not options['detached']: D.detach() else: D.detach() #if we're here we should be fully detached #if --task-testing was passed we use a test setup if options['testing']: from django.test.utils import setup_test_environment setup_test_environment() pid = os.getpid() logs = os.path.join(settings.ENVIRON_DIR, 'logs') if not os.path.isdir(logs): os.makedirs(logs) log = IdentiFile(open(os.path.join(logs, 'deferredtasks.out'), 'a'), '%-5d' % pid) success = False print >> log, '##### task %s[%-5d] started' % (taskName, pid) try: if options['log_std']: #debug version everything get's written to the logfile as well class StringIOX(StringIO): def write(self, s): log.write(s) StringIO.write(self, s) sys_stdout = StringIOX() sys_stderr = StringIOX() else: sys_stdout = StringIO() sys_stderr = StringIO() if not async: old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = sys_stdout sys.stderr = sys_stderr dtask = DeferredTask() dtask.start = utcnow() dtask.pid = pid dtask.progress = 0 username = options.get('username', '') dtask.username = decode(username) if username else '' dtask.status = 'initialized' # reset DB connection which might have been killed in detachment process # but close_connection deprecated in Django 1.8 # seems to be working OK without this #db.close_connection() dtask.save() D = {} dtask.task = taskName dtask.save() exec 'from %s import %s as task' % tuple(taskName.rsplit('.', 1)) in D task = D['task'] args = options.get('args', ()) if args: args = decode(args) kwds = options.get('kwds', {}) if kwds: kwds = decode(kwds) _success_url = kwds.pop('task_success_url', False) dtask.success_url = '' if _success_url and not '?pid=' in _success_url: if '?' in _success_url: dtask.success_url = "%s&pid=%s" % (_success_url, dtask.pid) else: dtask.success_url = "%s?pid=%s" % (_success_url, dtask.pid) dtask.args = repr(args) dtask.kwds = repr(kwds) dtask.hashcode = hashFunc(taskName, args, kwds) dtask.title = kwds.pop('task_title', '') dtask.status = 'prepared' dtask.save() result = getattr(task, '_task_func', task)(*args, **kwds) dtask = DeferredTask.objects.get(pid=pid) dtask.result = result dtask.status = 'finished' dtask.progress = 100 dtask.save() success = True except: traceback.print_exc() traceback.print_exc(file=log) finally: try: dtask = DeferredTask.objects.get(pid=pid) dtask.success = success dtask.finished = True dtask.status = 'suceeded' if success else 'failed' dtask.finish = utcnow() dtask.stdout = sys_stdout.getvalue() dtask.stderr = sys_stderr.getvalue() dtask.save() print >> log, '%s task %s[%-5d] %s' % ( ('!!!!!', '#####')[success], taskName, pid, ('failed!', 'ended OK.')[success]) except: traceback.print_exc(file=log) finally: if not async: sys.stdout = old_stdout sys.stderr = old_stderr