Ejemplo n.º 1
0
    def test_edit_settings_errors(self):
        client = self.login(TEST_USERNAME)

        for key, values in WRONG_SETTINGS.items():
            old_value = getattr(settings, key)

            for value in values:
                data = copy.deepcopy(TEST_SETTINGS)
                data.update({key: value})

                response = client.post(self.edit_settings_url, data)
                self.assertContains(
                    response,
                    'Settings cannot be saved cause of validation issues. ' \
                    'Check for errors below.'
                )
                self.assertContains(response, '<dd class="errors">')

                settings._backend.clear()

                if is_settings_container(old_value):
                    new_value = getattr(settings, key)
                    self.assertTrue(is_settings_container(new_value))
                    self.assertEqual(old_value._prefix, new_value._prefix)
                else:
                    self.assertEqual(getattr(settings, key), old_value)
Ejemplo n.º 2
0
def get_config(name, default=None):
    """
    Helper function to easy fetch ``name`` from database or django settings and
    return ``default`` value if setting key isn't found.

    But if not ``default`` value is provided (``None``) the ``AttributeError``
    exception can raised if setting key isn't found.

    If ``name`` is one of available ``app_name`` function raises
    ``ValueError`` cause cannot to returns config value.

    For fetching app setting use next definition:
    ``<app_name>.<setting_name>``.
    """
    app_name = None

    if '.' in name:
        app_name, name = name.split('.', 1)

    values = getattr(settings, app_name) if app_name else settings

    if default is not None:
        result = getattr(values, name) if hasattr(values, name) else default
    else:
        result = getattr(values, name)

    if is_settings_container(result):
        raise ValueError('%r is settings container, not setting.' % name)

    return result
Ejemplo n.º 3
0
def view_settings():
    """
    View all available configuration definition files.
    """
    path = settings.available_settings.path

    handler = open(path, 'rb')
    project_settings_content = handler.read()
    handler.close()

    apps_settings_contents = OrderedDict()

    for setting in settings.available_settings:
        if is_settings_container(setting):
            handler = open(setting.path, 'rb')
            apps_settings_contents[setting.app_name] = handler.read()
            handler.close()

    filename = app.config.get('SETMAN_DEFAULT_VALUES_FILE', None)

    if filename:
        handler = open(filename, 'rb')
        default_values_content = handler.read()
        handler.close()
    else:
        default_values_content = None

    context = {'apps_settings_contents': apps_settings_contents,
               'default_values_content': default_values_content,
               'project_settings_content': project_settings_content}
    return render_template('view_settings.html', **context)
Ejemplo n.º 4
0
def main(available_settings=None):
    available_settings = available_settings or settings.available_settings
    app_name = available_settings.app_name

    if not app_name:
        print('Found %d available setting(s)' % len(available_settings))

    for mixed in available_settings:
        if is_settings_container(mixed):
            main(mixed)
        else:
            setting = mixed
            values = getattr(settings, app_name) if app_name else settings
            old_value = getattr(values, setting.name)

            print('\n%s (%s)' % (setting.label, setting.help_text))
            new_value = raw_input('Enter new value, old value is %r: ' % \
                                  old_value)

            if not new_value:
                new_value = old_value

            setattr(values, setting.name, new_value)

    if not available_settings.app_name:
        if settings.is_valid():
            settings.save()
            print('\nSettings were saved! Exit...')
        else:
            print('\nCannot save settings, error:\n%s' % settings.error)
Ejemplo n.º 5
0
def view_settings(request):
    """
    View Configuration Definition File for Test Project.

    Only logged in users can have access to this page.
    """
    path = settings.available_settings.path

    handler = open(path, 'rb')
    project_settings_content = handler.read()
    handler.close()

    apps_settings_contents = SortedDict()

    for setting in settings.available_settings:
        if is_settings_container(setting):
            handler = open(setting.path, 'rb')
            apps_settings_contents[setting.app_name] = handler.read()
            handler.close()

    filename = getattr(django_settings, 'SETMAN_DEFAULT_VALUES_FILE', None)

    if filename:
        handler = open(filename, 'rb')
        default_values_content = handler.read()
        handler.close()
    else:
        default_values_content = None

    context = {
        'apps_settings_contents': apps_settings_contents,
        'default_values_content': default_values_content,
        'project_settings_content': project_settings_content
    }
    return render(request, 'view_settings.html', context)
Ejemplo n.º 6
0
def main(available_settings=None):
    available_settings = available_settings or settings.available_settings
    app_name = available_settings.app_name

    if not app_name:
        print('Found %d available setting(s)' % len(available_settings))

    for mixed in available_settings:
        if is_settings_container(mixed):
            main(mixed)
        else:
            setting = mixed
            values = getattr(settings, app_name) if app_name else settings
            old_value = getattr(values, setting.name)

            print('\n%s (%s)' % (setting.label, setting.help_text))
            new_value = raw_input('Enter new value, old value is %r: ' % \
                                  old_value)

            if not new_value:
                new_value = old_value

            setattr(values, setting.name, new_value)

    if not available_settings.app_name:
        if settings.is_valid():
            settings.save()
            print('\nSettings were saved! Exit...')
        else:
            print('\nCannot save settings, error:\n%s' % settings.error)
Ejemplo n.º 7
0
def view_settings():
    """
    View all available configuration definition files.
    """
    path = settings.available_settings.path

    handler = open(path, 'rb')
    project_settings_content = handler.read()
    handler.close()

    apps_settings_contents = OrderedDict()

    for setting in settings.available_settings:
        if is_settings_container(setting):
            handler = open(setting.path, 'rb')
            apps_settings_contents[setting.app_name] = handler.read()
            handler.close()

    filename = app.config.get('SETMAN_DEFAULT_VALUES_FILE', None)

    if filename:
        handler = open(filename, 'rb')
        default_values_content = handler.read()
        handler.close()
    else:
        default_values_content = None

    context = {
        'apps_settings_contents': apps_settings_contents,
        'default_values_content': default_values_content,
        'project_settings_content': project_settings_content
    }
    return render_template('view_settings.html', **context)
Ejemplo n.º 8
0
def view_settings(request):
    """
    View Configuration Definition File for Test Project.

    Only logged in users can have access to this page.
    """
    path = settings.available_settings.path

    handler = open(path, 'rb')
    project_settings_content = handler.read()
    handler.close()

    apps_settings_contents = SortedDict()

    for setting in settings.available_settings:
        if is_settings_container(setting):
            handler = open(setting.path, 'rb')
            apps_settings_contents[setting.app_name] = handler.read()
            handler.close()

    filename = getattr(django_settings, 'SETMAN_DEFAULT_VALUES_FILE', None)

    if filename:
        handler = open(filename, 'rb')
        default_values_content = handler.read()
        handler.close()
    else:
        default_values_content = None

    context = {'apps_settings_contents': apps_settings_contents,
               'default_values_content': default_values_content,
               'project_settings_content': project_settings_content}
    return render(request, 'view_settings.html', context)
Ejemplo n.º 9
0
    def check_setman(self, verbosity):
        """
        Check setman configuration.
        """
        if verbosity:
            print >> self.stdout, 'Project settings:'
            print >> self.stdout, 'Configuration definition file placed at ' \
                                  '%r\n' % AVAILABLE_SETTINGS.path

            for setting in AVAILABLE_SETTINGS:
                indent = ' ' * 4

                if is_settings_container(setting):
                    print >> self.stdout, '%s%r settings:' % \
                                          (indent, setting.app_name)
                    print >> self.stdout, '%sConfiguration definition file ' \
                                          'placed at %r' % \
                                          (indent, setting.path)
                    indent *= 2

                    for subsetting in setting:
                        print >> self.stdout, '%s%r' % (indent, subsetting)

                    print >> self.stdout
                else:
                    print >> self.stdout, '%s%r' % (indent, setting)

            print >> self.stdout, ''
Ejemplo n.º 10
0
def get_config(name, default=None):
    """
    Helper function to easy fetch ``name`` from database or django settings and
    return ``default`` value if setting key isn't found.

    But if not ``default`` value is provided (``None``) the ``AttributeError``
    exception can raised if setting key isn't found.

    If ``name`` is one of available ``app_name`` function raises
    ``ValueError`` cause cannot to returns config value.

    For fetching app setting use next definition:
    ``<app_name>.<setting_name>``.
    """
    app_name = None

    if '.' in name:
        app_name, name = name.split('.', 1)

    values = getattr(settings, app_name) if app_name else settings

    if default is not None:
        result = getattr(values, name) if hasattr(values, name) else default
    else:
        result = getattr(values, name)

    if is_settings_container(result):
        raise ValueError('%r is settings container, not setting.' % name)

    return result
Ejemplo n.º 11
0
    def check_values(self, settings, data):
        for name, value in data.items():
            mixed = getattr(settings, name)

            if is_settings_container(mixed):
                self.check_values(mixed, data.get(name))
            else:
                self.assertEqual(mixed, value)
Ejemplo n.º 12
0
    def check_labels(self, response, available_settings=None):
        available_settings = available_settings or settings.available_settings

        for setting in available_settings:
            if is_settings_container(setting):
                self.check_labels(response, setting)
            else:
                self.assertContains(response, setting.label)
                self.assertContains(response, setting.help_text)
Ejemplo n.º 13
0
        def check_values(prefix=None):
            data = TEST_SETTINGS[prefix] if prefix else TEST_SETTINGS
            values = getattr(settings, prefix) if prefix else settings

            for name, value in data.items():
                mixed = getattr(values, name)

                if is_settings_container(mixed):
                    check_values(name)
                else:
                    self.assertEqual(mixed, value)
Ejemplo n.º 14
0
    def test_app_settings(self):
        self.assertRaises(SettingDoesNotExist, getattr, settings, 'auth')

        self.assertTrue(hasattr(settings, 'testapp'))
        self.assertTrue(is_settings_container(settings.testapp))
        self.assertEqual(settings.testapp.app_setting, None)
        self.assertEqual(settings.testapp.setting_to_redefine, 0)

        settings.testapp.app_setting = 'string'
        settings.testapp.setting_to_redefine = 60
        settings.save()
Ejemplo n.º 15
0
    def get_setman_names(available_settings=None):
        available_settings = available_settings or settings.available_settings
        data = []

        for setting in available_settings:
            if is_settings_container(setting):
                data.extend(get_setman_names(setting))
            else:
                name = '.'.join((setting.app_name, setting.name)) \
                       if setting.app_name else setting.name
                data.append(name)

        return data
Ejemplo n.º 16
0
    def get_setman_names(available_settings=None):
        available_settings = available_settings or settings.available_settings
        data = []

        for setting in available_settings:
            if is_settings_container(setting):
                data.extend(get_setman_names(setting))
            else:
                name = '.'.join((setting.app_name, setting.name)) \
                       if setting.app_name else setting.name
                data.append(name)

        return data
Ejemplo n.º 17
0
    def test_default_values(self, prefix=None):
        data = TEST_SETTINGS[prefix] if prefix else TEST_SETTINGS
        values = getattr(settings, prefix) if prefix else settings

        self.assertEqual(Settings.objects.count(), 0)

        for name, value in data.items():
            self.assertTrue(hasattr(values, name))
            mixed = getattr(values, name)

            if is_settings_container(mixed):
                self.test_default_values(name)
            else:
                self.assertEqual(mixed, value)
Ejemplo n.º 18
0
    def build_form_fields(self, available_settings=None, fields=None):
        """
        Build fields from list of availabale settings.
        """
        from setman import settings

        available_settings = available_settings or settings.available_settings
        fields = fields or OrderedDict()

        for setting in available_settings:
            if is_settings_container(setting):
                fields = self.build_form_fields(setting, fields)
            else:
                field = settings._framework.setting_to_field(setting)
                fields[field.name] = field

        return fields
Ejemplo n.º 19
0
    def _batch_method(self, method, data, prefix=None):
        """
        Run batch ``method`` for data.
        """
        available_settings = self.available_settings

        if prefix:
            available_settings = getattr(available_settings, prefix)

        for key, value in data.items():
            if not hasattr(available_settings, key):
                continue

            mixed = getattr(available_settings, key)

            if is_settings_container(mixed):
                data[key] = self._batch_method(method, value, key)
            else:
                data[key] = getattr(mixed, method)(value)

        return data
Ejemplo n.º 20
0
    def _batch_method(self, method, data, prefix=None):
        """
        Run batch ``method`` for data.
        """
        available_settings = self.available_settings

        if prefix:
            available_settings = getattr(available_settings, prefix)

        for key, value in data.items():
            if not hasattr(available_settings, key):
                continue

            mixed = getattr(available_settings, key)

            if is_settings_container(mixed):
                data[key] = self._batch_method(method, value, key)
            else:
                data[key] = getattr(mixed, method)(value)

        return data
Ejemplo n.º 21
0
    def test_available_settings(self):
        self.assertEqual(len(settings.available_settings), 4)

        setting = settings.available_settings.max_processes
        self.assertEqual(setting.default, 2)
        self.assertIsInstance(setting, IntSetting)

        setting = settings.available_settings.hosts_file
        self.assertEqual(setting.default, '/etc/hosts')
        self.assertIsInstance(setting, StringSetting)

        setting = settings.available_settings.hourly_rate
        self.assertEqual(setting.default, Decimal(15))
        self.assertIsInstance(setting, DecimalSetting)

        container = settings.available_settings.testapp
        self.assertTrue(is_settings_container(container))

        setting = settings.available_settings.testapp.debug
        self.assertEqual(setting.default, False)
        self.assertIsInstance(setting, BooleanSetting)
Ejemplo n.º 22
0
    def __getattr__(self, name):
        """
        Add support for getting settings keys as instance attribute.

        For first try, method tries to read settings from database, then from
        Django settings and if all fails try to return default value of
        available setting from configuration definition file if any.
        """
        if name.startswith('_'):
            return super(LazySettings, self).__getattr__(name)

        if name == 'available_settings':
            return self._available_settings_cache

        if not self._configured:
            self.autoconf()

        data, prefix = copy.deepcopy(self._backend.data), self._prefix
        framework_settings = self._framework.settings

        # Read app setting from database
        if prefix and prefix in data and name in data[prefix]:
            return data[prefix][name]
        # Read project setting from database
        elif name in data and not isinstance(data[name], dict):
            return data[name]
        # Or from framework settings
        elif hasattr(framework_settings, name):
            return getattr(framework_settings, name)
        # Or read default value from available settings
        elif hasattr(self._settings, name):
            mixed = getattr(self._settings, name)

            if is_settings_container(mixed):
                return LazySettings(mixed, name, self)

            return mixed.default

        # If cannot read setting - raise error
        raise SettingDoesNotExist(name)
Ejemplo n.º 23
0
    def __getattr__(self, name):
        """
        Add support for getting settings keys as instance attribute.

        For first try, method tries to read settings from database, then from
        Django settings and if all fails try to return default value of
        available setting from configuration definition file if any.
        """
        if name.startswith('_'):
            return super(LazySettings, self).__getattr__(name)

        if name == 'available_settings':
            return self._available_settings_cache

        if not self._configured:
            self.autoconf()

        data, prefix = copy.deepcopy(self._backend.data), self._prefix
        framework_settings = self._framework.settings

        # Read app setting from database
        if prefix and prefix in data and name in data[prefix]:
            return data[prefix][name]
        # Read project setting from database
        elif name in data and not isinstance(data[name], dict):
            return data[name]
        # Or from framework settings
        elif hasattr(framework_settings, name):
            return getattr(framework_settings, name)
        # Or read default value from available settings
        elif hasattr(self._settings, name):
            mixed = getattr(self._settings, name)

            if is_settings_container(mixed):
                return LazySettings(mixed, name, self)

            return mixed.default

        # If cannot read setting - raise error
        raise SettingDoesNotExist(name)
Ejemplo n.º 24
0
    def revert(self, prefix=None):
        """
        Revert all available settings to default values.
        """
        available_settings = self.available_settings
        available_settings = \
            getattr(available_settings, prefix) if prefix \
                                                else available_settings
        data = {}

        for mixed in available_settings:
            if is_settings_container(mixed):
                app_name = mixed.app_name
                data.update({app_name: self.revert(app_name)})
            else:
                data.update({mixed.name: mixed.default})

        if prefix:
            return data

        self.data = data
        self.save()
Ejemplo n.º 25
0
    def revert(self, prefix=None):
        """
        Revert all available settings to default values.
        """
        available_settings = self.available_settings
        available_settings = \
            getattr(available_settings, prefix) if prefix \
                                                else available_settings
        data = {}

        for mixed in available_settings:
            if is_settings_container(mixed):
                app_name = mixed.app_name
                data.update({app_name: self.revert(app_name)})
            else:
                data.update({mixed.name: mixed.default})

        if prefix:
            return data

        self.data = data
        self.save()
Ejemplo n.º 26
0
    def check_setman(self, verbosity):
        """
        Check setman configuration.
        """
        if verbosity:
            print >>self.stdout, "Project settings:"
            print >>self.stdout, "Configuration definition file placed at " "%r\n" % AVAILABLE_SETTINGS.path

            for setting in AVAILABLE_SETTINGS:
                indent = " " * 4

                if is_settings_container(setting):
                    print >>self.stdout, "%s%r settings:" % (indent, setting.app_name)
                    print >>self.stdout, "%sConfiguration definition file " "placed at %r" % (indent, setting.path)
                    indent *= 2

                    for subsetting in setting:
                        print >>self.stdout, "%s%r" % (indent, subsetting)

                    print >>self.stdout
                else:
                    print >>self.stdout, "%s%r" % (indent, setting)

            print >>self.stdout, ""