Debian Codegraph @

tests/all/property_test.rs

raw symbols SCIP
1 use ::proptest::prelude::*;
2 use comfy_table::{ColumnConstraint::*, Width::*, *};
3
4 /// Pick any of the three existing ContentArrangement types for the table.
5 fn content_arrangement() -> impl Strategy<Value = ContentArrangement> {
6 prop_oneof![
7 Just(ContentArrangement::Disabled),
8 Just(ContentArrangement::Dynamic),
9 Just(ContentArrangement::DynamicFullWidth),
10 ]
11 }
12
13 /// Each cell can have any alignment.
14 fn cell_alignment() -> impl Strategy<Value = Option<CellAlignment>> {
15 prop_oneof![
16 Just(None),
17 Just(Some(CellAlignment::Left)),
18 Just(Some(CellAlignment::Right)),
19 Just(Some(CellAlignment::Center)),
20 ]
21 }
22
23 /// Any Column can have any constellation of ColumnConstraints
24 fn column_constraint() -> impl Strategy<Value = Option<ColumnConstraint>> {
25 prop_oneof![
26 Just(None),
27 Just(Some(ColumnConstraint::ContentWidth)),
28 Just(Some(ColumnConstraint::Hidden)),
29 any::<u16>().prop_map(|width| { Some(Absolute(Fixed(width))) }),
30 any::<u16>().prop_map(|width| { Some(LowerBoundary(Fixed(width))) }),
31 any::<u16>().prop_map(|width| { Some(UpperBoundary(Fixed(width))) }),
32 (0u16..200u16).prop_map(|percentage| { Some(Absolute(Percentage(percentage))) }),
33 (0u16..200u16).prop_map(|percentage| { Some(LowerBoundary(Percentage(percentage))) }),
34 (0u16..200u16).prop_map(|percentage| { Some(UpperBoundary(Percentage(percentage))) }),
35 ]
36 }
37
38 /// We test the Row::max_height with a few values.
39 fn max_height() -> impl Strategy<Value = Option<usize>> {
40 prop_oneof![
41 Just(None),
42 Just(Some(0)),
43 Just(Some(1)),
44 Just(Some(5)),
45 Just(Some(100))
46 ]
47 }
48
49 prop_compose! {
50 /// Returns the dimensions of the table, i.e. the amount of rows and columns.
51 fn dimensions()(columns in 1u16..10u16, rows in 1u16..10u16)
52 -> (u16, u16) {
53 (columns, rows)
54 }
55 }
56
57 /// Returns all data needed to build the final table.
58 /// 1. A matrix of cells Row[Column[Cell]].
59 /// 2. Constraints for all columns.
60 /// 3. The alignment for each cell.
61 /// 3. The alignment for each column.
62 #[allow(clippy::type_complexity)]
63 fn columns_and_rows() -> impl Strategy<
64 Value = (
65 Vec<Vec<String>>,
66 Vec<Option<ColumnConstraint>>,
67 Vec<Option<CellAlignment>>,
68 Vec<Option<CellAlignment>>,
69 ),
70 > {
71 dimensions().prop_flat_map(|(column_count, row_count)| {
72 let mut rows = Vec::new();
73 let mut cell_alignments = Vec::new();
74 for _i in 0..row_count {
75 // Create the max amount of possibly needed cell alignments
76 for _j in 0..column_count {
77 cell_alignments.push(cell_alignment());
78 }
79 // Add a strategy that creates random cell content with a length of 0 to column_count
80 //
81 // UTF-8 characters completely break table alignment in edge-case situations (e.g. 1
82 // space columns). UTF-8 characters can be multiple characters wide, which
83 // conflicts with the 1 space column fallback, as well as fixed-width-,
84 // percental- and max-column-constraints. As a result, we cannot check this
85 // with proptest, as this is inherently broken.
86 rows.push(::proptest::collection::vec(
87 "[A-Za-z_]*",
88 0..column_count as usize,
89 ));
90 }
91 let mut constraints = Vec::new();
92 let mut column_alignments = Vec::new();
93 for _i in 0..column_count {
94 constraints.push(column_constraint());
95 column_alignments.push(cell_alignment());
96 }
97
98 (rows, constraints, cell_alignments, column_alignments)
99 })
100 }
101
102 /// We test the Row::max_height with a few values.
103 fn table_width() -> impl Strategy<Value = u16> {
104 0..1000u16
105 }
106
107 prop_compose! {
108 /// The ultimate test
109 /// This creates a table from a combination of all "random" selectors above.
110 fn table()
111 (arrangement in content_arrangement(),
112 max_height in max_height(),
113 (rows, constraints, cell_alignments, column_alignments) in columns_and_rows()) -> Table {
114
115 let mut table = Table::new();
116 if let Some(height) = max_height {
117 for row in table.row_iter_mut() {
118 row.max_height(height);
119 }
120 }
121
122 let mut cell_alignments = cell_alignments.iter();
123 for row in rows.iter() {
124 // Convert a vector of Strings to a vector of Cells and
125 // set the content alignment for each cell
126 let row: Vec<Cell> = row.iter().map(|content| {
127 let mut cell = Cell::new(content.clone());
128 if let Some(alignment) = cell_alignments.next().unwrap() {
129 cell = cell.set_alignment(*alignment);
130 }
131 cell
132 }).collect();
133
134 // Add the row to the table
135 table.add_row(row);
136 }
137
138 for (column_index, column) in table.column_iter_mut().enumerate() {
139 // Add the alignment for all columns
140 let alignment = column_alignments.get(column_index).unwrap();
141 if let Some(alignment) = alignment {
142 column.set_cell_alignment(*alignment);
143 }
144
145 // Set constraints for all columns
146 let constraint = constraints.get(column_index).unwrap();
147 if let Some(constraint) = constraint {
148 column.set_constraint(*constraint);
149 }
150
151 }
152
153 table.set_content_arrangement(arrangement);
154 table
155 }
156 }
157
158 proptest! {
159 #![proptest_config({
160 let mut config = ProptestConfig::with_cases(512);
161 config.max_shrink_iters = 5000;
162 config
163 })]
164 #[test]
165 fn random_tables(mut table in table(), table_width in table_width()) {
166 table.set_width(table_width);
167
168 // Make sure the table builds without any panics
169 let formatted = table.to_string();
170
171 // We'll take a look at each individual line to ensure they all share some properties.
172 let lines: Vec<String> = formatted.split_terminator('\n').map(|line| line.to_owned()).collect();
173 let mut line_iter = lines.iter();
174
175 // ----- Table width check ------
176
177 // Get the length of the very first line.
178 // We're lateron going to ensure, that all lines have the same length.
179 let line_length = if let Some(line) = line_iter.next() {
180 line.trim().len()
181 } else {
182 0
183 };
184
185 // Make sure all lines have the same length
186 for line in line_iter {
187 if line.len() != line_length {
188 return build_error(&formatted, "Each line of a printed table has to have the same length!");
189 }
190 }
191
192 // Make sure that the table is within its width, if arrangement isn't enabled.
193 // This is a bit tricky.
194 // A table can be larger than the specified width, if the user forces it to be larger.
195 #[cfg(feature = "_integration_test")]
196 {
197 let current_arrangement = table.content_arrangement();
198 match current_arrangement {
199 ContentArrangement::Disabled => (),
200 _ => {
201 let expected_max = determine_max_table_width(&table);
202
203 // A line can be a bit longer than u16::MAX due to formatting and borders.
204 let actual: u16 = line_length.try_into().unwrap_or(u16::MAX);
205 if actual > expected_max {
206 return build_error(
207 &formatted,
208 &format!("Expected table to be smaller than line length!\n\
209 Actual: {actual}, Expected max: {expected_max}\n\
210 Arrangement: {current_arrangement:?}"
211 ));
212 }
213 }
214 }
215 }
216
217 #[cfg(feature = "_integration_test")]
218 // Only run this test, if the `integration_test` is enabled.
219 // Without this flag, we don't have access to some util functions in comfy_table, that
220 // aren't exposed by default.
221 enforce_constraints(&table, formatted, lines)?
222 }
223 }
224
225 fn build_error(table: &str, context: &str) -> Result<(), TestCaseError> {
226 Err(TestCaseError::Fail(
227 format!("\n{context}:\n{table}\n").into(),
228 ))
229 }
230
231 /// The user can actually force a table to be longer than the specified `table.width()`
232 /// by specifying [ColumnConstraint]s.
233 #[cfg(feature = "_integration_test")]
234 fn determine_max_table_width(table: &Table) -> u16 {
235 use comfy_table::utils::arrangement::helper::count_border_columns;
236 let table_width = table.width().unwrap();
237
238 // The max value that will be enforced by constraints.
239 // We start with `2` for the side borders.
240 let visible_columns = table
241 .column_iter()
242 .filter(|column| !column.is_hidden())
243 .count();
244
245 // Initialize the value for the min width enforced by constraints.
246 // Borders may exist, but they are not included in constraints, which is why we have to
247 // explicitly add them.
248 let mut constraint_min_width: u16 = count_border_columns(table, visible_columns)
249 .try_into()
250 .unwrap_or(u16::MAX);
251
252 // Get the max content widths for each column.
253 // This is necessary for the `ContentWidth` constraint.
254 let max_content_widths = table.column_max_content_widths();
255
256 // Calculate the enforced widths by any constraints.
257 for (index, column) in table.column_iter().enumerate() {
258 if let Some(constraint) = column.constraint() {
259 match constraint {
260 ColumnConstraint::ContentWidth => {
261 constraint_min_width = constraint_min_width
262 .saturating_add(max_content_widths[index])
263 .saturating_add(column.padding_width());
264 }
265 ColumnConstraint::Absolute(width) => {
266 constraint_min_width = constraint_min_width
267 .saturating_add(absolute_width(table, width))
268 .saturating_add(column.padding_width());
269 }
270 ColumnConstraint::LowerBoundary(width)
271 | ColumnConstraint::Boundaries { lower: width, .. } => {
272 constraint_min_width = constraint_min_width
273 .saturating_add(absolute_width(table, width))
274 .saturating_add(column.padding_width());
275 }
276 ColumnConstraint::Hidden => {}
277 _ => {
278 // Add the padding and the min-width of `1` for this column
279 constraint_min_width = constraint_min_width
280 .saturating_add(column.padding_width())
281 .saturating_add(1);
282 }
283 }
284 } else {
285 // Add the padding + 1 space for all columns without constraints.
286 constraint_min_width = constraint_min_width
287 .saturating_add(column.padding_width())
288 .saturating_add(1);
289 }
290 }
291
292 std::cmp::max(table_width, constraint_min_width)
293 }
294
295 /// Enforce that Column constraints are enforced as expected in `Dynamic` mode.
296 #[cfg(feature = "_integration_test")]
297 fn enforce_constraints(
298 table: &Table,
299 formatted: String,
300 lines: Vec<String>,
301 ) -> Result<(), TestCaseError> {
302 let content_arrangement = table.content_arrangement();
303 // Don't run the following for disabled or full-width arrangement.
304 // These constraints kind of mess with all kinds of assertions we can make, which is why we
305 // skip them.
306 match content_arrangement {
307 ContentArrangement::Dynamic => (),
308 _ => return Ok(()),
309 }
310
311 // Extract the constraints for each table
312 // Also remove hidden columns
313 let constraints: Vec<Option<ColumnConstraint>> = table
314 .column_iter()
315 .map(|col| col.constraint().cloned())
316 .filter(|constraint| !matches!(constraint, Some(ColumnConstraint::Hidden)))
317 .collect();
318
319 let line_iter = lines.iter();
320
321 for line in line_iter {
322 // Split the line along the column delimiter.
323 // This allows us to ensure that each column is inside its constraints.
324 let line_parts: Vec<String> = line.split('|').map(|col| col.to_string()).collect();
325
326 // Skip the line if there're fewer vertical delimiters than columns + borders.
327 // If that's the case, we're currently looking at a border or a delimiter line.
328 if line_parts.len() < (constraints.len() + 2) {
329 continue;
330 }
331
332 // The left and right borders will produce empty strings, let's filter those out.
333 let line_parts: Vec<String> = line_parts
334 .into_iter()
335 .filter(|part| !part.is_empty())
336 .collect();
337
338 for (index, (part, constraint)) in line_parts.iter().zip(constraints.iter()).enumerate() {
339 let constraint = match constraint {
340 Some(constraint) => constraint,
341 // No constraint, we're good to go.
342 None => continue,
343 };
344 // Get the actual length of the part.
345 let actual = part.len();
346
347 match constraint {
348 ColumnConstraint::Hidden => panic!("This shouldn't happen"),
349 // No need to check, if the column can be as wide as the content.
350 ColumnConstraint::ContentWidth => continue,
351 // Absolute width is defined.
352 ColumnConstraint::Absolute(absolute) => {
353 let mut expected = absolute_width(table, absolute);
354 // The minimal amount of chars per column (with default padding)
355 // is 3 chars. 2 padding + 1 char content.
356 if expected < 3 {
357 expected = 3;
358 }
359 if actual != expected.into() {
360 return build_error(
361 &formatted,
362 &format!(
363 "Column {index} for should have absolute width of {expected}.\n\
364 Actual width is {actual}.\n\
365 {absolute:?} for line '{line}', part '{part}'"
366 ),
367 );
368 }
369 }
370 ColumnConstraint::LowerBoundary(lower) => {
371 let expected_lower = absolute_width(table, lower);
372 if actual < expected_lower.into() {
373 return build_error(
374 &formatted,
375 &format!(
376 "Column {index} has a lower bound of {expected_lower}.\n\
377 Actual width is {actual}.\n\
378 {lower:?} for line '{line}', part '{part}'"
379 ),
380 );
381 }
382 }
383 ColumnConstraint::UpperBoundary(upper) => {
384 let mut expected_upper = absolute_width(table, upper);
385 // The minimal amount of chars per column (with default padding)
386 // is 3 chars. 2 padding + 1 char content.
387 if expected_upper < 3 {
388 expected_upper = 3;
389 }
390
391 if actual > expected_upper.into() {
392 return build_error(
393 &formatted,
394 &format!(
395 "Column {index} has a upper bound of {expected_upper}.\n\
396 Actual width is {actual}.\n\
397 {upper:?} for line '{line}', part '{part}'"
398 ),
399 );
400 }
401 }
402 ColumnConstraint::Boundaries { lower, upper } => {
403 let expected_lower = absolute_width(table, lower);
404 let mut expected_upper = absolute_width(table, upper);
405 // The minimal amount of chars per column (with default padding)
406 // is 3 chars. 2 padding + 1 char content.
407 if expected_upper < 3 {
408 expected_upper = 3;
409 }
410
411 if actual < expected_lower.into() {
412 return build_error(
413 &formatted,
414 &format!(
415 "Column {index} has a lower bound of {expected_lower}.\n\
416 Actual width is {actual}.\n\
417 {lower:?} for line '{line}', part '{part}'"
418 ),
419 );
420 }
421
422 if actual > expected_upper.into() {
423 return build_error(
424 &formatted,
425 &format!(
426 "Column {index} has a upper bound of {expected_upper}.\n\
427 Actual width is {actual}.\n\
428 {upper:?} for line '{line}', part '{part}'"
429 ),
430 );
431 }
432 }
433 }
434 }
435 }
436
437 Ok(())
438 }
439
440 /// Resolve an absolute value from a given boundary
441 #[cfg(feature = "_integration_test")]
442 pub fn absolute_width(table: &Table, width: &Width) -> u16 {
443 use comfy_table::utils::arrangement::constraint::absolute_value_from_width;
444
445 let visible_columns = table
446 .column_iter()
447 .filter(|column| !column.is_hidden())
448 .count();
449
450 let computed_width = absolute_value_from_width(table, width, visible_columns)
451 .expect("Expected table to have a width");
452
453 std::cmp::max(1, computed_width)
454 }