def test_username_non_unique(self): "A non-unique USERNAME_FIELD should raise a model validation error." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn( "The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue())
def test_username_not_in_required_fields(self): "USERNAME_FIELD should not appear in REQUIRED_FIELDS." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn( "The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue())
def test_declared_fields_doesnt_break_modelbase(self): # I'm not sure if this actually tests anything from django.core.management.validation import get_validation_errors from StringIO import StringIO class AppMod(object): __name__ = 'fusionbox.behaviors' class Sluggable(Behavior): slug = models.CharField(max_length=255) class Meta: abstract = True unique_together = (('slug', ), ) class AbstractSluggableModel(Sluggable, models.Model): class Meta: unique_together = (('slug', ), ) abstract = True class TheActualModel(AbstractSluggableModel): pass app_mod = AppMod() errors = StringIO() get_validation_errors(errors, app_mod) errors = errors.getvalue() self.assertTrue(errors == '')
def test_username_not_in_required_fields(self): "USERNAME_FIELD should not appear in REQUIRED_FIELDS." new_io = StringIO() get_validation_errors(new_io, get_app("auth")) self.assertIn( "The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue(), )
def __init__(self, *args, **kwargs): # Make sure all models are completely loaded before attempting to # proceed. The dynamic nature of FeinCMS models makes this necessary. # For more informations, have a look at issue #23 on github: # http://github.com/matthiask/feincms/issues#issue/23 from django.core.management.validation import get_validation_errors from StringIO import StringIO get_validation_errors(StringIO(), None) super(ItemEditor, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): # Make sure all models are completely loaded before attempting to # proceed. The dynamic nature of FeinCMS models makes this necessary. # For more informations, have a look at issue #23 on github: # http://github.com/matthiask/feincms/issues#issue/23 from django.core.management.validation import get_validation_errors from StringIO import StringIO get_validation_errors(StringIO(), None) super(ItemEditor, self).__init__(*args, **kwargs)
def test_invalid_models(self): app_config = apps.get_app_config("invalid_models") get_validation_errors(self.stdout, app_config) self.stdout.seek(0) error_log = self.stdout.read() actual = error_log.split('\n') expected = app_config.models_module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))
def ensure_completely_loaded(): global COMPLETELY_LOADED if COMPLETELY_LOADED: return # Make sure all models are completely loaded before attempting to # proceed. The dynamic nature of FeinCMS models makes this necessary. # For more informations, have a look at issue #23 on github: # http://github.com/matthiask/feincms/issues#issue/23 from django.core.management.validation import get_validation_errors from StringIO import StringIO get_validation_errors(StringIO(), None) COMPLETELY_LOADED = True
def validate_models(): """ Since BaseRunserverCommand is only run once, we need to call model valdidation here to ensure it is run every time the code changes. """ import logging from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO logging.info("Validating models...") s = StringIO() num_errors = get_validation_errors(s, None) if num_errors: s.seek(0) error_text = s.read() logging.critical("One or more models did not validate:\n%s" % error_text) else: logging.info("All models validated.")
def runTest(self): from django.core.management.validation import get_validation_errors from django.db.models.loading import load_app from io import StringIO try: module = load_app(self.model_label) except Exception as e: self.fail('Unable to load invalid model module') # Make sure sys.stdout is not a tty so that we get errors without # coloring attached (makes matching the results easier). We restore # sys.stderr afterwards. orig_stdout = sys.stdout s = StringIO() sys.stdout = s count = get_validation_errors(s, module) sys.stdout = orig_stdout s.seek(0) error_log = s.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertTrue(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertTrue(not missing, "Missing Errors: " + '\n'.join(missing))
def validate_models(self): import django try: django_setup = django.setup except AttributeError: pass else: django_setup() s = io.StringIO() try: from django.core.management.validation import get_validation_errors except ImportError: from django.core.management.base import BaseCommand cmd = BaseCommand() try: # since django 1.5 from django.core.management.base import OutputWrapper cmd.stdout = OutputWrapper(sys.stdout) cmd.stderr = OutputWrapper(sys.stderr) except ImportError: cmd.stdout, cmd.stderr = sys.stdout, sys.stderr cmd.check() else: num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError( 'One or more Django models did not validate:\n{0}'.format( s.getvalue()))
class InvalidModelTestCase(unittest.TestCase): def __init__(self, model_label): unittest.TestCase.__init__(self) self.model_label = model_label def runTest(self): from django.core.management.validation import get_validation_errors from django.db.models.loading import load_app from cStringIO import StringIO try: module = load_app(self.model_label) except Exception, e: self.fail('Unable to load invalid model module') # Make sure sys.stdout is not a tty so that we get errors without # coloring attached (makes matching the results easier). We restore # sys.stderr afterwards. orig_stdout = sys.stdout s = StringIO() sys.stdout = s count = get_validation_errors(s, module) sys.stdout = orig_stdout s.seek(0) error_log = s.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assert_(not missing, "Missing Errors: " + '\n'.join(missing))
def test_invalid_models(self): try: module = load_app("modeltests.invalid_models.invalid_models") except Exception: self.fail('Unable to load invalid model module') get_validation_errors(self.stdout, module) self.stdout.seek(0) error_log = self.stdout.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))
def test_invalid_models(self): try: module = load_app("invalid_models.invalid_models") except Exception: self.fail('Unable to load invalid model module') get_validation_errors(self.stdout, module) self.stdout.seek(0) error_log = self.stdout.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))
def validate_models(self): from django.core.management.validation import get_validation_errors s = io.StringIO() num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError( 'One or more Django models did not validate:\n{0}'.format( s.getvalue()))
def validate_models(self): self.django_setup() try: from django.core.management.validation import get_validation_errors except ImportError: self._validate_models_django17() else: s = StringIO() num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError("One or more Django models did not validate:\n{0}".format(s.getvalue()))
def validate_models(self): self.django_setup() try: from django.core.management.validation import get_validation_errors except ImportError: self._validate_models_django17() else: s = StringIO() num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError( 'One or more Django models did not validate:\n{0}'.format( s.getvalue()))
def ensure_completely_loaded(): """ This method ensures all models are completely loaded FeinCMS requires Django to be completely initialized before proceeding, because of the extension mechanism and the dynamically created content types. For more informations, have a look at issue #23 on github: http://github.com/feincms/feincms/issues#issue/23 """ global COMPLETELY_LOADED if COMPLETELY_LOADED: return True from django.core.management.validation import get_validation_errors from StringIO import StringIO get_validation_errors(StringIO(), None) COMPLETELY_LOADED = True return True
def ensure_completely_loaded(): """ This method ensures all models are completely loaded FeinCMS requires Django to be completely initialized before proceeding, because of the extension mechanism and the dynamically created content types. For more informations, have a look at issue #23 on github: http://github.com/matthiask/feincms/issues#issue/23 """ global COMPLETELY_LOADED if COMPLETELY_LOADED: return True from django.core.management.validation import get_validation_errors from StringIO import StringIO get_validation_errors(StringIO(), None) COMPLETELY_LOADED = True return True
def validate_models(self): self.django_setup() try: from django.core.checks import run_checks except ImportError: # django < 1.7 from django.core.management.validation import get_validation_errors s = StringIO() num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError( 'One or more Django models did not validate:\n{0}'.format( s.getvalue())) else: run_checks()
def run_tests(self, test_labels, extra_tests=[], **kwargs): # Shutup console logs logger = logging.getLogger() for h in logger.handlers: logger.removeHandler(h) import coverage coverage.erase() coverage.start() # If test_labels let django handle it if test_labels: return super(TestRunner, self).run_tests(test_labels, extra_tests) # Validate models s = StringIO() num_errors = get_validation_errors(s) if num_errors: raise Exception("%s error%s found:\n%s" % (num_errors, num_errors != 1 and 's' or '', s.getvalue())) # Use discover to find all the local tests loader = unittest.TestLoader() base = os.path.abspath(os.path.dirname(__file__)) if not extra_tests: extra_tests = [] tests = loader.discover(base) suite = unittest.TestSuite() if extra_tests: suite.addTests(extra_tests) suite.addTests(tests) local_dirs = [x for x in os.listdir(base) if os.path.isdir(os.path.join(base,x))] local_dirs.extend([x for x in os.listdir(os.path.join(base, 'apps')) \ if os.path.isdir(os.path.join(base,'apps', x))]) self.setup_test_environment() old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() result = self.suite_result(suite, result) if not result and self.verbosity >= 1: report_coverage(local_dirs) return result
def make_wsgi_application(): # validate models s = StringIO() if get_validation_errors(s): s.seek(0) error = s.read() sys.stderr.write("One or more models did not validate:\n%s" % error) sys.stderr.flush() sys.exit(1) translation.activate(settings.LANGUAGE_CODE) if django14: return get_internal_wsgi_application() return WSGIHandler()
def test_declared_fields_doesnt_break_modelbase(self): # I'm not sure if this actually tests anything from django.core.management.validation import get_validation_errors from StringIO import StringIO class AppMod(object): __name__ = 'fusionbox.behaviors' class Sluggable(Behavior): slug = models.CharField(max_length=255) class Meta: abstract = True unique_together = (('slug',),) class AbstractSluggableModel(Sluggable, models.Model): class Meta: unique_together = (('slug',),) abstract = True class TheActualModel(AbstractSluggableModel): pass app_mod = AppMod() errors = StringIO() get_validation_errors(errors, app_mod) errors = errors.getvalue() self.assertTrue(errors == '')
def validate(self, app=None, display_num_errors=False): """ Validates the given app, raising CommandError for any errors. If app is None, then this will validate all installed apps. """ from django.core.management.validation import get_validation_errors s = StringIO() num_errors = get_validation_errors(s, app) if num_errors: s.seek(0) error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: self.stdout.write("%s error%s found" % (num_errors, '' if num_errors == 1 else 's'))
def validate(self, app_config=None, display_num_errors=False): """ Validates the given app, raising CommandError for any errors. If app_config is None, then this will validate all installed apps. """ from django.core.management.validation import get_validation_errors s = StringIO() num_errors = get_validation_errors(s, app_config) if num_errors: s.seek(0) error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: self.stdout.write("%s error%s found" % (num_errors, '' if num_errors == 1 else 's'))
def validate_models(self): s = io.StringIO() try: from django.core.management.validation import get_validation_errors except ImportError: import django from django.core.management.base import BaseCommand django.setup() cmd = BaseCommand() cmd.stdout, cmd.stderr = sys.stdout, sys.stderr cmd.check() else: num_errors = get_validation_errors(s, None) if num_errors: raise RuntimeError( 'One or more Django models did not validate:\n{0}'.format( s.getvalue()))
def validate(self): """ Validate models. This also ensures that all models are imported in case of import-time side effects.""" from django.core.management.base import CommandError from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() if get_validation_errors(s): s.seek(0) error = s.read() sys.stderr.write("One or more models did not validate:\n%s" % error) sys.stderr.flush() sys.exit(1)
def validate(self, app=None, display_num_errors=False): """ Validates the given app, raising CommandError for any errors. If app is None, then this will validate all installed apps. """ from django.core.management.validation import get_validation_errors try: from io import StringIO except ImportError: from io import StringIO s = StringIO() num_errors = get_validation_errors(s, app) if num_errors: s.seek(0) error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: print("%s error%s found" % (num_errors, num_errors != 1 and 's' or ''))
def validate(self, app=None, display_num_errors=False): """ Validates the given app, raising CommandError for any errors. If app is None, then this will validate all installed apps. """ from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() num_errors = get_validation_errors(s, app) if num_errors: s.seek(0) error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: print "%s error%s found" % (num_errors, num_errors != 1 and 's' or '')
def check_plugin_broken(plugin_name): """ Check if plugin is broken (i.e. not exist in file system) and raises an exception """ try: get_plugin_config(plugin_name) try: # try to import plugin modules (if exists) to validate those models models_modname = '%s.models' % get_plugin_module_name(plugin_name) models_module = import_module(models_modname) s = StringIO() num_errors = get_validation_errors(s, models_module) if num_errors: # the plugin was broken because some models validation break return True except ImportError: # usually means models module does not exists. Don't worry about that pass except (TypeError, FieldError, SyntaxError): # some validation error when importing models raise BrokenPlugin(plugin_name, *sys.exc_info()) except Exception: raise BrokenPlugin(plugin_name, *sys.exc_info())
def check_plugin_broken(plugin_name): """ Check if plugin is broken (i.e. not exist in file system) and raises an exception """ try: get_plugin_config(plugin_name) try: # try to import plugin modules (if exists) to validate those models models_modname = '%s.models' % get_plugin_module_name(plugin_name) models_module = import_module(models_modname) s = StringIO() num_errors = get_validation_errors(s, models_module) if num_errors: # the plugin was broken because some models validation break return True except ImportError: # usually means models module does not exists. Don't worry about that pass except (TypeError, FieldError, SyntaxError): # some validation error when importing models raise BrokenPlugin(plugin_name, *sys.exc_info()) except Exception: raise BrokenPlugin(plugin_name, *sys.exc_info())
class InvalidModelTestCase(unittest.TestCase): """Import an appliation with invalid models and test the exceptions.""" def setUp(self): # Make sure sys.stdout is not a tty so that we get errors without # coloring attached (makes matching the results easier). We restore # sys.stderr afterwards. self.old_stdout = sys.stdout self.stdout = StringIO() sys.stdout = self.stdout # This test adds dummy applications to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. self.old_app_models = copy.deepcopy(cache.app_models) self.old_app_store = copy.deepcopy(cache.app_store) def tearDown(self): cache.app_models = self.old_app_models cache.app_store = self.old_app_store cache._get_models_cache = {} sys.stdout = self.old_stdout def test_invalid_models(self): try: module = load_app("modeltests.invalid_models.invalid_models") except Exception, e: self.fail('Unable to load invalid model module') count = get_validation_errors(self.stdout, module) self.stdout.seek(0) error_log = self.stdout.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))
def main(context): try: subcommands = [SUBCOMMANDS[cmd] for cmd in context.subcmds] except KeyError as exc: # argparse should protect against this, but otherwise: raise CommandError("unknown command: {}".format(exc)) # Ensure models loaded # try: import_module(context.models) # FIXME: will non-Django apps work like this? except ImportError: try: from django.core.management.validation import get_validation_errors except ImportError: raise CommandError("failed to import: {!r}".format(context.models)) else: buf = StringIO() num_errors = get_validation_errors(buf) if num_errors: buf.seek(0) raise CommandError("one or more Django models did not validate:\n%s" % buf.read()) for command in subcommands: command(context)
def test_username_non_unique(self): "A non-unique USERNAME_FIELD should raise a model validation error." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue())
def test_required_fields_is_list(self): "REQUIRED_FIELDS should be a list." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue())
# Add project directory to PYTHON_PATH import os, sys path = '/home/axinite/axinite/' if path not in sys.path: sys.path.append(path) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "axinite.settings") # BEGIN WORKAROUND FOR 500 ERROR WHEN DEBUG=False from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() num_errors = get_validation_errors(s, None) # END WORKAROUND from django.core.wsgi import get_wsgi_application application = get_wsgi_application() import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
def test_required_fields_is_list(self): "REQUIRED_FIELDS should be a list." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue())
path = '/home/hrms/hrms/' if path not in sys.path: sys.path.append(path) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hrms.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() # BEGIN WORKAROUND FOR 500 ERROR WHEN DEBUG=False # from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() num_errors = get_validation_errors(s, None) # END WORKAROUND # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)