def test_bad_byte(self, arg):
     with pytest.raises(TypeError):
         PoolByteArray([arg])
     with pytest.raises(TypeError):
         PoolByteArray([1, 2, arg, 4])
     arr = PoolByteArray([1])
     with pytest.raises(TypeError):
         arr.append(arg)
     with pytest.raises(TypeError):
         arr.insert(1, arg)
     with pytest.raises(TypeError):
         arr.push_back(arg)
     with pytest.raises(TypeError):
         arr.insert(1, arg)
 def test_byte_overflow(self):
     with pytest.raises(ValueError):
         PoolByteArray([256])
     with pytest.raises(ValueError):
         PoolByteArray([1, 2, 256, 4])
     arr = PoolByteArray([1])
     with pytest.raises(ValueError):
         arr.append(256)
     with pytest.raises(ValueError):
         arr.insert(1, 256)
     with pytest.raises(ValueError):
         arr.push_back(256)
     with pytest.raises(ValueError):
         arr.insert(1, 256)
 def test_bad_instantiate(self, arg):
     with pytest.raises(TypeError):
         PoolByteArray(arg)
Ejemplo n.º 4
0
class TestArray:
    def test_base(self):
        v = Array()
        assert type(v) == Array

    def test_equal(self):
        arr = Array()
        other = Array()
        for item in [1, "foo", Node(), Vector2()]:
            arr.append(item)
            other.append(item)
        assert arr == other
        bad = Array([0, 0, 0])
        assert not arr == bad  # Force use of __eq__

    @pytest.mark.parametrize(
        "arg",
        [
            None,
            0,
            "foo",
            Vector2(),
            Node(),
            [1],
            Array([1, 2]),
            PoolByteArray([1]),
            PoolIntArray([1]),
        ],
    )
    def test_bad_equal(self, arg):
        arr = Array([1])
        assert arr != arg

    def test_add(self):
        arr = Array([None])
        arr += Array([1, "two"])  # __iadd__
        assert arr == Array([None, 1, "two"])
        arr2 = arr + Array([3])  # __add__
        assert arr2 == Array([None, 1, "two", 3])

    def test_add_with_non_array(self):
        arr = Array([0])
        arr += [1, "two"]  # __iadd__
        assert arr == Array([0, 1, "two"])
        arr2 = arr + [3]  # __add__
        assert arr2 == Array([0, 1, "two", 3])
        # Also test list's __iadd__
        arr3 = ["-1"]
        arr3 += arr
        assert arr3 == ["-1", 0, 1, "two"]
        # list.__add__ only works with other lists
        with pytest.raises(TypeError):
            ["-1"] + arr
        arr4 = ["-1"] + list(arr)
        assert arr4 == ["-1", 0, 1, "two"]

    @pytest.mark.parametrize("arg", [None, 0, "foo", Vector2(), Node()])
    def test_bad_add(self, arg):
        with pytest.raises(TypeError):
            assert Array() + arg

    def test_repr(self):
        v = Array()
        assert repr(v) == "<Array([])>"
        v = Array([1, "foo", Vector2()])
        assert repr(v) == "<Array([1, 'foo', <Vector2(x=0.0, y=0.0)>])>"

    @pytest.mark.parametrize("arg", [42, "dummy", Node(), Vector2(), [object()]])
    def test_bad_instantiate(self, arg):
        with pytest.raises(TypeError):
            Array(arg)

    @pytest.mark.parametrize(
        "arg",
        [
            Array(),
            PoolColorArray(),
            PoolVector3Array(),
            PoolVector2Array(),
            PoolStringArray(),
            PoolRealArray(),
            PoolIntArray(),
            PoolByteArray(),
            [],
            (),
            [42, 43, 44],
            ("foo", "bar", "spam"),
            (Node(), Resource(), Area2D()),
            [Vector2(), Vector2(), Vector2()],
            (Node(), Resource(), Area2D(), Vector2(), "foo", 0),  # Enjoy the mix
        ],
    )
    def test_instantiate_from_copy(self, arg):
        arr = Array(arg)
        if hasattr(arg, "_gd_ptr"):
            assert arr._gd_ptr != arg._gd_ptr

    @pytest.mark.parametrize(
        "args",
        [
            ["append", type(None), ("bar",)],
            ["clear", type(None), ()],
            ["count", int, ("foo",)],
            ["empty", bool, ()],
            ["erase", type(None), ("foo",)],
            ["front", str, ()],
            ["back", str, ()],
            ["find", int, ("foo", 0)],
            ["find_last", int, ("foo",)],
            ["has", bool, ("foo",)],
            ["hash", int, ()],
            ["insert", type(None), (0, "bar")],
            ["invert", type(None), ()],
            ["pop_back", str, ()],
            ["pop_front", str, ()],
            ["push_back", type(None), ("bar",)],
            ["push_front", type(None), ("bar",)],
            ["resize", type(None), (2,)],
            ["rfind", int, ("foo", 0)],
            ["sort", type(None), ()],
            # ['sort_custom', type(None), (obj, func)],
        ],
        ids=lambda x: x[0],
    )
    def test_methods(self, args):
        v = Array(["foo"])
        # Don't test methods' validity but bindings one
        field, ret_type, params = args
        assert hasattr(v, field)
        method = getattr(v, field)
        assert callable(method)
        ret = method(*params)
        assert type(ret) == ret_type

    def test_len(self):
        v = Array()
        assert len(v) == 0
        v.append("foo")
        assert len(v) == 1

    def test_getitem(self):
        v = Array(["foo", 0, Node(), 0.42])
        assert v[0] == "foo"
        assert v[1] == 0
        assert v[-1] == 0.42

    def test_getitem_slice(self):
        v = Array(["foo", 0, Node()])
        assert isinstance(v[:-1], Array)
        assert v[1:] == Array([v[1], v[2]])

    def test_outofrange_getitem(self):
        v = Array(["foo", 0])
        with pytest.raises(IndexError):
            v[2]

    def test_setitem(self):
        v = Array(["foo", 0, Node()])
        v[0] = "bar"
        assert len(v) == 3
        assert v[0] == "bar"
        v[-1] = 4
        assert len(v) == 3
        assert v[2] == 4

    def test_outofrange_setitem(self):
        v = Array(["foo", 0])
        with pytest.raises(IndexError):
            v[2] = 42

    def test_delitem(self):
        v = Array(["foo", 0, Node()])
        del v[0]
        assert len(v) == 2
        assert v[0] == 0
        del v[-1]
        assert len(v) == 1
        v[0] == 0

    def test_outofrange_delitem(self):
        v = Array(["foo", 0])
        with pytest.raises(IndexError):
            del v[2]

    def test_iter(self):
        items = ["foo", 0, Node()]
        v = Array(items)
        items_from_v = [x for x in v]
        assert items_from_v == items

    def test_append(self):
        items = [1, "foo", Node()]
        v = Array()
        for item in items:
            v.append(item)
        assert len(v) == 3
        assert v == Array(items)
Ejemplo n.º 5
0
class TestArray:
    def test_base(self):
        v = Array()
        assert type(v) == Array

    def test_equal(self):
        arr = Array()
        other = Array()
        for item in [1, 'foo', Node(), Vector2()]:
            arr.append(item)
            other.append(item)
        assert arr == other
        bad = Array([0, 0, 0])
        assert not arr == bad  # Force use of __eq__

    @pytest.mark.parametrize('arg', [
        None, 0, 'foo',
        Vector2(),
        Node(), [1],
        Array([1, 2]),
        PoolByteArray([1]),
        PoolIntArray([1])
    ])
    def test_bad_equal(self, arg):
        arr = Array([1])
        assert arr != arg

    def test_add(self):
        arr = Array([None])
        arr += Array([1, 'two'])  # __iadd__
        assert arr == Array([None, 1, 'two'])
        arr2 = arr + Array([3])  # __add__
        assert arr2 == Array([None, 1, 'two', 3])

    def test_add_with_non_array(self):
        arr = Array([0])
        arr += [1, 'two']  # __iadd__
        assert arr == Array([0, 1, 'two'])
        arr2 = arr + [3]  # __add__
        assert arr2 == Array([0, 1, 'two', 3])
        # Test __radd__ as well
        arr3 = ['-1'] + arr
        assert arr3 == Array(['-1', 0, 1, 'two'])

    @pytest.mark.parametrize('arg', [
        None,
        0,
        'foo',
        Vector2(),
        Node(),
    ])
    def test_bad_add(self, arg):
        with pytest.raises(TypeError):
            assert Array() + arg

    def test_repr(self):
        v = Array()
        assert repr(v) == '<Array([])>'
        v = Array([1, 'foo', Vector2()])
        assert repr(v) == "<Array([1, 'foo', <Vector2(x=0.0, y=0.0)>])>"

    @pytest.mark.parametrize(
        'arg',
        [42, 'dummy', Node(), Vector2(), [object()]])
    def test_bad_instantiate(self, arg):
        with pytest.raises(TypeError):
            Array(arg)

    @pytest.mark.parametrize(
        'arg',
        [
            Array(),
            PoolColorArray(),
            PoolVector3Array(),
            PoolVector2Array(),
            PoolStringArray(),
            PoolRealArray(),
            PoolIntArray(),
            PoolByteArray(),
            [],
            (),
            [42, 43, 44],
            ('foo', 'bar', 'spam'),
            (Node(), Resource(), Area2D()),
            [Vector2(), Vector2(), Vector2()],
            (Node(), Resource(), Area2D(), Vector2(), 'foo',
             0),  # Enjoy the mix
        ])
    def test_instantiate_from_copy(self, arg):
        arr = Array(arg)
        if hasattr(arg, '_gd_ptr'):
            assert arr._gd_ptr != arg._gd_ptr

    @pytest.mark.parametrize(
        'args',
        [
            ['append', type(None), ('bar', )],
            ['clear', type(None), ()],
            ['count', int, ('foo', )],
            ['empty', bool, ()],
            ['erase', type(None), ('foo', )],
            ['front', str, ()],
            ['back', str, ()],
            ['find', int, ('foo', 0)],
            ['find_last', int, ('foo', )],
            ['has', bool, ('foo', )],
            ['hash', int, ()],
            ['insert', type(None), (0, 'bar')],
            ['invert', type(None), ()],
            ['pop_back', str, ()],
            ['pop_front', str, ()],
            ['push_back', type(None), ('bar', )],
            ['push_front', type(None), ('bar', )],
            ['resize', type(None), (2, )],
            ['rfind', int, ('foo', 0)],
            ['sort', type(None), ()],
            # ['sort_custom', type(None), (obj, func)],
        ],
        ids=lambda x: x[0])
    def test_methods(self, args):
        v = Array(['foo'])
        # Don't test methods' validity but bindings one
        field, ret_type, params = args
        assert hasattr(v, field)
        method = getattr(v, field)
        assert callable(method)
        ret = method(*params)
        assert type(ret) == ret_type

    def test_len(self):
        v = Array()
        assert len(v) == 0
        v.append('foo')
        assert len(v) == 1

    def test_getitem(self):
        v = Array(['foo', 0, Node(), 0.42])
        assert v[0] == 'foo'
        assert v[1] == 0
        assert v[-1] == 0.42

    def test_getitem_slice(self):
        v = Array(['foo', 0, Node()])
        assert isinstance(v[:-1], Array)
        assert v[1:] == Array([v[1], v[2]])

    def test_outofrange_getitem(self):
        v = Array(['foo', 0])
        with pytest.raises(IndexError):
            v[2]

    def test_setitem(self):
        v = Array(['foo', 0, Node()])
        v[0] = 'bar'
        assert len(v) == 3
        assert v[0] == 'bar'
        v[-1] = 4
        assert len(v) == 3
        assert v[2] == 4

    def test_outofrange_setitem(self):
        v = Array(['foo', 0])
        with pytest.raises(IndexError):
            v[2] = 42

    def test_delitem(self):
        v = Array(['foo', 0, Node()])
        del v[0]
        assert len(v) == 2
        assert v[0] == 0
        del v[-1]
        assert len(v) == 1
        v[0] == 0

    def test_outofrange_delitem(self):
        v = Array(['foo', 0])
        with pytest.raises(IndexError):
            del v[2]

    def test_iter(self):
        items = ['foo', 0, Node()]
        v = Array(items)
        items_from_v = [x for x in v]
        assert items_from_v == items

    def test_append(self):
        items = [1, 'foo', Node()]
        v = Array()
        for item in items:
            v.append(item)
        assert len(v) == 3
        assert v == Array(items)
Ejemplo n.º 6
0
    def _read_mail(
            self, imap_host, imap_port, imap_user, imap_pass, imap_folder,
            eNum,
            imap_sent):  # reads the most recent email and parses the text
        ### Reading emails from the server. The bulk of the work is here
        ### We prosses an email, clean up the text, check if it is a reply
        ### Load the original email if it is a reply, and check for and load images
        try:
            if "gmail" in imap_host:  # gmail server requires an ssl connection
                imap = IMAP4_SSL(imap_host, imap_port)
            else:  # tls is preferred
                imap = IMAP4(imap_host, imap_port)
                imap.starttls()
            ## login to server
            imap.login(imap_user, imap_pass)
        except:
            print("Failed to login")
            return
        #print(imap.list()) # for identifying mailboxes on the server
        imap.select("Inbox")  # connect to all mail.
        result, data = imap.uid('search', None,
                                "ALL")  # search and return uids instead
        ids = data[0]  # data is a list.
        id_list = ids.split()  # ids is a space separated string
        latest_email_uid = data[0].split()[eNum]
        result, data = imap.uid(
            'fetch', latest_email_uid, '(RFC822)'
        )  # fetch the email headers and body (RFC822) for the given ID
        raw_email = data[0][
            1]  # here's the body, which is raw headers and html and body of the whole email
        b = email.message_from_bytes(raw_email)
        date = b['Date']
        email_subject = b['subject']
        email_from = b['from']
        email_inreply = b['in-reply-to']
        email_body = b.get_payload()
        if b.is_multipart():  # search for text in the body
            for part in b.walk():
                ctype = part.get_content_type()
                cdispo = str(part.get('Content-Disposition'))
                if ctype == ('text/plain'
                             or 'text/html') and 'attachment' not in cdispo:
                    email_body = part.get_payload()
                    #print(email_body)
                    break
        frm = BeautifulSoup(email_from, 'html.parser')
        sub = BeautifulSoup(email_subject, 'html.parser')
        try:  # Try parsing the body text
            body = BeautifulSoup(email_body, 'html.parser')
        except:  # if email is encrypted it will throw an exception
            body = encription_warning
            #print(b['subject'])
            #print(b.keys())
        '''
		text = text.strip('\\t')
		text = text.replace('\\n', ' \n ')
		'''
        if email_inreply != "None":  # if this email is a reply
            try:
                if "gmail" in imap_host:
                    sent = IMAP4_SSL(imap_host, imap_port)
                else:
                    sent = IMAP4(imap_host, imap_port)
                    sent.starttls()
                ## login to server
                sent.login(imap_user, imap_pass)
                if "gmail" in imap_host:
                    sent.select('"[Gmail]/Sent Mail"')  # connect to sent mail.
                    #print("Opening gmail 'Sent'")
                else:
                    sent.select('Sent')  # connect to sent mail.
                    #print("Opening 'Sent'")
                # Search for the original email ID
                messages = sent.search(None, 'HEADER', 'MESSAGE-ID',
                                       email_inreply)
                # Process the result to get the message id’s
                messages = messages[1][0].split()
                # Use the first id to view the headers for a message
                result, source_data = sent.fetch(messages[0], '(RFC822)')
                raw_source = source_data[0][
                    1]  # here's the body, which is raw headers and html and body of the whole email
                s = email.message_from_bytes(
                    raw_source)  # convert to message object
                source_subject = s['subject']
                source_date = s['Date']
                source_bcc = s['bcc']
                #print("BCC from source: ", source_bcc)
                source_body = s.get_payload(decode=True)
                #print(frm, " Sent a reply to: ", source_subject)
                self.get_parent().msgIsReply = True
                src_sub = BeautifulSoup(source_subject, 'html.parser')
                try:  # extra check for encryption (in case user has encypted email)
                    src_body = BeautifulSoup(source_body, 'html.parser')
                except:  # if email is encrypted it will throw an exception
                    src_body = encription_warning
                self.get_parent().originSub = src_sub.get_text()
                self.get_parent().originBody = src_body.get_text()
                self.get_parent().originDate = src_date
                self.get_parent().originbcc = src_bcc
            except:
                print("No origin found")
        self.get_parent().msgFrom = frm.get_text()
        #print(frm.contents)
        add1 = re.findall("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)",
                          str(frm))
        self.get_parent().msgEmail = add1[0]
        self.get_parent().msgSubject = sub.get_text()
        if body != encription_warning:
            body = body.get_text()
        self.get_parent().msgBody = body
        self.get_parent().msgDate = date
        self.get_parent()._print_mail()
        for part in b.walk():  # Check for image attachments
            ctype = part.get_content_type()
            if ctype in ['image/jpeg', 'image/png']:
                by = bytearray(part.get_payload(decode=True))
                #print(by[0])
                pool = PoolByteArray(by)  # create a Godot PoolByteArray
                self.get_parent().add_image(pool)  #Pass it to the mail fetcher