|
1
|
|
|
import unittest |
|
|
|
|
|
|
2
|
|
|
|
|
3
|
|
|
from collections import namedtuple |
|
4
|
|
|
from operator import attrgetter, itemgetter |
|
5
|
|
|
|
|
6
|
|
|
from foil.order import partition_ordered, partition |
|
7
|
|
|
|
|
8
|
|
|
MockTuple = namedtuple('MockTuple', ('a', 'b')) |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
def is_even(x): |
|
|
|
|
|
|
12
|
|
|
return True if x % 2 == 0 else False |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
|
|
class TestPartitionOrdered(unittest.TestCase): |
|
16
|
|
|
|
|
17
|
|
|
def test_partition_by_attribute(self): |
|
18
|
|
|
|
|
19
|
|
|
data = [{'a': 5, 'b': 8}, {'a': 5, 'b': 7}, {'a': 4, 'b': 4}] |
|
20
|
|
|
tups = [MockTuple(**d) for d in data] |
|
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
expected = [(5, [MockTuple(a=5, b=8), MockTuple(a=5, b=7)]), |
|
23
|
|
|
(4, [MockTuple(a=4, b=4)])] |
|
24
|
|
|
result = list(partition_ordered(tups, key=attrgetter('a'))) |
|
25
|
|
|
|
|
26
|
|
|
self.assertSequenceEqual(expected, result) |
|
27
|
|
|
|
|
28
|
|
|
def test_partition_by_item(self): |
|
29
|
|
|
data = ['123', '234', '221', '210', '780', '822'] |
|
30
|
|
|
|
|
31
|
|
|
expected = [('1', ['123']), |
|
32
|
|
|
('2', ['234', '221', '210']), |
|
33
|
|
|
('7', ['780']), |
|
34
|
|
|
('8', ['822'])] |
|
35
|
|
|
result = list(partition_ordered(data, key=itemgetter(0))) |
|
36
|
|
|
|
|
37
|
|
|
self.assertEqual(expected, result) |
|
38
|
|
|
|
|
39
|
|
|
|
|
40
|
|
|
class TestPartition(unittest.TestCase): |
|
41
|
|
|
def test_partition(self): |
|
42
|
|
|
expected_true = [0, 2] |
|
43
|
|
|
expected_false = [1, 3] |
|
44
|
|
|
result_false, result_true = partition(is_even, range(0, 4)) |
|
45
|
|
|
|
|
46
|
|
|
self.assertEqual(expected_true, list(result_true)) |
|
47
|
|
|
self.assertEqual(expected_false, list(result_false)) |
|
48
|
|
|
|
|
49
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.