Passed
Push — main ( c39039...95ff57 )
by Alexander
01:40
created

TestMailboxCleanerIMAP.test_basics()   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""Module documentation goes here."""
5
6
7
import email
8
import imaplib
9
import unittest
10
from src.mailbox_imap import MailboxCleanerIMAP
11
from tests.test_mailbox_abstract import TestMailboxAbstract
12
13
14
class TestMailboxCleanerIMAP(TestMailboxAbstract, unittest.TestCase):
15
    """Class documentation goes here."""
16
    class _ImapMockup():
17
        def __init__(self):
18
            self.store = []
19
            test_input = 'tests/input/test.eml'
20
            with open(test_input) as filepointer:
21
                self.msg = email.message_from_file(filepointer)
22
23
        @staticmethod
24
        def setsockopt(_a, _b, _c):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
25
            pass
26
27
        @staticmethod
28
        def socket():
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
29
            return TestMailboxCleanerIMAP._ImapMockup
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _ImapMockup was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
30
31
        @staticmethod
32
        def login(user=None, _password=None):
33
            """Mocking login."""
34
            if user != 'test':
35
                raise imaplib.IMAP4.error('wrong username')
36
37
        @staticmethod
38
        def logout():
39
            """Mocking logout."""
40
            return ('OK', None)
41
42
        @staticmethod
43
        def close():
44
            """Mocking close."""
45
            return ('OK', None)
46
47
        @staticmethod
48
        def expunge():
49
            """Mocking expunge."""
50
            return ('OK', None)
51
52
        @staticmethod
53
        def select(_folder, readonly=True):
54
            """Mocking select."""
55
            return ('OK', readonly)
56
57
        def append(self, _folder, _flags, _date, msg):
58
            """Mocking append."""
59
            self.store.append(msg)
60
            return ('OK', None)
61
62
        @staticmethod
63
        def list():
64
            """Mocking list."""
65
            folders = [b'(\\Marked \\HasNoChildren) "/" Inbox',
66
                       b'(\\Marked \\HasChildren) "/" Archive',
67
                       b'(\\HasNoChildren) "/" "Archive/Test"']
68
            return ('OK',
69
                    folders)
70
71
        def uid(self, command, _a=None, query=None, _c=None):
72
            """Mocking uid."""
73
            result = 'OK'
74
            if command.lower() == 'search':
75
                if len(self.store) > 0 or query == "ALL":
76
                    data = [b'142627 142632 142633 142640 142641']
77
                else:
78
                    data = [b'']
79
            elif command.lower() == 'fetch':
80
                data = [(b'10 (UID 142684 BODY[] {2617453}',
81
                         self.msg.as_bytes()),
82
                        b' FLAGS (\\Seen \\Recent))']
83
            else:
84
                data = None
85
            return (result, data)
86
87
    def test_basics(self):
88
        """Testing basic class."""
89
90
        imap = MailboxCleanerIMAP(self.args)
91
        with self.assertRaises((ConnectionRefusedError,
92
                                SystemExit)):
93
            imap.login()
94
95
        imap._load_cache()  # pylint: disable=W0212
96
        imap.cleanup()
97
98
    def test_with_mockup(self):
99
        """Testing with mockup class."""
100
101
        mockup = self._ImapMockup()
102
        imap = MailboxCleanerIMAP(self.args, mockup)
103
        imap.process_folders()
104
        imap.login()
105
        imap.logout()
106
107
        self.args.user = 'invalid'
108
        with self.assertRaises(SystemExit):
109
            imap = MailboxCleanerIMAP(self.args, mockup)
110
            imap.login()
111
112
    def test_get_tags(self):
113
        """Testing flag extraction."""
114
115
        test_input = [(b'1 (RFC822 {242020}', b'\r\n'),
116
                      b' UID 142377 FLAGS (\\Seen \\Recent NotJunk)']
117
        test_output = MailboxCleanerIMAP.get_flags_from_struct(test_input)
118
        print("Result: ", test_output)
119
        self.assertTrue("Seen" in test_output)
120
        self.assertTrue("NotJunk" in test_output)
121
        self.assertFalse("Recent" in test_output)
122
123
    def test_convert_date(self):
124
        """Testing date conversion."""
125
126
        test_input = "Thu, 22 Oct 2020 12:38:26 +0200"
127
        test_output = MailboxCleanerIMAP.convert_date(test_input)
128
        test_expectation = '22-Oct-2020'
129
        print("Result: ", test_output)
130
        self.assertTrue(test_expectation in test_output)
131
132
    def test_struct(self):
133
        """Testing struct parser."""
134
135
        test_input = [(b'1 (RFC822 {242020}', b'\x80abc'),
136
                      b' UID 142377 FLAGS (\\Seen \\Recent NotJunk)']
137
        test_output = MailboxCleanerIMAP.get_msg_from_struct(test_input)
138
        test_output = test_output.as_string()
139
        test_expectation = 'abc'
140
        print("Result: '%s'" % test_output)
141
        self.assertTrue(test_expectation in test_output)
142
143
144
if __name__ == '__main__':
145
    unittest.main()
146