File: test_utils.py

package info (click to toggle)
isbg 2.3.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 468 kB
  • sloc: python: 1,906; makefile: 108; sh: 24
file content (151 lines) | stat: -rw-r--r-- 5,472 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_utils.py
#  This file is part of utils.
#
#  Copyright 2018 Carles Muñoz Gorriz <carlesmu@internautas.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.

"""Test cases for utils module."""

import os
import sys

try:
    import pytest
except ImportError:
    pass

# We add the upper dir to the path
sys.path.insert(0, os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..')))
from isbg import utils  # noqa: E402


def test_detect_enc():
    """Test the detenct_enc function."""
    assert 'encoding' in utils.detect_enc(b"foo")
    assert 'encoding' in utils.detect_enc(b"")


def test_hexof_dehexof():
    """Test the dehexof function."""
    dehex = utils.dehexof("50402A")
    assert dehex == "P@*"
    assert utils.hexof(dehex) == "50402a"
    with pytest.raises(ValueError,
                       match=repr("G") + " is not a valid hexadecimal digit"):
        utils.dehexof("G")
        pytest.fail("Not error or unexpected error message")
    dehex = utils.dehexof("50402a")
    assert dehex == "P@*"
    assert utils.hexof(dehex) == "50402a"


def test_get_ascii_or_value():
    """Test get_ascii_or_value."""
    ret = utils.get_ascii_or_value(b'IMAP Spam Begone')
    assert ret == u'IMAP Spam Begone', 'should return IMAP Spam Begone'
    ret = utils.get_ascii_or_value(u'IMAP Spam Begone')
    assert ret == u'IMAP Spam Begone', 'should return IMAP Spam Begone'
    ret = utils.get_ascii_or_value('IMAP Spam Begone')
    assert ret == u'IMAP Spam Begone', 'should return IMAP Spam Begone'
    ret = utils.get_ascii_or_value(22)
    assert ret == 22, 'should return 22 (int)'

    d = {'isbg': (u'IMAP', [b'Spam', r'Begone'])}
    ret = utils.get_ascii_or_value(d)
    assert ret == {u'isbg': (u'IMAP', [u'Spam', u'Begone'])}, 'error'


def test_score_from_mail():
    """Test score_from_mail."""
    # Without score:
    fmail = open('tests/examples/spam.eml', 'rb')
    ftext = fmail.read()
    fmail.close()
    with pytest.raises(AttributeError):
        ret = utils.score_from_mail(ftext.decode(errors='ignore'))
        pytest.fail("Should rise AttributeError.")
    # With score:
    fmail = open('tests/examples/spam.from.spamassassin.eml', 'rb')
    ftext = fmail.read()
    fmail.close()
    ret = utils.score_from_mail(ftext.decode(errors='ignore'))
    assert ret == u"6.4/5.0\n", "Unexpected score."


def test_shorten():
    """Test the shorten function."""
    # We try with dicts:
    dic = {1: 'Option 1', 2: u'Option 2', 3: b'Option 3'}
    assert dic == utils.shorten(dic, 8), "The dicts should be the same."
    dic2 = utils.shorten(dic, 7)
    assert dic != dic2, "The dicts should be diferents."
    assert dic2[1] in ['u\'Opti…', '\'Optio…'], "Unexpected shortened string."
    assert dic2[2] in ['u\'Opti…', '\'Optio…'], "Unexpected shortened string."
    assert dic2[3] in ['\'Optio…', 'b\'Opti…'], "Unexpected shortened string."

    # We try with lists:
    ls = ['Option 1', 'Option 2', 'Option 3']
    assert ls == utils.shorten(ls, 8)
    ls2 = utils.shorten(ls, 7)
    for k in ls2:
        assert k in ['u\'Opti…', '\'Optio…'], "Unexpected shortened string."

    # We try with strings:
    assert "Option 1" == utils.shorten("Option 1", 8), \
        "Strings should be the same."
    assert utils.shorten("Option 1", 7) in ['u\'Opti…', "\'Optio…"], \
        "Strings should be diferents."

    # Others:
    with pytest.raises(TypeError):
        utils.shorten(None, 8)
        pytest.fail("None should raise a TypeError.")
    with pytest.raises(TypeError):
        utils.shorten(None, 7)
        pytest.fail("None should raise a TypeError.")
    with pytest.raises(TypeError):
        utils.shorten(False, 8)
        pytest.fail("None should raise a TypeError.")
    with pytest.raises(TypeError):
        utils.shorten(True, 7)
        pytest.fail("None should raise a TypeError.")
    with pytest.raises(TypeError):
        utils.shorten(1, 7)
        pytest.fail("int should raise a TypeError.")
    with pytest.raises(TypeError):
        utils.shorten(1.0, 7)
        pytest.fail("float should raise a TypeError.")
    with pytest.raises(ValueError):
        utils.shorten("123", 0)
        pytest.fail("length should be at least 1.")
    with pytest.raises(TypeError):
        assert utils.shorten([1, 2, 3], 2)
        pytest.fail("int should be not supported.")
    assert utils.shorten(["111", "2", "3"], 3) == ["111", "2", "3"]
    assert utils.shorten(("111", "2", "3"), 3) == ("111", "2", "3")


def test_BraceMessage():
    """Test BraceMessage."""
    ret = utils.BraceMessage("Test {} {}".format(1, "is one."))
    assert str(ret) == "Test 1 is one."
    ret = utils.__("Test {} {}".format(1, "is one."))
    assert str(ret) == "Test 1 is one."