예제 #1
0
def test_already_implmeneted_error():
    with pytest.raises(NotImplementedError):
        get_utility(IBanana)

    provide_utility(IBanana, o)

    with pytest.raises(AlreadyImplementedError):
        provide_utility(IBanana, o)
예제 #2
0
def test_provide_utility():
    with pytest.raises(NotImplementedError):
        get_utility(IBanana)

    provide_utility(IBanana, o)

    with pytest.raises(TypeError):
        provide_utility(object, o)
예제 #3
0
def test_get_utility():
    assert get_utility(IBanana, None) is None

    provide_utility(IBanana, o)
    with pytest.raises(TypeError):
        get_utility(object)

    assert get_utility(IBanana, o)
예제 #4
0
 def _set_admin_password(self, store):
     logger.info('_set_admin_password')
     adminuser = store.find(LoginUser,
                            username=USER_ADMIN_DEFAULT_NAME).one()
     if adminuser is None:
         raise DatabaseInconsistency(
             ("You should have a user with username: %s" %
              USER_ADMIN_DEFAULT_NAME))
     # Lets create a user without password and set a cookie so that it
     # auto login
     adminuser.set_password(u'')
     get_utility(ICookieFile).store('admin', '')
예제 #5
0
 def _idle_logout(self):
     # Before performing logout, verify that the currently opened window
     # is modal.
     from stoqlib.lib.component import get_utility
     from stoq.lib.gui.base.dialogs import has_modal_window
     from stoqlib.lib.interfaces import ICookieFile
     # If not a modal window, logout.
     # Otherwise returns True to continue checking the automatic logout.
     if not has_modal_window():
         log.debug('Automatic logout')
         get_utility(ICookieFile).clear()
         self.quit(restart=True)
     return True
예제 #6
0
    def _run_about(self):
        info = get_utility(IAppInfo)
        about = Gtk.AboutDialog()
        about.set_name(info.get("name"))
        about.set_version(info.get("version"))
        about.set_website(stoq.website)
        release_date = stoq.release_date
        about.set_comments(
            _('Release date: %s') %
            datetime.datetime(*release_date).strftime('%x'))
        about.set_copyright('Copyright (C) 2005-2012 Async Open Source')

        about.set_logo(render_logo_pixbuf('about'))

        # License

        if locale.getlocale()[0] == 'pt_BR':
            filename = 'COPYING.pt_BR'
        else:
            filename = 'COPYING'
        data = self._read_resource('docs', filename)
        about.set_license(data)

        # Authors & Contributors
        data = self._read_resource('docs', 'AUTHORS')
        lines = data.split('\n')
        lines.append('')  # separate authors from contributors
        data = self._read_resource('docs', 'CONTRIBUTORS')
        lines.extend([c.strip() for c in data.split('\n')])
        about.set_authors(lines)

        about.set_transient_for(get_current_toplevel())
        about.run()
        about.destroy()
예제 #7
0
    def cookie_login(self):
        if api.sysparam.get_bool('DISABLE_COOKIES'):
            log.info("Cookies disable by parameter")
            return

        cookie_file = get_utility(ICookieFile)
        try:
            username, password = cookie_file.get()
        except CookieError:
            log.info("Not using cookie based login")
            return

        def is_md5(password):
            # This breaks for passwords that are 32 characters long,
            # uses only digits and lowercase a-f, pretty unlikely as
            # real-world password
            if len(password) != 32:
                return False
            for c in '1234567890abcdef':
                password = password.replace(c, '')
            return password == ''

        # Migrate old passwords to md5 hashes.
        if not is_md5(password):
            password = LoginUser.hash(password)
            cookie_file.store(username, password)

        try:
            user = self._check_user(username, password)
        except (LoginError, UserProfileError, DatabaseError) as e:
            log.info("Cookie login failed: %r" % e)
            return

        log.info("Logging in using cookie credentials")
        return user
예제 #8
0
def test_zope_interface():
    try:
        from zope.interface import Interface
    except ImportError:
        return

    class IApple(Interface):
        pass

    with pytest.raises(NotImplementedError):
        get_utility(IApple)

    provide_utility(IApple, o)

    with pytest.raises(AlreadyImplementedError):
        provide_utility(IApple, o)
예제 #9
0
    def _create_dialog(self):
        app_info = get_utility(IAppInfo, None)

        self._dialog = HIGAlertDialog(parent=self._parent,
                                      flags=Gtk.DialogFlags.MODAL,
                                      type=Gtk.MessageType.WARNING)

        self._dialog.set_details_label(_("Details ..."))
        self._dialog.set_resizable(True)
        primary_fmt = _(
            'We\'r sorry to inform you that an error occurred while '
            'running %s. Please help us improving Stoq by sending a '
            'automatically generated report about the incident.\n'
            'Click on details to see the report text.')
        self._dialog.set_primary(primary_fmt % (app_info.get('name'), ),
                                 bold=False)

        self._create_details()
        self._create_comments()
        self._create_email()

        self._no_button = self._dialog.add_button(_('No thanks'),
                                                  Gtk.ResponseType.NO)
        self._yes_button = self._dialog.add_button(_('Send report'),
                                                   Gtk.ResponseType.YES)

        self._insert_tracebacks()
예제 #10
0
    def get_permission_manager(cls):
        """Returns the payment operation manager"""
        pm = get_utility(IPermissionManager, None)

        if not pm:
            pm = PermissionManager()
            provide_utility(IPermissionManager, pm)
        return pm
예제 #11
0
    def _get_headers(self):
        user_agent = 'Stoq'
        app_info = get_utility(IAppInfo, None)
        if app_info:
            user_agent += ' %s' % (app_info.get('version'), )
        headers = {'User-Agent': user_agent}

        return headers
예제 #12
0
 def create_profile_template(cls, store, name,
                             has_full_permission=False):
     profile = cls(store=store, name=name)
     descr = get_utility(IApplicationDescriptions)
     for app_dir in descr.get_application_names():
         ProfileSettings(store=store,
                         has_permission=has_full_permission,
                         app_dir_name=app_dir, user_profile=profile)
     return profile
예제 #13
0
    def _add_registers(self):
        appinfo = get_utility(IAppInfo)
        self.cat.add_software_house(company, appinfo.get('name'),
                                    appinfo.get('version'))

        self._add_ecf_identification()
        self._add_z_reduction_information()
        self._add_fiscal_coupon_information()
        self._add_other_documents()
예제 #14
0
def get_payment_operation_manager():
    """Returns the payment operation manager"""
    pmm = get_utility(IPaymentOperationManager, None)

    if not pmm:
        from stoqlib.lib.payment import PaymentOperationManager
        pmm = PaymentOperationManager()
        provide_utility(IPaymentOperationManager, pmm)

    return pmm
예제 #15
0
 def _get_label(self):
     info = get_utility(IAppInfo, None)
     if not info:
         return "Stoq"
     version = info.get("version")
     if ' ' in version:
         ver, rev = version.split(' ')
         version = '%s\n<span font="8">%s</span>' % (
             ver, GLib.markup_escape_text(rev))
     return _("Version %s") % (version, )
예제 #16
0
def get_current_station(store=None):
    """Fetches the current station (computer) which we are running on

    :param store: a store
    :param: current station
    :rtype: BranchStation or ``None``
    """
    station = get_utility(ICurrentBranchStation, None)
    if station is not None and store is not None:
        return store.fetch(station)
    return station
예제 #17
0
def get_current_branch(store=None):
    """Fetches the current branch company.

    :param store: a store
    :returns: the current branch
    :rtype: a branch or ``None``
    """

    branch = get_utility(ICurrentBranch, None)
    if branch is not None and store is not None:
        return store.fetch(branch)
    return branch
예제 #18
0
def update_profile_applications(store, profile=None):
    """This method checks for all available applications and perform a
    comparision with the application names stored in user profiles. If a
    certain application is not there it is added.
    """
    app_list = get_utility(IApplicationDescriptions).get_application_names()
    profiles = profile and [profile] or store.find(UserProfile)
    for app_name in app_list:
        for profile in profiles:
            settings = profile.profile_settings
            app_names = [s.app_dir_name for s in settings]
            if not app_name in app_names:
                profile.add_application_reference(app_name)
예제 #19
0
def get_category_label(name):
    if name.startswith('app.common'):
        return _("General")
    elif name.startswith('app'):
        app_name = name.split('.', 2)[1]
        app_list = get_utility(IApplicationDescriptions)
        for item in app_list.get_descriptions():
            if item[0] == app_name:
                return item[1]  # the label

    elif name.startswith('plugin'):
        return _('%s plugin') % (name.split('.', 2)[1], )
    else:
        raise AssertionError(name)
예제 #20
0
def get_current_user(store):
    """Fetch the user which is currently logged into the system or None
    None means that there are no utilities available which in turn
    should only happens during startup, for example when creating
    a new database or running the migration script,
    at that point no users are logged in

    :param store: a store
    :returns: currently logged in user or None
    :rtype: a LoginUser or ``None``
    """
    user = get_utility(ICurrentUser, None)
    if user is not None:
        return store.fetch(user)
예제 #21
0
def get_plugin_manager():
    """Provides and returns the plugin manager

    @attention: Try to always use this instead of getting the utillity
        by hand, as that could not have been provided before.

    :returns: an :class:`PluginManager` instance
    """
    manager = get_utility(IPluginManager, None)
    if not manager:
        manager = PluginManager()
        provide_utility(IPluginManager, manager)

    return manager
예제 #22
0
    def _setup_application_name(self):
        """Sets a friendly name for postgres connection

        This name will appear when selecting from pg_stat_activity, for instance,
        and will allow to better debug the queries (specially when there is a deadlock)
        """
        try:
            appinfo = get_utility(IAppInfo)
        except Exception:
            appname = 'stoq'
        else:
            appname = appinfo.get('name') or 'stoq'

        self.execute("SET application_name = '%s - %s - %s'" %
                     ((appname.lower(), get_hostname(), os.getpid())))
예제 #23
0
    def get_available_applications(self):
        user = api.get_current_user(self.store)

        permissions = user.profile.get_permissions()
        descriptions = get_utility(IApplicationDescriptions).get_descriptions()

        available_applications = []

        # sorting by app_full_name
        for name, full, icon, descr in locale_sorted(
                descriptions, key=operator.itemgetter(1)):
            if permissions.get(name):
                available_applications.append(
                    Application(name, full, icon, descr))
        return available_applications
예제 #24
0
    def setup_slaves(self):
        settings = {}
        for setting in self.model.profile_settings:
            settings[setting.app_dir_name] = setting

        apps = get_utility(IApplicationDescriptions)
        for name, full_name, icon_name, description in apps.get_descriptions():
            # Virtual apps should not be selected here
            if name in ProfileSettings.virtual_apps:
                continue

            # Create the user interface for each application which is
            # a HBox, a CheckButton and an Image
            box = Gtk.HBox()
            box.show()

            button = ProxyCheckButton()
            button.set_label(full_name)
            button.data_type = bool
            button.model_attribute = 'has_permission'
            button.show()
            box.pack_start(button, True, True, 6)

            image = Gtk.Image.new_from_stock(icon_name, Gtk.IconSize.MENU)
            box.pack_start(image, False, False, 0)
            image.show()

            self.applications_vbox.pack_start(box, False, True, 0)

            model = settings.get(name)
            if model is None:
                model = ProfileSettings(store=self.store,
                                        has_permission=False,
                                        app_dir_name=name,
                                        user_profile=self.model)

            setattr(self, name, button)
            self.add_proxy(model, [name])

        # Scroll to the bottom of the scrolled window
        vadj = self.scrolled_window.get_vadjustment()
        vadj.set_value(vadj.get_upper())
예제 #25
0
 def _set_method_slave(self):
     """Sets the payment method slave"""
     method = self._ms.get_selected_method()
     if not method:
         return
     domain_mapper = get_utility(IDomainSlaveMapper)
     slave_class = domain_mapper.get_slave_class(method)
     if slave_class:
         self.wizard.payment_group = self.model
         self.slave = slave_class(
             self.wizard,
             self,
             self.store,
             self.parent,
             method,
             outstanding_value=self.outstanding_value,
             first_duedate=self._first_duedate,
             installments_number=self._installments_number,
             temporary_identifiers=self.wizard.is_for_another_branch())
         self.attach_slave('method_slave_holder', self.slave)
예제 #26
0
 def _create_slave(self, method):
     dsm = get_utility(IDomainSlaveMapper)
     slave_class = dsm.get_slave_class(method)
     assert slave_class
     method = self.store.fetch(method)
     if slave_class is MultipleMethodSlave:
         slave = slave_class(self.wizard,
                             self,
                             self.store,
                             self.model,
                             method,
                             outstanding_value=self._outstanding_value,
                             finish_on_total=self._finish_on_total,
                             allow_remove_paid=False)
     else:
         slave = slave_class(self.wizard,
                             self,
                             self.store,
                             self.model,
                             method,
                             outstanding_value=self._outstanding_value)
     self._method_slave = slave
     return slave
예제 #27
0
    def setUp(self):
        self._mocks = []

        self._iappinfo = get_utility(IAppInfo)
        # Shell will provide this utility
        remove_utility(IAppInfo)

        # If the locale is changed here, gui tests will break
        mocked = mock.patch.dict(get_settings()._root, clear=True)
        self._mocks.append(mocked)

        # Do not show the splash screen during the tests
        mocked = mock.patch('stoq.lib.gui.widgets.splash.show_splash',
                            new=lambda: None)
        self._mocks.append(mocked)

        # If a dependency is missing, avoid showing an error message
        # or else jenkins will hang
        mocked = mock.patch('stoq.lib.dependencies.DependencyChecker._error',
                            new=lambda *args, **kwargs: None)
        self._mocks.append(mocked)

        for mocked in self._mocks:
            mocked.start()
예제 #28
0
def yesno(text, default=-1, *verbs):
    sn = get_utility(ISystemNotifier)
    rv = sn.yesno(text, default, *verbs)
    log.info("Yes/No: text='%s' verbs='%r' rv='%r'" % (text, verbs, rv))
    return rv
예제 #29
0
def error(short, description=None):
    sn = get_utility(ISystemNotifier)
    log.info("Error: short='%s' description='%s'" % (short, description))
    sn.error(short, description)
    sys.exit(1)
예제 #30
0
def warning(short, description=None, *args, **kwargs):
    sn = get_utility(ISystemNotifier)
    log.info("Warning: short='%s' description='%s'" % (short, description))
    return sn.warning(short, description, *args, **kwargs)