Beispiel #1
0
def test_sort_after_points_to_nothing():
    with pytest.raises(KeyError) as e:
        sort_after([
            Struct(name='quux'),
            Struct(name='foo'),
            Struct(name='quux6', after='does-not-exist'),
        ])

    assert "'Tried to order after does-not-exist but that key does not exist'" == str(e.value)
Beispiel #2
0
def test_sort_after_points_to_nothing_plural():
    with pytest.raises(KeyError) as e:
        sort_after([
            Struct(name='quux'),
            Struct(name='foo', after='does-not-exist2'),
            Struct(name='quux6', after='does-not-exist'),
        ])

    assert "'Tried to order after does-not-exist, does-not-exist2 but those keys do not exist'" == str(e.value)
Beispiel #3
0
def test_sort_after_points_to_nothing_plural():
    with pytest.raises(KeyError) as e:
        sort_after([
            Struct(name='quux'),
            Struct(name='foo', after='does-not-exist2'),
            Struct(name='quux6', after='does-not-exist'),
        ])

    assert "'Tried to order after does-not-exist, does-not-exist2 but those keys do not exist'" == str(
        e.value).replace("u'", "'")
Beispiel #4
0
def test_sort_after_points_to_nothing():
    objects = [
        Struct(name='quux'),
        Struct(name='foo'),
        Struct(name='quux6', after='does-not-exist'),
    ]

    with pytest.raises(KeyError) as e:
        sort_after(objects)

    assert e.value.message == 'Tried to order after does-not-exist but that key does not exist'
Beispiel #5
0
    def __init__(self, request=None, variables=None, variables_dict=None, endpoint_dispatch_prefix='query', **kwargs):  # variables=None to make pycharm tooling not confused
        """
        :type variables: list of Variable
        :type request: django.http.request.HttpRequest
        """
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.request = request
        self._form = None

        def generate_variables():
            if variables is not None:
                for variable in variables:
                    yield variable
            for name, variable in variables_dict.items():
                dict.__setitem__(variable, 'name', name)
                yield variable
        self.variables = sort_after(list(generate_variables()))

        def generate_bound_variables():
            for x in self.variables:
                yield BoundVariable(**merged(
                    Struct(x),
                    query=self,
                    attr=x.attr if x.attr is not MISSING else x.name
                ))
        bound_variables = list(generate_bound_variables())

        bound_variables = [evaluate_recursive(x, query=self, variable=x) for x in bound_variables]
        self.bound_variables = filter_show_recursive(bound_variables)

        self.bound_variable_by_name = {variable.name: variable for variable in self.bound_variables}

        self.gui_kwargs = extract_subkeys(kwargs, 'gui')
Beispiel #6
0
def sorts_right(objects):
    expected_order = sorted(objects, key=lambda x: x.expected_position)
    assert [y.expected_position for y in expected_order
            ] == list(range(len(objects))), "Borken test"
    sorted_objects = sort_after(objects)
    assert list(range(len(objects))) == [
        x.expected_position for x in sorted_objects
    ], [x.name for x in objects]
Beispiel #7
0
    def __init__(self, request=None, data=None, instance=None, fields=None, model=None, post_validation=None):
        """
        :type fields: list of Field
        :type data: dict[basestring, basestring]
        :type model: django.db.models.Model
        """
        self.request = request
        if data is None and request:
            data = request.POST if request.method == 'POST' else request.GET

        if isinstance(fields, dict):  # Declarative case
            fields = [merged(field, dict(name=name)) for name, field in fields.items()]
        self.fields = sort_after([BoundField(field, self) for field in fields])

        if instance is not None:
            for field in self.fields:
                if field.attr:
                    initial = getattr_path(instance, field.attr)
                    if field.is_list:
                        field.initial_list = initial
                    else:
                        field.initial = initial

        if data:
            for field in self.fields:
                if field.is_list:
                    try:
                        # noinspection PyUnresolvedReferences
                        raw_data_list = data.getlist(field.name)
                    except AttributeError:  # pragma: no cover
                        raw_data_list = data.get(field.name)
                    if raw_data_list and field.strip_input:
                        raw_data_list = [x.strip() for x in raw_data_list]
                    if raw_data_list is not None:
                        field.raw_data_list = raw_data_list
                else:
                    field.raw_data = data.get(field.name)
                    if field.raw_data and field.strip_input:
                        field.raw_data = field.raw_data.strip()

        if post_validation is not None:
            self.post_validation = post_validation
        self.fields_by_name = {field.name: field for field in self.fields}
        self.style = None
        self.model = model
        self._valid = None
        self.errors = []
        self.should_parse = bool(data)
        self.evaluate()
        self.is_valid()
Beispiel #8
0
    def __init__(self, request=None, data=None, instance=None, fields=None, model=None, post_validation=None, fields_dict=None, endpoint_dispatch_prefix='form', is_full_form=True):
        """
        :type fields: list of Field
        :type data: dict[basestring, basestring]
        :type model: django.db.models.Model
        """
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.is_full_form = is_full_form
        self.request = request
        if data is None and request:
            data = request.POST if request.method == 'POST' else request.GET

        if data is None:
            data = {}

        def unbound_fields():
            if fields is not None:
                for field in fields:
                    yield field
            for name, field in fields_dict.items():
                dict.__setitem__(field, 'name', name)
                yield field
        self.fields = sort_after([BoundField(f, self) for f in unbound_fields()])
        """ :type: list of BoundField"""

        if instance is not None:
            for field in self.fields:
                if field.attr:
                    initial = field.read_from_instance(field, instance)
                    if field.is_list:
                        field.initial_list = initial
                    else:
                        field.initial = initial

            self.instance = instance
        else:
            self.instance = None

        self.mode = FULL_FORM_FROM_REQUEST if '-' in data else INITIALS_FROM_GET
        if self.mode == INITIALS_FROM_GET and request:
            assert request.method == 'GET', 'Seems to be a POST but parameter "-" is not present'

        if data:
            for field in self.fields:
                if field.is_list:
                    try:
                        # django and similar
                        # noinspection PyUnresolvedReferences
                        raw_data_list = data.getlist(field.name)
                    except AttributeError:  # pragma: no cover
                        # werkzeug and similar
                        raw_data_list = data.get(field.name)

                    if raw_data_list and field.strip_input:
                        raw_data_list = [x.strip() for x in raw_data_list]

                    if raw_data_list is not None:
                        field.raw_data_list = raw_data_list
                else:
                    field.raw_data = data.get(field.name)
                    if field.raw_data and field.strip_input:
                        field.raw_data = field.raw_data.strip()

        self.post_validation = post_validation if post_validation is not None else lambda form: None
        self.fields_by_name = None
        """ :type: dict[str, BoundField] """
        self.style = None
        self.model = model
        """ :type model: django.db.models.Model """
        self._valid = None
        self.errors = set()
        self.evaluate()
        self.is_valid()
        """ :type: list of str """
Beispiel #9
0
    def __init__(
        self,
        data=None,
        request=None,
        columns=None,
        columns_dict=None,
        model=None,
        filter=None,
        bulk_exclude=None,
        sortable=None,
        links=None,
        column=None,
        bulk=None,
        header=None,
        bulk_filter=None,
        endpoint=None,
        attrs=None,
        query=None,
        endpoint_dispatch_prefix=None,
        row=None,
        instance=None,
        extra=None,
    ):
        """
        :param data: a list or QuerySet of objects
        :param columns: (use this only when not using the declarative style) a list of Column objects
        :param attrs: dict of strings to string/callable of HTML attributes to apply to the table
        :param row__attrs: dict of strings to string/callable of HTML attributes to apply to the row. Callables are passed the row as argument.
        :param row__template: name of template to use for rendering the row
        :param bulk_filter: filters to apply to the QuerySet before performing the bulk operation
        :param bulk_exclude: exclude filters to apply to the QuerySet before performing the bulk operation
        :param sortable: set this to false to turn off sorting for all columns
        """

        if data is None:  # pragma: no cover
            warnings.warn("deriving model from data queryset is deprecated, use Table.from_model", DeprecationWarning)
            assert model is not None
            data = model.objects.all()

        if isinstance(data, QuerySet):
            model = data.model

        def generate_columns():
            for column_ in columns if columns is not None else []:
                yield column_
            for name, column_ in columns_dict.items():
                dict.__setitem__(column_, "name", name)
                yield column_

        columns = sort_after(list(generate_columns()))

        assert (
            len(columns) > 0
        ), "columns must be specified. It is only set to None to make linting tools not give false positives on the declarative style"

        self.data = data
        self.request = request
        self.columns = columns
        """ :type : list of Column """

        self.model = model
        self.instance = instance

        self.filter = TemplateConfig(**filter)
        self.links = TemplateConfig(**links)
        self.header = TemplateConfig(**header)
        self.row = RowConfig(**row)
        self.bulk_exclude = bulk_exclude
        self.sortable = sortable
        self.column = column
        self.bulk = bulk
        self.bulk_filter = bulk_filter
        self.endpoint = endpoint
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.attrs = attrs

        self.query_args = query
        self.query = None
        """ :type : tri.query.Query """
        self.query_form = None
        """ :type : tri.form.Form """
        self.query_error = None
        """ :type : list of str """

        self.bulk_form = None
        """ :type : tri.form.Form """
        self.bound_columns = None
        """ :type : list of BoundColumn """
        self.shown_bound_columns = None
        """ :type : list of BoundColumn """
        self.bound_column_by_name = None
        """ :type: dict[str, BoundColumn] """
        self._has_prepared = False
        """ :type: bool """
        self.header_levels = None

        self.extra = extra
        """ :type: tri.declarative.Namespace """
def test_order_after():
    objects = [
        # header1
        Struct(name='quux', expected_position=2),
        Struct(name='foo', expected_position=3),
        # header2
        Struct(name='bar', expected_position=6),
        Struct(name='asd', expected_position=7),
        Struct(name='header1', after=0, expected_position=0),
        Struct(name='header1b', after=0, expected_position=1),
        Struct(name='header2', after='foo', expected_position=4),
        Struct(name='header2.b', after='foo', expected_position=5),
        Struct(name='header3', after='quux2', expected_position=9),
        Struct(name='quux2', expected_position=8),
        # header3
        Struct(name='quux3', expected_position=10),
        Struct(name='quux4', expected_position=11),
        Struct(name='quux5', after=LAST, expected_position=12),
        Struct(name='quux6', after=LAST, expected_position=13),
    ]

    expected_order = sorted(objects, key=lambda x: x.expected_position)
    assert list(range(len(objects))) == [y.expected_position for y in expected_order], 'check expected_order'
    assert [x.expected_position for x in expected_order] == [x.expected_position for x in sort_after(objects)]
Beispiel #11
0
def test_sort_after_chaining():
    objects = [
        Struct(name='foo', after='bar'),
        Struct(name='bar', after=0),
    ]
    assert ['bar', 'foo'] == [x.name for x in sort_after(objects)]
Beispiel #12
0
    def __init__(self, request=None, data=None, instance=None, fields=None, model=None, post_validation=None, fields_dict=None, endpoint_dispatch_prefix='form'):
        """
        :type fields: list of Field
        :type data: dict[basestring, basestring]
        :type model: django.db.models.Model
        """
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.request = request
        if data is None and request:
            data = request.POST if request.method == 'POST' else request.GET

        if data is None:
            data = {}

        def unbound_fields():
            if fields is not None:
                for field in fields:
                    yield field
            for name, field in fields_dict.items():
                dict.__setitem__(field, 'name', name)
                yield field
        self.fields = sort_after([BoundField(f, self) for f in unbound_fields()])
        """ :type: list of BoundField"""

        if instance is not None:
            for field in self.fields:
                if field.attr:
                    initial = field.read_from_instance(field, instance)
                    if field.is_list:
                        field.initial_list = initial
                    else:
                        field.initial = initial

            self.instance = instance
        else:
            self.instance = None

        self.mode = FULL_FORM_FROM_REQUEST if '-' in data else INITIALS_FROM_GET
        if self.mode == INITIALS_FROM_GET and request:
            assert request.method == 'GET', 'Seems to be a POST but parameter "-" is not present'

        if data:
            for field in self.fields:
                if field.is_list:
                    try:
                        # django and similar
                        # noinspection PyUnresolvedReferences
                        raw_data_list = data.getlist(field.name)
                    except AttributeError:  # pragma: no cover
                        # werkzeug and similar
                        raw_data_list = data.get(field.name)

                    if raw_data_list and field.strip_input:
                        raw_data_list = [x.strip() for x in raw_data_list]

                    if raw_data_list is not None:
                        field.raw_data_list = raw_data_list
                else:
                    field.raw_data = data.get(field.name)
                    if field.raw_data and field.strip_input:
                        field.raw_data = field.raw_data.strip()

        self.post_validation = post_validation if post_validation is not None else lambda form: None
        self.fields_by_name = None
        """ :type: dict[str, BoundField] """
        self.style = None
        self.model = model
        """ :type model: django.db.models.Model """
        self._valid = None
        self.errors = set()
        self.evaluate()
        self.is_valid()
        """ :type: list of str """
Beispiel #13
0
    def __init__(self,
                 data=None,
                 request=None,
                 columns=None,
                 columns_dict=None,
                 **kwargs):
        """
        :param data: a list of QuerySet of objects
        :param columns: (use this only when not using the declarative style) a list of Column objects
        :param attrs: dict of strings to string/callable of HTML attributes to apply to the table
        :param row__attrs: dict of strings to string/callable of HTML attributes to apply to the row. Callables are passed the row as argument.
        :param row__template: name of template to use for rendering the row
        :param bulk_filter: filters to apply to the QuerySet before performing the bulk operation
        :param bulk_exclude: exclude filters to apply to the QuerySet before performing the bulk operation
        :param sortable: set this to false to turn off sorting for all columns
        :param filter__template:
        :param header__template:
        :param links__template:

        """

        self._has_prepared = False

        if data is None:
            assert 'model' in kwargs and kwargs['model'] is not None
            data = kwargs['model'].objects.all()

        self.data = data
        self.request = request

        if isinstance(self.data, QuerySet):
            kwargs['model'] = data.model

        def generate_columns():
            for column in columns if columns is not None else []:
                yield column
            for name, column in columns_dict.items():
                dict.__setitem__(column, 'name', name)
                yield column

        self.columns = sort_after(list(generate_columns()))
        """:type : list of Column"""

        assert len(
            self.columns
        ) > 0, 'columns must be specified. It is only set to None to make linting tools not give false positives on the declarative style'

        self.bound_columns = None
        self.shown_bound_columns = None
        self.bound_column_by_name = None

        self.Meta = self.get_meta()
        self.Meta.update(**kwargs)

        self.header_levels = None
        self.query = None
        self.query_form = None
        self.query_error = None
        self.bulk_form = None

        self.query_kwargs = extract_subkeys(kwargs, 'query')
        self.bulk_kwargs = extract_subkeys(kwargs, 'bulk')
        self.endpoint = extract_subkeys(kwargs, 'endpoint')