test_array.py 2.13 KB
Newer Older
1
2
3
4
5
from dlib import array
try:
    import cPickle as pickle  # Use cPickle on Python 2.7
except ImportError:
    import pickle
Davis King's avatar
Davis King committed
6
7
8
9
10
11

try:
    from types import FloatType
except ImportError:
    FloatType = float

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
from pytest import raises


def test_array_init_with_number():
    a = array(5)
    assert len(a) == 5
    for i in range(5):
        assert a[i] == 0
        assert type(a[i]) == FloatType


def test_array_init_with_negative_number():
    with raises(MemoryError):
        array(-5)


def test_array_init_with_zero():
    a = array(0)
    assert len(a) == 0


def test_array_init_with_list():
    a = array([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType


def test_array_init_with_empty_list():
    a = array([])
    assert len(a) == 0


def test_array_init_without_argument():
    a = array()
    assert len(a) == 0


def test_array_init_with_tuple():
    a = array((0, 1, 2, 3, 4))
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType


def test_array_serialization_empty():
    a = array()
    # cPickle with protocol 2 required for Python 2.7
    # see http://pybind11.readthedocs.io/en/stable/advanced/classes.html#custom-constructors
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser


def test_array_serialization():
    a = array([0, 1, 2, 3, 4])
    ser = pickle.dumps(a, 2)
    deser = pickle.loads(ser)
    assert a == deser


def test_array_extend():
    a = array()
    a.extend([0, 1, 2, 3, 4])
    assert len(a) == 5
    for idx, val in enumerate(a):
        assert idx == val
        assert type(val) == FloatType


def test_array_string_representations_empty():
    a = array()
    assert str(a) == ""
    assert repr(a) == "array[]"


def test_array_string_representations():
    a = array([1, 2, 3])
    assert str(a) == "1\n2\n3"
    assert repr(a) == "array[1, 2, 3]"


def test_array_clear():
    a = array(10)
    a.clear()
    assert len(a) == 0


def test_array_resize():
    a = array(10)
    a.resize(100)
    assert len(a) == 100

    for i in range(100):
        assert a[i] == 0