コード例 #1
0
 def test_activate_with_non_existent_catalogs(self):
     locales = self._get_available_locales()
     if locales:
         locale_dir = self._get_locale_dir()
         translation.add_domain('catalog1', self.env.path, locale_dir)
         translation.add_domain('catalog2', self.env.path, locale_dir)
         translation.activate(locales[0], self.env.path)
コード例 #2
0
ファイル: console.py プロジェクト: pkdevbox/trac
def run(args=None):
    """Main entry point."""
    if args is None:
        args = sys.argv[1:]
    if has_babel:
        translation.activate(get_console_locale())
    warn_setuptools_issue()
    admin = TracAdmin()
    if len(args) > 0:
        if args[0] in ('-h', '--help', 'help'):
            return admin.onecmd(' '.join(['help'] + args[1:]))
        elif args[0] in ('-v','--version'):
            printout(os.path.basename(sys.argv[0]), TRAC_VERSION)
        else:
            env_path = os.path.abspath(args[0])
            try:
                unicode(env_path, 'ascii')
            except UnicodeDecodeError:
                printerr(_("Non-ascii environment path '%(path)s' not "
                           "supported.", path=to_unicode(env_path)))
                sys.exit(2)
            admin.env_set(env_path)
            if len(args) > 1:
                s_args = ' '.join(["'%s'" % c for c in args[2:]])
                command = args[1] + ' ' + s_args
                return admin.onecmd(command)
            else:
                while True:
                    try:
                        admin.run()
                    except KeyboardInterrupt:
                        admin.do_quit('')
    else:
        return admin.onecmd("help")
コード例 #3
0
ファイル: translation.py プロジェクト: pkdevbox/trac
 def test_activate_with_non_existent_catalogs(self):
     locales = self._get_available_locales()
     if locales:
         locale_dir = self._get_locale_dir()
         translation.add_domain('catalog1', self.env.path, locale_dir)
         translation.add_domain('catalog2', self.env.path, locale_dir)
         translation.activate(locales[0], self.env.path)
コード例 #4
0
ファイル: console.py プロジェクト: minimalistduck/trac
 def _init_env(self):
     self.__env = env = Environment(self.envname)
     # fix language according to env settings
     if has_babel:
         negotiated = get_console_locale(env)
         if negotiated:
             translation.activate(negotiated)
コード例 #5
0
ファイル: console.py プロジェクト: minimalistduck/trac
def run(args=None):
    """Main entry point."""
    translation.activate(get_console_locale())
    try:
        return _run(args)
    finally:
        translation.deactivate()
コード例 #6
0
ファイル: console.py プロジェクト: timgraham/trac
def run(args=None):
    """Main entry point."""
    if args is None:
        args = sys.argv[1:]
    if has_babel:
        translation.activate(get_console_locale())
    warn_setuptools_issue()
    admin = TracAdmin()
    if len(args) > 0:
        if args[0] in ('-h', '--help', 'help'):
            return admin.onecmd(' '.join(['help'] + args[1:]))
        elif args[0] in ('-v','--version'):
            printout(os.path.basename(sys.argv[0]), TRAC_VERSION)
        else:
            env_path = os.path.abspath(args[0])
            try:
                unicode(env_path, 'ascii')
            except UnicodeDecodeError:
                printerr(_("Non-ascii environment path '%(path)s' not "
                           "supported.", path=to_unicode(env_path)))
                sys.exit(2)
            admin.env_set(env_path)
            if len(args) > 1:
                s_args = ' '.join(["'%s'" % c for c in args[2:]])
                command = args[1] + ' ' + s_args
                return admin.onecmd(command)
            else:
                while True:
                    try:
                        admin.run()
                    except KeyboardInterrupt:
                        admin.do_quit('')
    else:
        return admin.onecmd("help")
コード例 #7
0
ファイル: translation.py プロジェクト: pkdevbox/trac
 def test_activate_unavailable_locale(self):
     unavailables = sorted(set(locale_identifiers()) -
                           set(translation.get_available_locales())) or \
                    ('en_US',)
     locale_dir = self._get_locale_dir()
     translation.add_domain('catalog1', self.env.path, locale_dir)
     translation.add_domain('catalog2', self.env.path, locale_dir)
     translation.activate(unavailables[0], self.env.path)
コード例 #8
0
 def test_activate_unavailable_locale(self):
     unavailables = sorted(set(locale_identifiers()) -
                           set(translation.get_available_locales())) or \
                    ('en_US',)
     locale_dir = self._get_locale_dir()
     translation.add_domain('catalog1', self.env.path, locale_dir)
     translation.add_domain('catalog2', self.env.path, locale_dir)
     translation.activate(unavailables[0], self.env.path)
コード例 #9
0
ファイル: console.py プロジェクト: pkdevbox/trac
 def _init_env(self):
     self.__env = env = Environment(self.envname)
     negotiated = None
     # fixup language according to env settings
     if has_babel:
         negotiated = get_console_locale(env)
         if negotiated:
             translation.activate(negotiated)
コード例 #10
0
ファイル: console.py プロジェクト: t2y/trac
 def _init_env(self):
     self.__env = env = Environment(self.envname)
     negotiated = None
     # fixup language according to env settings
     if has_babel:
         negotiated = get_console_locale(env)
         if negotiated:
             translation.activate(negotiated)
     self.cmd_mgr = AdminCommandManager(env)
コード例 #11
0
    def _sendAllMails(self):
        """Central send logic for sending e-mails"""
        self.log.info( "check mails, language is: %s" % self._locale_string )
        sys_desc = self.get_system_info()
        filterids = self._get_all_relevant_filters()
        
        for filter_id, username in filterids:
            self.log.info ( "[XMail._sendAllMails] -- filter_id: %s -- username: %s" % (filter_id, username) )
            tickets = {}
            subject = "[%s] " % self.env.project_name
            filter = FilterObject(filter_id, self.env)
            
            # retrieve new tickets
            new_tickets = self._get_relevant_tickets('time', filter)

            # retrieve ticket changes
            changed_tickets = self._get_relevant_tickets('time != changetime and changetime', filter)            
            
            if new_tickets:
                for t in new_tickets:
                    tickets[t['id']] = 'new'
            if changed_tickets:
                for t in changed_tickets:
                    if not tickets.has_key(t['id']):
                        tickets[t['id']] = 'changed'
                    else:
                        changed_tickets.remove(t)
            
            if len(tickets) == 0:
                if filter.values['interval'] > 0:
                    self._set_next_exe(filter, self._get_current_time())
                    self.log.debug("[XMail._sendAllMails] no relevant tickets, since length of tickets is %s" % len(tickets))
                # nothing to do, so continue with next filter
                continue
            
            user_data = self._get_user_data(username)
            self.log.debug( "user data: %r -- negotiated: %s" % (user_data, self._locale_string) )
            if not user_data.has_key('language'):
                self.log.debug("got no user-specific language, so using locale %s" % self._locale_string)
                activate(self._locale_string, self.env.path)
            else:
                activate(user_data['language'], self.env.path)
            
            subject += filter.name
            notifyer = XMailTicketNotify(self.env, {'user_data' : user_data, 
                             'new_tickets': new_tickets,
                             'changed_tickets': changed_tickets,
                             'filter': filter,
                             'sys_desc': sys_desc})
            notifyer.notify(resid=None, subject=subject)
            self._set_next_exe(filter, self._get_current_time())
            self.log.info( "[XMail._sendAllMails] -----> sent email with %r tickets by XMailTicketNotify" % len(tickets) )
        return
コード例 #12
0
    def _sendAllMails(self):
        """Central send logic for sending e-mails"""
        self.log.info( "check mails, language is: %s" % self._locale_string )
        sys_desc = self.get_system_info()
        filterids = self._get_all_relevant_filters()
        
        for filter_id, username in filterids:
            self.log.info ( "[XMail._sendAllMails] -- filter_id: %s -- username: %s" % (filter_id, username) )
            tickets = {}
            subject = "[%s] " % self.env.project_name
            filter = FilterObject(filter_id, db=self.env.get_db_cnx())
            
            # retrieve new tickets
            new_tickets = self._get_relevant_tickets('time', filter)

            # retrieve ticket changes
            changed_tickets = self._get_relevant_tickets('time != changetime and changetime', filter)            
            
            if new_tickets:
                for t in new_tickets:
                    tickets[t['id']] = 'new'
            if changed_tickets:
                for t in changed_tickets:
                    if not tickets.has_key(t['id']):
                        tickets[t['id']] = 'changed'
                    else:
                        changed_tickets.remove(t)
            
            if len(tickets) == 0:
                if filter.values['interval'] > 0:
                    self._set_next_exe(filter, self._get_current_time())
                    self.log.debug("[XMail._sendAllMails] no relevant tickets, since length of tickets is %s" % len(tickets))
                # nothing to do, so continue with next filter
                continue
            
            user_data = self._get_user_data(username)
            self.log.debug( "user data: %r -- negotiated: %s" % (user_data, self._locale_string) )
            if not user_data.has_key('language'):
                self.log.debug("got no user-specific language, so using locale %s" % self._locale_string)
                activate(self._locale_string, self.env.path)
            else:
                activate(user_data['language'], self.env.path)
            
            subject += filter.name
            notifyer = XMailTicketNotify(self.env, {'user_data' : user_data, 
                             'new_tickets': new_tickets,
                             'changed_tickets': changed_tickets,
                             'filter': filter,
                             'sys_desc': sys_desc})
            notifyer.notify(resid=None, subject=subject)
            self._set_next_exe(filter, self._get_current_time())
            self.log.info( "[XMail._sendAllMails] -----> sent email with %r tickets by XMailTicketNotify" % len(tickets) )
        return
コード例 #13
0
ファイル: test.py プロジェクト: wiraqutra/photrackjp
    def __init__(self, default_data=False, enable=None):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        """
        ComponentManager.__init__(self)
        Component.__init__(self)
        self.systeminfo = []

        import trac
        self.path = os.path.dirname(trac.__file__)
        if not os.path.isabs(self.path):
            self.path = os.path.join(os.getcwd(), self.path)

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'stderr')
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')

        # -- logging
        from trac.log import logger_handler_factory
        self.log, self._log_handler = logger_handler_factory('test')

        # -- database
        self.dburi = get_dburi()
        if self.dburi.startswith('sqlite'):
            self.config.set('trac', 'database', 'sqlite::memory:')
            self.db = InMemoryDatabase()

        if default_data:
            self.reset_db(default_data)

        from trac.web.href import Href
        self.href = Href('/trac.cgi')
        self.abs_href = Href('http://example.org/trac.cgi')

        self.known_users = []
        translation.activate(Locale and Locale('en', 'US'))
コード例 #14
0
ファイル: test.py プロジェクト: wiraqutra/photrackjp
    def __init__(self, default_data=False, enable=None):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        """
        ComponentManager.__init__(self)
        Component.__init__(self)
        self.systeminfo = []

        import trac
        self.path = os.path.dirname(trac.__file__)
        if not os.path.isabs(self.path):
            self.path = os.path.join(os.getcwd(), self.path)

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'stderr')
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')

        # -- logging
        from trac.log import logger_handler_factory
        self.log, self._log_handler = logger_handler_factory('test')

        # -- database
        self.dburi = get_dburi()
        if self.dburi.startswith('sqlite'):
            self.config.set('trac', 'database', 'sqlite::memory:')
            self.db = InMemoryDatabase()

        if default_data:
            self.reset_db(default_data)

        from trac.web.href import Href
        self.href = Href('/trac.cgi')
        self.abs_href = Href('http://example.org/trac.cgi')

        self.known_users = []
        translation.activate(Locale and Locale('en', 'US'))
コード例 #15
0
    def setup(self, **kwargs):
        """Do the setup. A kwargs dictionary may be passed to override base
        options, potentially allowing for multiple environment creation."""
        
        if has_babel:
            import babel
            try:
                locale = get_negotiated_locale([LANG]) 
                locale = locale or babel.Locale.default()
            except babel.UnknownLocaleError:
                pass
            translation.activate(locale)
        
        options = dict(self.options)
        options.update(kwargs)
        if psycopg2 is None and options.get('dbtype') == 'postgres':
            print "psycopg2 needs to be installed to initialise a postgresql db"
            return False

        environments_path = options['envsdir']
        if not os.path.exists(environments_path):
            os.makedirs(environments_path)

        new_env =  os.path.join(environments_path, options['project'])
        tracini = os.path.abspath(os.path.join(new_env, 'conf', 'trac.ini'))
        baseini = os.path.abspath(os.path.join(new_env, 'conf', 'base.ini'))
        options['inherit'] = baseini

        options['db'] = self._generate_db_str(options)
        if 'repo_type' not in options or options['repo_type'] is None:
            options['repo_type'] = ''
        if 'repo_path' not in options or options['repo_path'] is None:
            options['repo_path'] = ''
        if (len(options['repo_type']) > 0) ^ (len(options['repo_path']) > 0):
            print "Error: Specifying a repository requires both the "\
                  "repository-type and the repository-path options."
            return False

        digestfile = os.path.abspath(os.path.join(new_env,
                                                  options['digestfile']))
        realm =  options['realm']
        adminuser = options['adminuser']
        adminpass = options['adminpass']

        # create base options:
        accounts_config = dict(ACCOUNTS_CONFIG)
        accounts_config['account-manager']['htdigest_file'] = digestfile
        accounts_config['account-manager']['htdigest_realm'] = realm

        trac = TracAdmin(os.path.abspath(new_env))
        if not trac.env_check():
            try:
                trac.do_initenv('%(project)s %(db)s '
                                '%(repo_type)s %(repo_path)s '
                                '--inherit=%(inherit)s '
                                '--nowiki'
                                % options)
            except SystemExit:
                print ("Error: Unable to initialise the database"
                       "Traceback for error is above")
                return False
        else:
            print ("Warning: Environment already exists at %s." % new_env)
            self.writeconfig(tracini, [{'inherit': {'file': baseini},},])

        self.writeconfig(baseini, [BASE_CONFIG, accounts_config])

        if os.path.exists(digestfile):
            backupfile(digestfile)
        htdigest_create(digestfile, adminuser, realm, adminpass)

        print "Adding TRAC_ADMIN permissions to the admin user %s" % adminuser
        trac.onecmd('permission add %s TRAC_ADMIN' % adminuser)

        # get fresh TracAdmin instance (original does not know about base.ini)
        bloodhound = TracAdmin(os.path.abspath(new_env))

        # final upgrade
        print "Running upgrades"
        bloodhound.onecmd('upgrade')
        pages = []
        pages.append(pkg_resources.resource_filename('bhdashboard',
                                                     'default-pages'))
        bloodhound.onecmd('wiki load %s' % " ".join(pages))

        print "Running wiki upgrades"
        bloodhound.onecmd('wiki upgrade')
        
        print "Running wiki bh upgrades"
        bloodhound.onecmd('wiki bh-upgrade')

        print """
You can now start Bloodhound by running:

  tracd --port=8000 %s

And point your browser at http://localhost:8000/%s
""" % (os.path.abspath(new_env), options['project'])
        return True
コード例 #16
0
    def setup(self, **kwargs):
        """Do the setup. A kwargs dictionary may be passed to override base
        options, potentially allowing for multiple environment creation."""

        if has_babel:
            import babel
            try:
                locale = get_negotiated_locale([LANG])
                locale = locale or babel.Locale.default()
            except babel.UnknownLocaleError:
                pass
            translation.activate(locale)

        options = dict(self.options)
        options.update(kwargs)
        if psycopg2 is None and options.get('dbtype') == 'postgres':
            print "psycopg2 needs to be installed to initialise a postgresql db"
            return False
        elif mysqldb is None and options.get('dbtype') == 'mysql':
            print "MySQLdb needs to be installed to initialise a mysql db"
            return False

        environments_path = options['envsdir']
        if not os.path.exists(environments_path):
            os.makedirs(environments_path)

        new_env =  os.path.join(environments_path, options['project'])
        tracini = os.path.abspath(os.path.join(new_env, 'conf', 'trac.ini'))
        baseini = os.path.abspath(os.path.join(new_env, 'conf', 'base.ini'))
        options['inherit'] = '"' + baseini + '"'

        options['db'] = self._generate_db_str(options)
        if 'repo_type' not in options or options['repo_type'] is None:
            options['repo_type'] = ''
        if 'repo_path' not in options or options['repo_path'] is None:
            options['repo_path'] = ''
        if (len(options['repo_type']) > 0) ^ (len(options['repo_path']) > 0):
            print "Error: Specifying a repository requires both the "\
                  "repository-type and the repository-path options."
            return False

        custom_prefix = 'default_product_prefix'
        if custom_prefix in options and options[custom_prefix]:
            default_product_prefix = options[custom_prefix]
        else:
            default_product_prefix = '@'

        digestfile = os.path.abspath(os.path.join(new_env,
                                                  options['digestfile']))
        realm =  options['realm']
        adminuser = options['adminuser']
        adminpass = options['adminpass']

        # create base options:
        accounts_config = dict(ACCOUNTS_CONFIG)
        accounts_config['account-manager']['htdigest_file'] = digestfile
        accounts_config['account-manager']['htdigest_realm'] = realm

        trac = TracAdmin(os.path.abspath(new_env))
        if not trac.env_check():
            try:
                rv = trac.do_initenv('%(project)s %(db)s '
                                     '%(repo_type)s %(repo_path)s '
                                     '--inherit=%(inherit)s '
                                     '--nowiki'
                                     % options)
                if rv == 2:
                    raise SystemExit
            except SystemExit:
                print ("Error: Unable to initialise the environment.")
                return False
        else:
            print ("Warning: Environment already exists at %s." % new_env)
            self.writeconfig(tracini, [{'inherit': {'file': baseini},},])

        base_config = dict(BASE_CONFIG)
        base_config['trac']['environment_factory'] = \
            'multiproduct.hooks.MultiProductEnvironmentFactory'
        base_config['trac']['request_factory'] = \
            'multiproduct.hooks.ProductRequestFactory'
        if default_product_prefix != '@':
            base_config['multiproduct'] = dict(
                default_product_prefix=default_product_prefix
            )

        self.writeconfig(baseini, [base_config, accounts_config])

        if os.path.exists(digestfile):
            backupfile(digestfile)
        htdigest_create(digestfile, adminuser, realm, adminpass)

        print "Adding TRAC_ADMIN permissions to the admin user %s" % adminuser
        trac.onecmd('permission add %s TRAC_ADMIN' % adminuser)

        # get fresh TracAdmin instance (original does not know about base.ini)
        bloodhound = TracAdmin(os.path.abspath(new_env))

        # final upgrade
        print "Running upgrades"
        bloodhound.onecmd('upgrade')
        pages = []
        pages.append(pkg_resources.resource_filename('bhdashboard',
                                                 'default-pages'))
        pages.append(pkg_resources.resource_filename('bhsearch',
                                                 'default-pages'))
        bloodhound.onecmd('wiki load %s' % " ".join(pages))

        print "Running wiki upgrades"
        bloodhound.onecmd('wiki upgrade')

        if self.apply_bhwiki_upgrades:
            print "Running wiki Bloodhound upgrades"
            bloodhound.onecmd('wiki bh-upgrade')
        else:
            print "Skipping Bloodhound wiki upgrades"

        print "Loading default product wiki"
        bloodhound.onecmd('product admin %s wiki load %s' %
                          (default_product_prefix,
                           " ".join(pages)))

        print "Running default product wiki upgrades"
        bloodhound.onecmd('product admin %s wiki upgrade' %
                          default_product_prefix)

        if self.apply_bhwiki_upgrades:
            print "Running default product Bloodhound wiki upgrades"
            bloodhound.onecmd('product admin %s wiki bh-upgrade' %
                              default_product_prefix)
        else:
            print "Skipping default product Bloodhound wiki upgrades"

        print """
You can now start Bloodhound by running:

  tracd --port=8000 %s

And point your browser at http://localhost:8000/%s
""" % (os.path.abspath(new_env), options['project'])
        return True
コード例 #17
0
 def test_activate(self):
     locales = self._get_available_locales()
     if locales:
         translation.activate(locales[0], self.env.path)
コード例 #18
0
ファイル: test.py プロジェクト: exocad/exotrac
    def __init__(self, default_data=False, enable=None, disable=None,
                 path=None, destroying=False):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        :param disable: A list of component classes or name globs to
                        deactivate in the stub environment.
        :param path: The location of the environment in the file system.
                     No files or directories are created when specifying
                     this parameter.
        :param destroying: If True, the database will not be reset. This is
                           useful for cases when the object is being
                           constructed in order to call `destroy_db`.
        """
        if enable is not None and not isinstance(enable, (list, tuple)):
            raise TypeError('Keyword argument "enable" must be a list')
        if disable is not None and not isinstance(disable, (list, tuple)):
            raise TypeError('Keyword argument "disable" must be a list')

        ComponentManager.__init__(self)

        self.systeminfo = []

        import trac
        self.path = path
        if self.path is None:
            self.path = os.path.dirname(trac.__file__)
            if not os.path.isabs(self.path):
                self.path = os.path.join(os.getcwd(), self.path)

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'stderr')
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        else:
            self.config.set('components', 'tracopt.versioncontrol.*',
                            'enabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')
        for name_or_class in disable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'disabled')

        # -- logging
        from trac.log import logger_handler_factory
        self.log, self._log_handler = logger_handler_factory('test')

        # -- database
        self.config.set('components', 'trac.db.*', 'enabled')
        self.dburi = get_dburi()

        init_global = False
        if self.global_databasemanager:
            self.components[DatabaseManager] = self.global_databasemanager
        else:
            self.config.set('trac', 'database', self.dburi)
            self.global_databasemanager = DatabaseManager(self)
            self.config.set('trac', 'debug_sql', True)
            init_global = not destroying

        if default_data or init_global:
            self.reset_db(default_data)

        self.config.set('trac', 'base_url', 'http://example.org/trac.cgi')

        self.known_users = []
        translation.activate(locale_en)
コード例 #19
0
ファイル: translation.py プロジェクト: pkdevbox/trac
 def test_activate(self):
     locales = self._get_available_locales()
     if locales:
         translation.activate(locales[0], self.env.path)
コード例 #20
0
ファイル: test.py プロジェクト: khoi-huynh/trac
    def __init__(self, default_data=False, enable=None, disable=None,
                 path=None, destroying=False):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        :param disable: A list of component classes or name globs to
                        deactivate in the stub environment.
        :param path: The location of the environment in the file system.
                     No files or directories are created when specifying
                     this parameter.
        :param destroying: If True, the database will not be reset. This is
                           useful for cases when the object is being
                           constructed in order to call `destroy_db`.
        """
        if enable is not None and not isinstance(enable, (list, tuple)):
            raise TypeError('Keyword argument "enable" must be a list')
        if disable is not None and not isinstance(disable, (list, tuple)):
            raise TypeError('Keyword argument "disable" must be a list')

        ComponentManager.__init__(self)

        self._old_registry = None
        self._old_components = None

        import trac
        self.path = path
        if self.path is None:
            self.path = os.path.abspath(os.path.dirname(trac.__file__))
        self.path = os.path.normpath(os.path.normcase(self.path))

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'none')  # Ignored.
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        else:
            self.config.set('components', 'tracopt.versioncontrol.*',
                            'enabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')
        for name_or_class in disable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'disabled')
        self.config.set('trac', 'permission_policies',
                        'DefaultPermissionPolicy, LegacyAttachmentPolicy')

        # -- logging
        self.log = logging.getLogger('trac.test')
        level = self.log_level.upper()
        level_as_int = trac.log.LOG_LEVEL_MAP.get(level)
        self.log.setLevel(level_as_int)
        handler_cls = logging.handlers.BufferingHandler
        if not self.log.handlers:
            log_handler = handler_cls(sys.maxsize)  # Never flush implicitly.
            formatter = logging.Formatter(self.log_format)
            log_handler.setFormatter(formatter)
            self.log.addHandler(log_handler)
        elif len(self.log.handlers) == 1 and \
                isinstance(self.log.handlers[0], handler_cls):
            self.log.handlers[0].flush()  # Reset buffer.
        else:
            raise TracError("Logger has unexpected handler(s).")

        # -- database
        self.dburi = get_dburi()
        self.config.set('components', 'trac.db.*', 'enabled')
        self.config.set('trac', 'database', self.dburi)

        if not destroying:
            self.reset_db(default_data)

        self.config.set('trac', 'base_url', 'http://example.org/trac.cgi')

        translation.activate(locale_en)
コード例 #21
0
    def __init__(self,
                 default_data=False,
                 enable=None,
                 disable=None,
                 path=None,
                 destroying=False):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        :param disable: A list of component classes or name globs to
                        deactivate in the stub environment.
        :param path: The location of the environment in the file system.
                     No files or directories are created when specifying
                     this parameter.
        :param destroying: If True, the database will not be reset. This is
                           useful for cases when the object is being
                           constructed in order to call `destroy_db`.
        """
        if enable is not None and not isinstance(enable, (list, tuple)):
            raise TypeError('Keyword argument "enable" must be a list')
        if disable is not None and not isinstance(disable, (list, tuple)):
            raise TypeError('Keyword argument "disable" must be a list')

        ComponentManager.__init__(self)
        Component.__init__(self)

        self.systeminfo = []

        import trac
        self.path = path
        if self.path is None:
            self.path = os.path.dirname(trac.__file__)
            if not os.path.isabs(self.path):
                self.path = os.path.join(os.getcwd(), self.path)

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'stderr')
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        else:
            self.config.set('components', 'tracopt.versioncontrol.*',
                            'enabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')
        for name_or_class in disable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'disabled')

        # -- logging
        from trac.log import logger_handler_factory
        self.log, self._log_handler = logger_handler_factory('test')

        # -- database
        self.config.set('components', 'trac.db.*', 'enabled')
        self.dburi = get_dburi()

        init_global = False
        if self.global_databasemanager:
            self.components[DatabaseManager] = self.global_databasemanager
        else:
            self.config.set('trac', 'database', self.dburi)
            self.global_databasemanager = DatabaseManager(self)
            self.config.set('trac', 'debug_sql', True)
            self.config.set('logging', 'log_type', 'stderr')
            self.config.set('logging', 'log_level', 'DEBUG')
            init_global = not destroying

        if default_data or init_global:
            self.reset_db(default_data)

        from trac.web.href import Href
        self.href = Href('/trac.cgi')
        self.abs_href = Href('http://example.org/trac.cgi')

        self.known_users = []
        translation.activate(locale_en)
コード例 #22
0
    def __init__(self,
                 default_data=False,
                 enable=None,
                 disable=None,
                 path=None,
                 destroying=False,
                 config=None):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        :param disable: A list of component classes or name globs to
                        deactivate in the stub environment.
        :param path: The location of the environment in the file system.
                     No files or directories are created when specifying
                     this parameter.
        :param destroying: If True, the database will not be reset. This is
                           useful for cases when the object is being
                           constructed in order to call `destroy_db`.
        :param config: A list of (section, key, value) configuration
                       tuples.
        """
        if enable is not None and not isinstance(enable, (list, tuple)):
            raise TypeError('Keyword argument "enable" must be a list')
        if disable is not None and not isinstance(disable, (list, tuple)):
            raise TypeError('Keyword argument "disable" must be a list')

        ComponentManager.__init__(self)

        self._old_registry = None
        self._old_components = None

        import trac
        self.path = path
        if self.path is None:
            self.path = os.path.abspath(os.path.dirname(trac.__file__))
        self.path = os.path.normpath(os.path.normcase(self.path))

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, 'basic-workflow.ini')
        self.config.set('logging', 'log_level', 'DEBUG')
        self.config.set('logging', 'log_type', 'none')  # Ignored.
        if enable is not None:
            self.config.set('components', 'trac.*', 'disabled')
        else:
            self.config.set('components', 'tracopt.versioncontrol.*',
                            'enabled')
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'enabled')
        for name_or_class in disable or ():
            config_key = self._component_name(name_or_class)
            self.config.set('components', config_key, 'disabled')
        self.config.set('trac', 'permission_policies',
                        'DefaultPermissionPolicy, LegacyAttachmentPolicy')
        for item in config or []:
            self.config.set(*item)

        # -- logging
        self.setup_log()

        # -- database
        self.dburi = get_dburi()
        self.config.set('components', 'trac.db.*', 'enabled')
        self.config.set('trac', 'database', self.dburi)

        if not destroying:
            self.reset_db(default_data)

        self.config.set('trac', 'base_url', 'http://example.org/trac.cgi')

        translation.activate(locale_en)
コード例 #23
0
ファイル: test.py プロジェクト: dafrito/trac-mirror
    def __init__(self, default_data=False, enable=None, disable=None, path=None, destroying=False):
        """Construct a new Environment stub object.

        :param default_data: If True, populate the database with some
                             defaults.
        :param enable: A list of component classes or name globs to
                       activate in the stub environment.
        """
        ComponentManager.__init__(self)
        Component.__init__(self)

        self.systeminfo = []

        import trac

        self.path = path
        if self.path is None:
            self.path = os.path.dirname(trac.__file__)
            if not os.path.isabs(self.path):
                self.path = os.path.join(os.getcwd(), self.path)

        # -- configuration
        self.config = Configuration(None)
        # We have to have a ticket-workflow config for ''lots'' of things to
        # work.  So insert the basic-workflow config here.  There may be a
        # better solution than this.
        load_workflow_config_snippet(self.config, "basic-workflow.ini")
        self.config.set("logging", "log_level", "DEBUG")
        self.config.set("logging", "log_type", "stderr")
        if enable is not None:
            self.config.set("components", "trac.*", "disabled")
        else:
            self.config.set("components", "tracopt.versioncontrol.*", "enabled")
        for name_or_class in enable or ():
            config_key = self._component_name(name_or_class)
            self.config.set("components", config_key, "enabled")
        for name_or_class in disable or ():
            config_key = self._component_name(name_or_class)
            self.config.set("components", config_key, "disabled")

        # -- logging
        from trac.log import logger_handler_factory

        self.log, self._log_handler = logger_handler_factory("test")

        # -- database
        self.config.set("components", "trac.db.*", "enabled")
        self.dburi = get_dburi()

        init_global = False
        if self.global_databasemanager:
            self.components[DatabaseManager] = global_databasemanager
        else:
            self.config.set("trac", "database", self.dburi)
            self.global_databasemanager = DatabaseManager(self)
            self.config.set("trac", "debug_sql", True)
            self.config.set("logging", "log_type", "stderr")
            self.config.set("logging", "log_level", "DEBUG")
            init_global = not destroying

        if default_data or init_global:
            self.reset_db(default_data)

        from trac.web.href import Href

        self.href = Href("/trac.cgi")
        self.abs_href = Href("http://example.org/trac.cgi")

        self.known_users = []
        translation.activate(locale_en)