Exemplo n.º 1
0
    def test_07(self):
        """ Test modifying validators.
        """

        def name_validator(sheet, row, replaced_row=None):
            """ Splits name into first name and last name.
            """

            first_name, last_name = unicode(row[u'Name']).split()
            row[u'First name'] = first_name.capitalize()
            row[u'Last name'] = last_name.capitalize()
            del row[u'Name']

            return row

        sheet = Sheet(captions=[u'ID', u'First name', u'Last name'])

        sheet.add_validator(name_validator, 'insert', 'replace')

        self.assertRaises(ValueError, sheet.append, [u'1', u'Foo Bar'])
        self.assertRaises(
                ValueError, sheet.append, {u'ID': 1, u'Name': u'Foo'})
        self.assertEqual(len(sheet), 0)
        sheet.append({u'ID': 1, u'Name': u'   fOo  bAR'})
        self.assertEqual(len(sheet), 1)
        self.assertEqual(list(sheet[0]), [1, u'Foo', u'Bar'])

        sheet[0] = {u'ID': u'0', u'Name': u'bar foo'}
        self.assertEqual(len(sheet), 1)
        self.assertEqual(list(sheet[0]), [u'0', u'Bar', u'Foo'])

        validator = UniqueNameValidator()
        sheet.add_insert_validator(validator.insert)
        sheet.add_delete_validator(validator.delete)
        sheet.add_replace_validator(validator.replace)

        self.assertEqual(
                sheet.insert_validators, [name_validator, validator.insert])
        self.assertEqual(
                sheet.delete_validators, [validator.delete])
        self.assertEqual(
                sheet.replace_validators,
                [name_validator, validator.replace])

        sheet.append({u'Name': u'Fooer Barer'})
        self.assertEqual(
                list(u', '.join(row) for row in sheet),
                [u'0, Bar, Foo', u'1, Fooer, Barer'])
        self.assertRaises(
                ValidationError, sheet.append, {u'Name': u'Fooer Barer'})
        del sheet[1]
        sheet.append({u'Name': u'Fooer Barer'})
        self.assertEqual(
                list(u', '.join(row) for row in sheet),
                [u'0, Bar, Foo', u'2, Fooer, Barer'])
        sheet[1] = {u'Name': u'fooer barer', u'ID': u'1'}
        self.assertEqual(
                list(u', '.join(row) for row in sheet),
                [u'0, Bar, Foo', u'1, Fooer, Barer'])
Exemplo n.º 2
0
    def test_06(self):
        """ Test non-modifying validators.
        """

        validator = UniqueIntegerValidator(u'ID')
        sheet = Sheet(captions=[u'ID'])
        sheet.add_insert_validator(validator.insert)
        sheet.add_delete_validator(validator.delete)
        sheet.add_replace_validator(validator.replace)

        self.assertEqual(sheet.insert_validators, [validator.insert])
        self.assertEqual(sheet.delete_validators, [validator.delete])
        self.assertEqual(sheet.replace_validators, [validator.replace])

        sheet.add_validator(validate_nothing)
        self.assertEqual(sheet.insert_validators, [validator.insert])
        self.assertEqual(sheet.delete_validators, [validator.delete])
        self.assertEqual(sheet.replace_validators, [validator.replace])

        sheet.add_validator(validate_nothing, 'insert', 'delete', 'replace')
        self.assertEqual(sheet.insert_validators,
                         [validator.insert, validate_nothing])
        self.assertEqual(sheet.delete_validators,
                         [validator.delete, validate_nothing])
        self.assertEqual(sheet.replace_validators,
                         [validator.replace, validate_nothing])
        self.assertRaises(
                ValueError, sheet.add_validator, validate_nothing, 'foo')

        self.assertRaises(ValidationError, sheet.append, [u'baba'])
        self.assertEqual(len(sheet), 0)

        sheet.append([u'2'])
        sheet.append([u'3'])
        self.assertEqual(sorted(validator.values), [2, 3])
        self.assertEqual(sheet[1][u'ID'], 3)
        self.assertEqual(len(sheet), 2)

        self.assertRaises(ValidationError, sheet.append, [3])
        self.assertEqual(len(sheet), 2)
        del sheet[1]
        self.assertEqual(validator.values, set([2]))

        sheet.append([u'3'])
        sheet[1] = {u'ID': 4}
        sheet.append([u'3'])
Exemplo n.º 3
0
def dump_query_to_sheet(
        queryset, sheet=None, fields=None, exclude=None,
        join_rules=None,
        merge_rules=None):
    """ Dumps query to sheet.

    If ``sheet`` is None, then creates one.

    :param fields: what fields from object to include, if None then all.
    :param exclude:
        what fields from object to exclude, if None then none.
    :param join_rules: what relationships to join_rules by field.
    :param merge_rules:
        what relationships to merge_rules into sheet. (``get`` method
        must return an item or raise DoesNotExist error).
    :returns: sheet object.

    """

    if sheet is None:
        sheet = Sheet()

    if len(queryset) < 1:
        return sheet
    obj = queryset[0]

    if fields is None:
        fields = collect_fields(obj, exclude)

    def modifier(sheet, row):
        """ Changes fields to Unicode strings.
        """
        new_row = collections.defaultdict(unicode)
        for field_name, (obj, field) in row.items():
            if obj is not None:
                display_attr = 'get_{0}_display'.format(field.name)
                if hasattr(obj, display_attr):
                    new_row[field_name] = getattr(obj, display_attr)()
                else:
                    value = getattr(obj, field.name)
                    if value is None:
                        new_row[field_name] = u''
                    else:
                        new_row[field_name] = value
            else:
                new_row[field_name] = field
        return new_row

    sheet.add_insert_validator(modifier)
    sheet.add_columns([field.verbose_name for field in fields])

    mergable = {}
    joinable = {}
    merge_rules = merge_rules or ()
    join_rules = join_rules or ()
    for related_obj in obj._meta.get_all_related_objects():
        if related_obj.name in merge_rules:
            model = related_obj.model
            merge_fields = collect_fields(model, ('id',))
            mergable[related_obj.name] = merge_fields, model
            sheet.add_columns([
                field.verbose_name
                for field in merge_fields
                ])
        for field_name, model_name, kwargs in join_rules:
            if model_name == related_obj.name:
                model = related_obj.model
                field = model._meta.get_field(field_name)
                joinable[related_obj.name.split(':')[1]] = field, kwargs
                sheet.add_column(field.verbose_name)
                break

    for obj in queryset:
        row = dict([(field.verbose_name, (obj, field)) for field in fields])
        for full_name, (merge_fields, model) in mergable.items():
            name = full_name.split(':')[1]
            try:
                related_obj = getattr(obj, name)
                for field in merge_fields:
                    row[field.verbose_name] = related_obj, field
            except model.DoesNotExist:
                pass
        for name, (field, (filter_kwargs, exclude_kwargs)) in (
                joinable.items()):
            query = getattr(obj, '{0}_set'.format(name)).all()
            row[field.verbose_name] = None, join(
                    query.filter(**filter_kwargs).exclude(**exclude_kwargs),
                    field.name)
        sheet.append_dict(row)

    return sheet