7
7
import pytest
8
8
9
9
import tableformatter as tf
10
+ from collections import namedtuple
10
11
11
12
# Make the test results reproducible regardless of what color libraries are installed
12
13
tf .TableColors .set_color_library ('none' )
@@ -26,11 +27,19 @@ def get_field3(self):
26
27
return self ._field3
27
28
28
29
30
+ NamedTupleRow = namedtuple ('NamedTupleRow' , 'field1,field2,field3,field4' )
31
+ """Example named tuple to demonstrate usage with TableFormatter"""
32
+
33
+
29
34
def multiply (row_obj : MyRowObject ):
30
35
"""Demonstrates an object formatter function"""
31
36
return str (row_obj .get_field3 () * row_obj .field4 )
32
37
33
38
39
+ def multiply_named_tuple (row_job ):
40
+ return str (row_job .field3 * row_job .field4 )
41
+
42
+
34
43
def multiply_tuple (row_obj ):
35
44
"""Demonstrates an object formatter function"""
36
45
return str (row_obj [2 ] * row_obj [3 ])
@@ -117,6 +126,38 @@ def test_obj_rows():
117
126
assert table == expected
118
127
119
128
129
+ def test_namedtuple_rows ():
130
+ expected = '''
131
+ ╔══════════════════════╤════════╤═════╤═══════╤════════════╗
132
+ ║ │ │ Num │ │ ║
133
+ ║ First │ Second │ 1 │ Num 2 │ Multiplied ║
134
+ ╠══════════════════════╪════════╪═════╪═══════╪════════════╣
135
+ ║ RLonger text that │ RA2 │ R5 │ R56 │ R280 ║
136
+ ║ Rwill trigger the │ │ │ │ ║
137
+ ║ Rcolumn wrapping │ │ │ │ ║
138
+ ║ GB1 │ GB2 │ G23 │ G8 │ G184 ║
139
+ ║ │ GB2 │ │ │ ║
140
+ ║ │ GB2 │ │ │ ║
141
+ ║ C1 │ C2 │ 4 │ 9 │ 36 ║
142
+ ║ D1 │ D2 │ 7 │ 5 │ 35 ║
143
+ ╚══════════════════════╧════════╧═════╧═══════╧════════════╝
144
+ ''' .lstrip ('\n ' )
145
+ rows = [tf .Row (NamedTupleRow ('Longer text that will trigger the column wrapping' , 'A2' , 5 , 56 ),
146
+ text_color = 'R' ),
147
+ tf .Row (NamedTupleRow ('B1' , 'B2\n B2\n B2' , 23 , 8 ),
148
+ text_color = 'G' ),
149
+ NamedTupleRow ('C1' , 'C2' , 4 , 9 ),
150
+ NamedTupleRow ('D1' , 'D2' , 7 , 5 )]
151
+
152
+ columns = (tf .Column ('First' , width = 20 , attrib = 'field1' ),
153
+ tf .Column ('Second' , attrib = 'field2' ),
154
+ tf .Column ('Num 1' , width = 3 , attrib = 'field3' ),
155
+ tf .Column ('Num 2' , attrib = 'field4' ),
156
+ tf .Column ('Multiplied' , obj_formatter = multiply_named_tuple ))
157
+ table = tf .generate_table (rows , columns )
158
+ assert table == expected
159
+
160
+
120
161
def test_tuple_rows ():
121
162
expected = '''
122
163
╔══════════════════════╤════════╤═══════╤═══════════╤════════════╗
0 commit comments