コード例 #1
0
    def test_order_by_on_indexed_field(self):
        # Test order_by() on IndexedField (simple and multi-subfield). Only Contact items have these
        test_items = []
        label = self.random_val(EmailAddress.get_field_by_fieldname("label"))
        for i in range(4):
            item = self.get_test_item()
            item.email_addresses = [
                EmailAddress(email=f"{i}@foo.com", label=label)
            ]
            test_items.append(item)
        self.test_folder.bulk_create(items=test_items)
        qs = self.test_folder.filter(categories__contains=self.categories)
        self.assertEqual(
            [
                i[0].email
                for i in qs.order_by(f"email_addresses__{label}").values_list(
                    "email_addresses", flat=True)
            ],
            ["*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
        )
        self.assertEqual(
            [
                i[0].email
                for i in qs.order_by(f"-email_addresses__{label}").values_list(
                    "email_addresses", flat=True)
            ],
            ["*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"],
        )
        self.bulk_delete(qs)

        test_items = []
        label = self.random_val(
            PhysicalAddress.get_field_by_fieldname("label"))
        for i in range(4):
            item = self.get_test_item()
            item.physical_addresses = [
                PhysicalAddress(street=f"Elm St {i}", label=label)
            ]
            test_items.append(item)
        self.test_folder.bulk_create(items=test_items)
        qs = self.test_folder.filter(categories__contains=self.categories)
        self.assertEqual(
            [
                i[0].street
                for i in qs.order_by(f"physical_addresses__{label}__street").
                values_list("physical_addresses", flat=True)
            ],
            ["Elm St 0", "Elm St 1", "Elm St 2", "Elm St 3"],
        )
        self.assertEqual(
            [
                i[0].street
                for i in qs.order_by(f"-physical_addresses__{label}__street").
                values_list("physical_addresses", flat=True)
            ],
            ["Elm St 3", "Elm St 2", "Elm St 1", "Elm St 0"],
        )
        self.bulk_delete(qs)
コード例 #2
0
ファイル: test_contacts.py プロジェクト: spmsh/exchangelib
 def test_update_on_multi_field_indexed_field(self):
     home = PhysicalAddress(label='Home', street='ABC')
     business = PhysicalAddress(label='Business', street='DEF', city='GHI')
     item = self.get_test_item()
     item.physical_addresses = [home]
     item.save()
     item.physical_addresses = [business]
     item.save(update_fields=['physical_addresses'])
     item.refresh()
     self.assertListEqual(item.physical_addresses, [business])
コード例 #3
0
 def test_update_on_multi_field_indexed_field(self):
     home = PhysicalAddress(label="Home", street="ABC")
     business = PhysicalAddress(label="Business", street="DEF", city="GHI")
     item = self.get_test_item()
     item.physical_addresses = [home]
     item.save()
     item.physical_addresses = [business]
     item.save(update_fields=["physical_addresses"])
     item.refresh()
     self.assertListEqual(item.physical_addresses, [business])
コード例 #4
0
ファイル: test_contacts.py プロジェクト: zha0/exchangelib
    def test_order_by_on_indexed_field(self):
        # Test order_by() on IndexedField (simple and multi-subfield). Only Contact items have these
        test_items = []
        label = self.random_val(EmailAddress.get_field_by_fieldname('label'))
        for i in range(4):
            item = self.get_test_item()
            item.email_addresses = [
                EmailAddress(email='*****@*****.**' % i, label=label)
            ]
            test_items.append(item)
        self.test_folder.bulk_create(items=test_items)
        qs = QuerySet(folder_collection=FolderCollection(
            account=self.account, folders=[self.test_folder])).filter(
                categories__contains=self.categories)
        self.assertEqual([
            i[0].email
            for i in qs.order_by('email_addresses__%s' % label).values_list(
                'email_addresses', flat=True)
        ], ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
        self.assertEqual([
            i[0].email
            for i in qs.order_by('-email_addresses__%s' % label).values_list(
                'email_addresses', flat=True)
        ], ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'])
        self.bulk_delete(qs)

        test_items = []
        label = self.random_val(
            PhysicalAddress.get_field_by_fieldname('label'))
        for i in range(4):
            item = self.get_test_item()
            item.physical_addresses = [
                PhysicalAddress(street='Elm St %s' % i, label=label)
            ]
            test_items.append(item)
        self.test_folder.bulk_create(items=test_items)
        qs = QuerySet(folder_collection=FolderCollection(
            account=self.account, folders=[self.test_folder])).filter(
                categories__contains=self.categories)
        self.assertEqual([
            i[0].street
            for i in qs.order_by('physical_addresses__%s__street' % label).
            values_list('physical_addresses', flat=True)
        ], ['Elm St 0', 'Elm St 1', 'Elm St 2', 'Elm St 3'])
        self.assertEqual([
            i[0].street
            for i in qs.order_by('-physical_addresses__%s__street' % label).
            values_list('physical_addresses', flat=True)
        ], ['Elm St 3', 'Elm St 2', 'Elm St 1', 'Elm St 0'])
        self.bulk_delete(qs)
コード例 #5
0
 def random_val(self, field):
     if isinstance(field, ExtendedPropertyField):
         if field.value_cls.property_type == 'StringArray':
             return [get_random_string(255) for _ in range(random.randint(1, 4))]
         if field.value_cls.property_type == 'IntegerArray':
             return [get_random_int(0, 256) for _ in range(random.randint(1, 4))]
         if field.value_cls.property_type == 'BinaryArray':
             return [get_random_string(255).encode() for _ in range(random.randint(1, 4))]
         if field.value_cls.property_type == 'String':
             return get_random_string(255)
         if field.value_cls.property_type == 'Integer':
             return get_random_int(0, 256)
         if field.value_cls.property_type == 'Binary':
             # In the test_extended_distinguished_property test, EWS rull return 4 NULL bytes after char 16 if we
             # send a longer bytes sequence.
             return get_random_string(16).encode()
         raise ValueError('Unsupported field %s' % field)
     if isinstance(field, URIField):
         return get_random_url()
     if isinstance(field, EmailAddressField):
         return get_random_email()
     if isinstance(field, ChoiceField):
         return get_random_choice(field.supported_choices(version=self.account.version))
     if isinstance(field, CultureField):
         return get_random_choice(['da-DK', 'de-DE', 'en-US', 'es-ES', 'fr-CA', 'nl-NL', 'ru-RU', 'sv-SE'])
     if isinstance(field, BodyField):
         return get_random_string(400)
     if isinstance(field, CharListField):
         return [get_random_string(16) for _ in range(random.randint(1, 4))]
     if isinstance(field, TextListField):
         return [get_random_string(400) for _ in range(random.randint(1, 4))]
     if isinstance(field, CharField):
         return get_random_string(field.max_length)
     if isinstance(field, TextField):
         return get_random_string(400)
     if isinstance(field, MimeContentField):
         return get_random_string(400).encode('utf-8')
     if isinstance(field, Base64Field):
         return get_random_bytes(400)
     if isinstance(field, BooleanField):
         return get_random_bool()
     if isinstance(field, DecimalField):
         return get_random_decimal(field.min or 1, field.max or 99)
     if isinstance(field, IntegerField):
         return get_random_int(field.min or 0, field.max or 256)
     if isinstance(field, DateField):
         return get_random_date()
     if isinstance(field, DateTimeBackedDateField):
         return get_random_date()
     if isinstance(field, DateTimeField):
         return get_random_datetime(tz=self.account.default_timezone)
     if isinstance(field, AttachmentField):
         return [FileAttachment(name='my_file.txt', content=get_random_string(400).encode('utf-8'))]
     if isinstance(field, MailboxListField):
         # email_address must be a real account on the server(?)
         # TODO: Mailbox has multiple optional args but vals must match server account, so we can't easily test
         if get_random_bool():
             return [Mailbox(email_address=self.account.primary_smtp_address)]
         return [self.account.primary_smtp_address]
     if isinstance(field, MailboxField):
         # email_address must be a real account on the server(?)
         # TODO: Mailbox has multiple optional args but vals must match server account, so we can't easily test
         if get_random_bool():
             return Mailbox(email_address=self.account.primary_smtp_address)
         return self.account.primary_smtp_address
     if isinstance(field, AttendeesField):
         # Attendee must refer to a real mailbox on the server(?). We're only sure to have one
         if get_random_bool():
             mbx = Mailbox(email_address=self.account.primary_smtp_address)
         else:
             mbx = self.account.primary_smtp_address
         with_last_response_time = get_random_bool()
         if with_last_response_time:
             return [
                 Attendee(mailbox=mbx, response_type='Accept',
                          last_response_time=get_random_datetime(tz=self.account.default_timezone))
             ]
         if get_random_bool():
             return [Attendee(mailbox=mbx, response_type='Accept')]
         return [self.account.primary_smtp_address]
     if isinstance(field, EmailAddressesField):
         addrs = []
         for label in EmailAddress.get_field_by_fieldname('label').supported_choices(version=self.account.version):
             addr = EmailAddress(email=get_random_email())
             addr.label = label
             addrs.append(addr)
         return addrs
     if isinstance(field, PhysicalAddressField):
         addrs = []
         for label in PhysicalAddress.get_field_by_fieldname('label')\
                 .supported_choices(version=self.account.version):
             addr = PhysicalAddress(street=get_random_string(32), city=get_random_string(32),
                                    state=get_random_string(32), country=get_random_string(32),
                                    zipcode=get_random_string(8))
             addr.label = label
             addrs.append(addr)
         return addrs
     if isinstance(field, PhoneNumberField):
         pns = []
         for label in PhoneNumber.get_field_by_fieldname('label').supported_choices(version=self.account.version):
             pn = PhoneNumber(phone_number=get_random_string(16))
             pn.label = label
             pns.append(pn)
         return pns
     if isinstance(field, EWSElementField):
         if field.value_cls == Recurrence:
             return Recurrence(pattern=DailyPattern(interval=5), start=get_random_date(), number=7)
         if field.value_cls == TaskRecurrence:
             return TaskRecurrence(pattern=DailyRegeneration(interval=5), start=get_random_date(), number=7)
         if field.value_cls == ReminderMessageData:
             start = get_random_time()
             end = get_random_time(start_time=start)
             return ReminderMessageData(
                 reminder_text=get_random_string(16),
                 location=get_random_string(16),
                 start_time=start,
                 end_time=end,
             )
     if field.value_cls == CompleteName:
         return CompleteName(
             title=get_random_string(16),
             first_name=get_random_string(16),
             middle_name=get_random_string(16),
             last_name=get_random_string(16),
             suffix=get_random_string(16),
             initials=get_random_string(16),
             full_name=get_random_string(16),
             nickname=get_random_string(16),
             yomi_first_name=get_random_string(16),
             yomi_last_name=get_random_string(16),
         )
     if isinstance(field, TimeZoneField):
         while True:
             tz = zoneinfo.ZoneInfo(random.choice(tuple(zoneinfo.available_timezones())))
             try:
                 EWSTimeZone.from_zoneinfo(tz)
             except UnknownTimeZone:
                 continue
             return tz
     if isinstance(field, PermissionSetField):
         return PermissionSet(
             permissions=[
                 Permission(
                     user_id=UserId(primary_smtp_address=self.account.primary_smtp_address),
                 )
             ]
         )
     raise ValueError('Unknown field %s' % field)
コード例 #6
0
 def test_physical_address(self):
     # Test that we can enter an integer zipcode and that it's converted to a string by clean()
     zipcode = 98765
     addr = PhysicalAddress(zipcode=zipcode)
     addr.clean()
     self.assertEqual(addr.zipcode, str(zipcode))