Esempio n. 1
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)
Esempio n. 2
0
    def test_delegate(self):
        # The test server does not have any delegate info. Mock instead.
        xml = b'''<?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap:Header>
            <t:ServerVersionInfo MajorBuildNumber="845" MajorVersion="15" MinorBuildNumber="22" MinorVersion="1"
                                 Version="V2016_10_10"
                                 xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" />
          </soap:Header>
          <soap:Body>
            <m:GetDelegateResponse xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
                                   ResponseClass="Success"
                                   xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
              <m:ResponseCode>NoError</m:ResponseCode>
              <m:ResponseMessages>
                <m:DelegateUserResponseMessageType ResponseClass="Success">
                  <m:ResponseCode>NoError</m:ResponseCode>
                  <m:DelegateUser>
                      <t:UserId>
                        <t:SID>SOME_SID</t:SID>
                        <t:PrimarySmtpAddress>[email protected]</t:PrimarySmtpAddress>
                        <t:DisplayName>Foo Bar</t:DisplayName>
                      </t:UserId>
                      <t:DelegatePermissions>
                        <t:CalendarFolderPermissionLevel>Author</t:CalendarFolderPermissionLevel>
                        <t:InboxFolderPermissionLevel>Reviewer</t:ContactsFolderPermissionLevel>
                      </t:DelegatePermissions>
                      <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
                    <t:ViewPrivateItems>true</t:ViewPrivateItems>
                    </m:DelegateUser>
                  </m:DelegateUserResponseMessageType>
              </m:ResponseMessages>
              <m:DeliverMeetingRequests>DelegatesAndMe</m:DeliverMeetingRequests>
              </m:GetDelegateResponse>
          </soap:Body>
        </soap:Envelope>'''

        MockTZ = namedtuple('EWSTimeZone', ['ms_id'])
        MockAccount = namedtuple('Account', ['access_type', 'primary_smtp_address', 'default_timezone', 'protocol'])
        a = MockAccount(DELEGATE, '*****@*****.**', MockTZ('XXX'), protocol='foo')

        ws = GetDelegate(account=a)
        header, body = ws._get_soap_parts(response=MockResponse(xml))
        res = ws._get_elements_in_response(response=ws._get_soap_messages(body=body))
        delegates = [DelegateUser.from_xml(elem=elem, account=a) for elem in res]
        self.assertListEqual(
            delegates,
            [
                DelegateUser(
                    user_id=UserId(sid='SOME_SID', primary_smtp_address='*****@*****.**', display_name='Foo Bar'),
                    delegate_permissions=DelegatePermissions(
                        calendar_folder_permission_level='Author',
                        inbox_folder_permission_level='Reviewer',
                        contacts_folder_permission_level='None',
                        notes_folder_permission_level='None',
                        journal_folder_permission_level='None',
                        tasks_folder_permission_level='None',
                    ),
                    receive_copies_of_meeting_messages=False,
                    view_private_items=True,
                )
            ]
        )
Esempio n. 3
0
    def test_delegate(self):
        # The test server does not have any delegate info. Test that account.delegates works, and mock to test parsing
        # of a non-empty response.
        self.assertGreaterEqual(
            len(self.account.delegates),
            0
        )
        self.assertGreaterEqual(
            len(list(GetDelegate(account=self.account).call(user_ids=['*****@*****.**'], include_permissions=True))),
            0
        )

        xml = b'''\
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <m:GetDelegateResponse ResponseClass="Success"
            xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
            xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
      <m:ResponseCode>NoError</m:ResponseCode>
      <m:ResponseMessages>
        <m:DelegateUserResponseMessageType ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:DelegateUser>
              <t:UserId>
                <t:SID>SOME_SID</t:SID>
                <t:PrimarySmtpAddress>[email protected]</t:PrimarySmtpAddress>
                <t:DisplayName>Foo Bar</t:DisplayName>
              </t:UserId>
              <t:DelegatePermissions>
                <t:CalendarFolderPermissionLevel>Author</t:CalendarFolderPermissionLevel>
                <t:InboxFolderPermissionLevel>Reviewer</t:ContactsFolderPermissionLevel>
              </t:DelegatePermissions>
              <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
            <t:ViewPrivateItems>true</t:ViewPrivateItems>
            </m:DelegateUser>
          </m:DelegateUserResponseMessageType>
      </m:ResponseMessages>
      <m:DeliverMeetingRequests>DelegatesAndMe</m:DeliverMeetingRequests>
      </m:GetDelegateResponse>
  </s:Body>
</s:Envelope>'''

        MockTZ = namedtuple('EWSTimeZone', ['ms_id'])
        MockAccount = namedtuple('Account', ['access_type', 'primary_smtp_address', 'default_timezone', 'protocol'])
        MockProtocol = namedtuple('Protocol', ['version'])
        p = MockProtocol(version=Version(build=EXCHANGE_2007_SP1))
        a = MockAccount(DELEGATE, '*****@*****.**', MockTZ('XXX'), protocol=p)

        ws = GetDelegate(account=a)
        _, body = ws._get_soap_parts(response=MockResponse(xml))
        res = ws._get_elements_in_response(response=ws._get_soap_messages(body=body))
        delegates = [DelegateUser.from_xml(elem=elem, account=a) for elem in res]
        self.assertListEqual(
            delegates,
            [
                DelegateUser(
                    user_id=UserId(sid='SOME_SID', primary_smtp_address='*****@*****.**', display_name='Foo Bar'),
                    delegate_permissions=DelegatePermissions(
                        calendar_folder_permission_level='Author',
                        inbox_folder_permission_level='Reviewer',
                        contacts_folder_permission_level='None',
                        notes_folder_permission_level='None',
                        journal_folder_permission_level='None',
                        tasks_folder_permission_level='None',
                    ),
                    receive_copies_of_meeting_messages=False,
                    view_private_items=True,
                )
            ]
        )
Esempio n. 4
0
    def test_permissionset_effectiverights_parsing(self):
        # Test static XML since server may not have any permission sets or effective rights
        xml = b'''\
<?xml version="1.0" ?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
                             xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:GetFolderResponseMessage ResponseClass="Success">
                    <m:ResponseCode>NoError</m:ResponseCode>
                    <m:Folders>
                        <t:CalendarFolder>
                            <t:FolderId Id="XXX" ChangeKey="YYY"/>
                            <t:ParentFolderId Id="ZZZ" ChangeKey="WWW"/>
                            <t:FolderClass>IPF.Appointment</t:FolderClass>
                            <t:DisplayName>My Calendar</t:DisplayName>
                            <t:TotalCount>1</t:TotalCount>
                            <t:ChildFolderCount>2</t:ChildFolderCount>
                            <t:EffectiveRights>
                                <t:CreateAssociated>true</t:CreateAssociated>
                                <t:CreateContents>true</t:CreateContents>
                                <t:CreateHierarchy>true</t:CreateHierarchy>
                                <t:Delete>true</t:Delete>
                                <t:Modify>true</t:Modify>
                                <t:Read>true</t:Read>
                                <t:ViewPrivateItems>false</t:ViewPrivateItems>
                            </t:EffectiveRights>
                            <t:PermissionSet>
                                <t:CalendarPermissions>
                                    <t:CalendarPermission>
                                        <t:UserId>
                                            <t:SID>SID1</t:SID>
                                            <t:PrimarySmtpAddress>[email protected]</t:PrimarySmtpAddress>
                                            <t:DisplayName>User 1</t:DisplayName>
                                        </t:UserId>
                                        <t:CanCreateItems>false</t:CanCreateItems>
                                        <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                                        <t:IsFolderOwner>false</t:IsFolderOwner>
                                        <t:IsFolderVisible>true</t:IsFolderVisible>
                                        <t:IsFolderContact>false</t:IsFolderContact>
                                        <t:EditItems>None</t:EditItems>
                                        <t:DeleteItems>None</t:DeleteItems>
                                        <t:ReadItems>FullDetails</t:ReadItems>
                                        <t:CalendarPermissionLevel>Reviewer</t:CalendarPermissionLevel>
                                    </t:CalendarPermission>
                                    <t:CalendarPermission>
                                        <t:UserId>
                                            <t:SID>SID2</t:SID>
                                            <t:PrimarySmtpAddress>[email protected]</t:PrimarySmtpAddress>
                                            <t:DisplayName>User 2</t:DisplayName>
                                        </t:UserId>
                                        <t:CanCreateItems>true</t:CanCreateItems>
                                        <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                                        <t:IsFolderOwner>false</t:IsFolderOwner>
                                        <t:IsFolderVisible>true</t:IsFolderVisible>
                                        <t:IsFolderContact>false</t:IsFolderContact>
                                        <t:EditItems>All</t:EditItems>
                                        <t:DeleteItems>All</t:DeleteItems>
                                        <t:ReadItems>FullDetails</t:ReadItems>
                                        <t:CalendarPermissionLevel>Editor</t:CalendarPermissionLevel>
                                    </t:CalendarPermission>
                                </t:CalendarPermissions>
                            </t:PermissionSet>
                        </t:CalendarFolder>
                    </m:Folders>
                </m:GetFolderResponseMessage>
            </m:ResponseMessages>
        </m:GetFolderResponse>
    </s:Body>
</s:Envelope>'''
        ws = GetFolder(account=self.account)
        ws.folders = [self.account.calendar]
        res = list(ws.parse(xml))
        self.assertEqual(len(res), 1)
        fld = res[0]
        self.assertEqual(
            fld.effective_rights,
            EffectiveRights(create_associated=True,
                            create_contents=True,
                            create_hierarchy=True,
                            delete=True,
                            modify=True,
                            read=True,
                            view_private_items=False))
        self.assertEqual(
            fld.permission_set,
            PermissionSet(permissions=None,
                          calendar_permissions=[
                              CalendarPermission(
                                  can_create_items=False,
                                  can_create_subfolders=False,
                                  is_folder_owner=False,
                                  is_folder_visible=True,
                                  is_folder_contact=False,
                                  edit_items='None',
                                  delete_items='None',
                                  read_items='FullDetails',
                                  user_id=UserId(
                                      sid='SID1',
                                      primary_smtp_address='*****@*****.**',
                                      display_name='User 1',
                                      distinguished_user=None,
                                      external_user_identity=None),
                                  calendar_permission_level='Reviewer'),
                              CalendarPermission(
                                  can_create_items=True,
                                  can_create_subfolders=False,
                                  is_folder_owner=False,
                                  is_folder_visible=True,
                                  is_folder_contact=False,
                                  edit_items='All',
                                  delete_items='All',
                                  read_items='FullDetails',
                                  user_id=UserId(
                                      sid='SID2',
                                      primary_smtp_address='*****@*****.**',
                                      display_name='User 2',
                                      distinguished_user=None,
                                      external_user_identity=None),
                                  calendar_permission_level='Editor')
                          ],
                          unknown_entries=None),
        )
    def test_delegate(self):
        # The test server does not have any delegate info. Test that account.delegates works, and mock to test parsing
        # of a non-empty response.
        self.assertGreaterEqual(len(self.account.delegates), 0)
        with self.assertRaises(ErrorInvalidUserSid):
            list(GetDelegate(account=self.account).call(user_ids=[UserId(sid="XXX")], include_permissions=True))
        with self.assertRaises(ErrorDelegateNoUser):
            list(GetDelegate(account=self.account).call(user_ids=["*****@*****.**"], include_permissions=True))
        with self.assertRaises(ErrorNotDelegate):
            list(
                GetDelegate(account=self.account).call(
                    user_ids=[self.account.primary_smtp_address], include_permissions=True
                )
            )

        xml = b"""\
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <m:GetDelegateResponse ResponseClass="Success"
            xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
            xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
      <m:ResponseCode>NoError</m:ResponseCode>
      <m:ResponseMessages>
        <m:DelegateUserResponseMessageType ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:DelegateUser>
              <t:UserId>
                <t:SID>SOME_SID</t:SID>
                <t:PrimarySmtpAddress>[email protected]</t:PrimarySmtpAddress>
                <t:DisplayName>Foo Bar</t:DisplayName>
              </t:UserId>
              <t:DelegatePermissions>
                <t:CalendarFolderPermissionLevel>Author</t:CalendarFolderPermissionLevel>
                <t:InboxFolderPermissionLevel>Reviewer</t:ContactsFolderPermissionLevel>
              </t:DelegatePermissions>
              <t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>
            <t:ViewPrivateItems>true</t:ViewPrivateItems>
            </m:DelegateUser>
          </m:DelegateUserResponseMessageType>
      </m:ResponseMessages>
      <m:DeliverMeetingRequests>DelegatesAndMe</m:DeliverMeetingRequests>
      </m:GetDelegateResponse>
  </s:Body>
</s:Envelope>"""

        MockTZ = namedtuple("EWSTimeZone", ["ms_id"])
        MockAccount = namedtuple("Account", ["access_type", "primary_smtp_address", "default_timezone", "protocol"])
        MockProtocol = namedtuple("Protocol", ["version"])
        p = MockProtocol(version=Version(build=EXCHANGE_2007_SP1))
        a = MockAccount(DELEGATE, "*****@*****.**", MockTZ("XXX"), protocol=p)

        ws = GetDelegate(account=a)
        delegates = list(ws.parse(xml))
        self.assertListEqual(
            delegates,
            [
                DelegateUser(
                    user_id=UserId(sid="SOME_SID", primary_smtp_address="*****@*****.**", display_name="Foo Bar"),
                    delegate_permissions=DelegatePermissions(
                        calendar_folder_permission_level="Author",
                        inbox_folder_permission_level="Reviewer",
                        contacts_folder_permission_level="None",
                        notes_folder_permission_level="None",
                        journal_folder_permission_level="None",
                        tasks_folder_permission_level="None",
                    ),
                    receive_copies_of_meeting_messages=False,
                    view_private_items=True,
                )
            ],
        )