Exemplo n.º 1
0
def test_app(app):
    """test_app(app)
    
    Tests the application app:
    - a clean sqlite in-memory database is create
    - the applications models are installed
    - the fixtures in path-to-app/fixtures/*.yml are created
    - settings.ROOT_URLCONF is pointed at the applications urls-module
    - the tests in the tests-module are run with doctest.testmod
      given the fixtures and a browser-instance as globals
    """

    # Import application module
    if '.' in app:
        i = app.rfind('.')
        app_name = app[i+1:]
    else:
        app_name = app
    module = __import__(app, None, None, ['*'])

    # Reinitialize database
    db.db.real_close() # this is in effect a 'drop database' with a sqlite :memory: database
    management.init()

    # Install models
    for model in module.models.__all__:
        management.install(meta.get_app(model))

    # Load fixtures
    files = os.path.join(os.path.dirname(module.__file__), 'fixtures', '*.yml')
    fixtures = {}
    for yml in [ yaml.loadFile(f) for f in glob(files) ]:
        models = yml.next()
        
        for model, fixs in models.items():
            model = meta.get_module(app_name, model)
            klass = model.Klass
    
            for name, kwargs in fixs.items():
                obj = create_object(klass, kwargs)
                # Load object from database, this normalizes it.
                fixtures[name] = model.get_object(pk=obj.id)

    # Commit fixtures
    db.db.commit()

    # Munge django.conf.settings.ROOT_URLCONF to point to
    # this apps urls-module,
    settings.ROOT_URLCONF = app + '.urls'

    # Run tests
    module = __import__(app, None, None, ['tests'])
    tests = getattr(module, 'tests', None)
    if tests:
        globs = {
            'browser': Browser(app),
        }
        globs.update(fixtures)
        doctest.testmod(tests, None, globs)
Exemplo n.º 2
0
def init():
    "Initializes the database with auth and core."
    try:
        from django.core import db, meta
        auth = meta.get_app('auth')
        core = meta.get_app('core')
        cursor = db.db.cursor()
        for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth):
            cursor.execute(sql)
        cursor.execute("INSERT INTO %s (%s, %s) VALUES ('example.com', 'Example site')" % \
            (db.db.quote_name(core.Site._meta.db_table), db.db.quote_name('domain'),
            db.db.quote_name('name')))
    except Exception, e:
        sys.stderr.write("Error: The database couldn't be initialized.\n%s\n" % e)
        try:
            db.db.rollback()
        except UnboundLocalError:
            pass
        sys.exit(1)
Exemplo n.º 3
0
def model_detail(request, model):
    if not doc:
        return missing_docutils_page(request)

    try:
        model = meta.get_app(model)
    except ImportError:
        raise Http404
    opts = model.Klass._meta

    # Gather fields/field descriptions
    fields = []
    for field in opts.fields:
        fields.append({
            'name'     : field.name,
            'data_type': get_readable_field_data_type(field),
            'verbose'  : field.verbose_name,
            'help'     : field.help_text,
        })
    for func_name, func in model.Klass.__dict__.items():
        if callable(func) and len(inspect.getargspec(func)[0]) == 0:
            try:
                for exclude in MODEL_METHODS_EXCLUDE:
                    if func_name.startswith(exclude):
                        raise StopIteration
            except StopIteration:
                continue
            verbose = func.__doc__
            if verbose:
                verbose = doc.parse_rst(doc.trim_docstring(verbose), 'model', 'model:' + opts.module_name)
            fields.append({
                'name'      : func_name,
                'data_type' : get_return_data_type(func_name),
                'verbose'   : verbose,
            })
    return render_to_response('admin_doc/model_detail', {
        'name': '%s.%s' % (opts.app_label, opts.module_name),
        'summary': "Fields on %s objects" % opts.verbose_name,
        'fields': fields,
    }, context_instance=DjangoContext(request))
Exemplo n.º 4
0
def main():
    # Parse the command-line arguments. optparse handles the dirty work.
    parser = DjangoOptionParser(get_usage())
    parser.add_option('--settings',
        help='Python path to settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
    parser.add_option('--pythonpath',
        help='Lets you manually add a directory the Python path, e.g. "/home/djangoprojects/myproject".')
    options, args = parser.parse_args()

    # Take care of options.
    if options.settings:
        os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
    if options.pythonpath:
        sys.path.insert(0, options.pythonpath)

    # Run the appropriate action. Unfortunately, optparse can't handle
    # positional arguments, so this has to parse/validate them.
    try:
        action = args[0]
    except IndexError:
        parser.print_usage_and_exit()
    if not ACTION_MAPPING.has_key(action):
        print_error("Your action, %r, was invalid." % action, sys.argv[0])

    # switch to english, because django-admin creates database content
    # like permissions, and those shouldn't contain any translations.
    # But only do this if we should have a working settings file.
    if action not in ('startproject', 'startapp'):
        from django.utils import translation
        translation.activate('en-us')

    if action in ('createsuperuser', 'init', 'validate'):
        ACTION_MAPPING[action]()
    elif action == 'inspectdb':
        try:
            param = args[1]
        except IndexError:
            parser.print_usage_and_exit()
        try:
            for line in ACTION_MAPPING[action](param):
                print line
        except NotImplementedError:
            sys.stderr.write("Error: %r isn't supported for the currently selected database backend.\n" % action)
            sys.exit(1)
    elif action == 'createcachetable':
        try:
            ACTION_MAPPING[action](args[1])
        except IndexError:
            parser.print_usage_and_exit()
    elif action in ('startapp', 'startproject'):
        try:
            name = args[1]
        except IndexError:
            parser.print_usage_and_exit()
        ACTION_MAPPING[action](name, os.getcwd())
    elif action == 'runserver':
        if len(args) < 2:
            addr = ''
            port = '8000'
        else:
            try:
                addr, port = args[1].split(':')
            except ValueError:
                addr, port = '', args[1]
        ACTION_MAPPING[action](addr, port)
    else:
        from django.core import meta
        if action == 'dbcheck':
            mod_list = meta.get_all_installed_modules()
        else:
            try:
                mod_list = [meta.get_app(app_label) for app_label in args[1:]]
            except ImportError, e:
                sys.stderr.write("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e)
                sys.exit(1)
            if not mod_list:
                parser.print_usage_and_exit()
        if action not in NO_SQL_TRANSACTION:
            print "BEGIN;"
        for mod in mod_list:
            output = ACTION_MAPPING[action](mod)
            if output:
                print '\n'.join(output)
        if action not in NO_SQL_TRANSACTION:
            print "COMMIT;"
Exemplo n.º 5
0
    def run_tests(self):
        from django.conf import settings
        from django.core.db import db
        from django.core import management, meta

        # Manually set INSTALLED_APPS to point to the test app.
        settings.INSTALLED_APPS = (APP_NAME,)

        # Determine which models we're going to test.
        test_models = get_test_models()
        if self.which_tests:
            # Only run the specified tests.
            bad_models = [m for m in self.which_tests if m not in test_models]
            if bad_models:
                sys.stderr.write("Models not found: %s\n" % bad_models)
                sys.exit(1)
            else:
                test_models = self.which_tests

        self.output(0, "Running tests with database %r" % settings.DATABASE_ENGINE)

        # If we're using SQLite, it's more convenient to test against an
        # in-memory database.
        if settings.DATABASE_ENGINE == "sqlite3":
            global TEST_DATABASE_NAME
            TEST_DATABASE_NAME = ":memory:"
        else:
            # Create the test database and connect to it. We need autocommit()
            # because PostgreSQL doesn't allow CREATE DATABASE statements
            # within transactions.
            cursor = db.cursor()
            try:
                db.connection.autocommit(1)
            except AttributeError:
                pass
            self.output(1, "Creating test database")
            try:
                cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
            except:
                confirm = raw_input("The test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_DATABASE_NAME)
                if confirm == 'yes':
                    cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
                    cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
                else:
                    print "Tests cancelled."
                    return
        db.close()
        old_database_name = settings.DATABASE_NAME
        settings.DATABASE_NAME = TEST_DATABASE_NAME

        # Initialize the test database.
        cursor = db.cursor()
        self.output(1, "Initializing test database")
        management.init()

        # Run the tests for each test model.
        self.output(1, "Running app tests")
        for model_name in test_models:
            self.output(1, "%s model: Importing" % model_name)
            try:
                mod = meta.get_app(model_name)
            except Exception, e:
                log_error(model_name, "Error while importing", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
                continue
            self.output(1, "%s model: Installing" % model_name)
            management.install(mod)

            # Run the API tests.
            p = doctest.DocTestParser()
            test_namespace = dict([(m._meta.module_name, getattr(mod, m._meta.module_name)) for m in mod._MODELS])
            dtest = p.get_doctest(mod.API_TESTS, test_namespace, model_name, None, None)
            # Manually set verbose=False, because "-v" command-line parameter
            # has side effects on doctest TestRunner class.
            runner = DjangoDoctestRunner(verbosity_level=verbosity_level, verbose=False)
            self.output(1, "%s model: Running tests" % model_name)
            try:
                runner.run(dtest, clear_globs=True, out=sys.stdout.write)
            finally:
                # Rollback, in case of database errors. Otherwise they'd have
                # side effects on other tests.
                db.rollback()