evp 1.0.0-beta.4

Library to work with evidence packages (*.evp).
Documentation
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use markdown::{ParseOptions, mdast::Node};
use rust_xlsxwriter::{Format, FormatBorder, Image, Note, Workbook, Worksheet};
use uuid::Uuid;

use crate::prelude::{Error, EvidencePackage, Result as EVPResult, TestCase, TestCasePassStatus};

use super::Exporter;

/// An exporter to an Excel document.
#[derive(Default)]
pub struct ExcelExporter;

impl Exporter for ExcelExporter {
    fn export_name() -> String {
        "Excel Workbook".to_string()
    }

    fn export_extension() -> String {
        ".xlsx".to_string()
    }

    fn export_package(
        &mut self,
        package: &mut EvidencePackage,
        path: std::path::PathBuf,
    ) -> EVPResult<()> {
        let mut workbook = Workbook::new();
        workbook.read_only_recommended();

        create_metadata_sheet(workbook.add_worksheet(), package)
            .map_err(Error::OtherExportError)?;

        create_summary_sheet(workbook.add_worksheet(), package).map_err(Error::OtherExportError)?;

        let test_cases: Vec<&TestCase> = package.test_case_iter()?.collect();
        for test_case in test_cases {
            let worksheet = workbook.add_worksheet();
            create_test_case_sheet(worksheet, package.clone(), test_case)
                .map_err(Error::OtherExportError)?;
        }

        workbook
            .save(path)
            .map_err(|e| Error::OtherExportError(e.into()))?;

        Ok(())
    }

    fn export_case(
        &mut self,
        package: &mut EvidencePackage,
        case: Uuid,
        path: std::path::PathBuf,
    ) -> EVPResult<()> {
        let mut workbook = Workbook::new();

        let worksheet = workbook.add_worksheet();
        let case = package
            .test_case(case)?
            .ok_or(Error::OtherExportError("Test case not found!".into()))?;
        create_test_case_sheet(worksheet, package.clone(), case)
            .map_err(Error::OtherExportError)?;

        workbook
            .save(path)
            .map_err(|e| Error::OtherExportError(e.into()))?;

        Ok(())
    }
}

/// Create the worksheet for the metadata
fn create_metadata_sheet(
    worksheet: &mut Worksheet,
    package: &EvidencePackage,
) -> Result<(), Box<dyn std::error::Error>> {
    tracing::debug!("Creating excel sheet for metadata");
    worksheet.set_name(package.metadata().title())?;
    worksheet.set_screen_gridlines(false);
    worksheet.set_column_width(0, 3)?; // To appear tidy

    let mut row = 1;

    let title = Format::new().set_bold().set_font_size(14);
    let italic = Format::new().set_italic();

    // Write title and execution timestamp
    worksheet.write_string_with_format(row, 1, package.metadata().title(), &title)?;
    row += 1;

    for author in package.metadata().authors() {
        row += 1;
        worksheet.write_string_with_format(row, 1, format!("{author}"), &italic)?;
    }

    row += 2;
    if let Some(description) = package.metadata().description() {
        worksheet.write_string(row, 1, description)?;
    }

    if let Ok(branding_img) = std::env::var("EA_BRAND_IMAGE") {
        row += 2;
        let image = Image::new(branding_img)?;
        worksheet.insert_image(row, 1, &image)?;
    }

    Ok(())
}

/// Create the worksheet for the test case summary
fn create_summary_sheet(
    worksheet: &mut Worksheet,
    package: &EvidencePackage,
) -> Result<(), Box<dyn std::error::Error>> {
    tracing::debug!("Creating excel sheet for summary");
    worksheet.set_name("Summary")?;
    worksheet.set_screen_gridlines(false);
    worksheet.set_column_width(0, 3)?; // To appear tidy

    let mut row = 1;

    let title = Format::new().set_bold().set_font_size(14);
    let bold_bordered = Format::new().set_bold().set_border(FormatBorder::Thin);
    let bordered = Format::new().set_border(FormatBorder::Thin);

    // Write title and execution timestamp
    worksheet.write_string_with_format(row, 1, "Summary", &title)?;
    row += 2;

    // Write header row
    worksheet.write_string_with_format(row, 1, "Test Case", &bold_bordered)?;
    worksheet.write_string_with_format(row, 2, "Executed At", &bold_bordered)?;
    worksheet.write_string_with_format(row, 3, "Status", &bold_bordered)?;
    let mut custom_keys = vec![];
    if let Some(fields) = package.metadata().custom_metadata() {
        let mut fields = fields.iter().collect::<Vec<_>>();
        fields.sort_by(|(_, a), (_, b)| a.cmp(b));
        for (idx, (key, field)) in fields.iter().enumerate() {
            let col = u16::try_from(4 + idx)?;
            custom_keys.push((*key).clone());
            worksheet.write_string_with_format(row, col, field.name(), &bold_bordered)?;
            if !field.description().is_empty() {
                worksheet.insert_note(row, col, &Note::new(field.description()))?;
            }
        }
    }
    row += 1;

    // Write data rows
    for test_case in package.test_case_iter()? {
        worksheet.write_string_with_format(row, 1, test_case.metadata().title(), &bordered)?;
        worksheet.write_string_with_format(
            row,
            2,
            test_case.metadata().execution_datetime().to_rfc3339(),
            &bordered,
        )?;
        worksheet.write_string_with_format(
            row,
            3,
            match test_case.metadata().passed() {
                None => "",
                Some(TestCasePassStatus::Pass) => "Pass",
                Some(TestCasePassStatus::Fail) => "Fail",
            },
            &bordered,
        )?;
        for (idx, key) in custom_keys.iter().enumerate() {
            let col = u16::try_from(4 + idx)?;
            worksheet.write_string_with_format(row, col, "", &bordered)?;
            if let Some(custom) = test_case.metadata().custom()
                && let Some(data) = custom.get(key)
            {
                worksheet.write_string_with_format(row, col, data, &bordered)?;
            }
        }
        row += 1;
    }
    worksheet.autofit();

    Ok(())
}

/// Create the worksheet that holds the test case's information
fn create_test_case_sheet(
    worksheet: &mut Worksheet,
    mut package: EvidencePackage,
    test_case: &TestCase,
) -> Result<(), Box<dyn std::error::Error>> {
    tracing::debug!("Creating excel sheet for test case {}", test_case.id());
    worksheet.set_name(test_case.metadata().title())?;
    worksheet.set_screen_gridlines(false);
    worksheet.set_column_width(0, 3)?; // To appear tidy
    worksheet.set_column_width(1, 13)?; // For "Executed at:"
    worksheet.set_column_width(2, 20)?; // For execution date/time

    let mut row = 1;

    let title = Format::new().set_bold().set_font_size(14);
    let bold = Format::new().set_bold();
    let italic = Format::new().set_italic();
    let file_data = Format::new()
        .set_font_name("Courier New")
        .set_border_left(FormatBorder::Thick);

    // Write title and execution timestamp
    worksheet.write_string_with_format(row, 1, test_case.metadata().title(), &title)?;
    row += 1;
    worksheet.write(row, 1, "Executed at:")?;
    worksheet.write_with_format(
        row,
        2,
        &test_case.metadata().execution_datetime().naive_local(),
        &Format::new().set_num_format("yyyy-mm-dd hh:mm"),
    )?;
    row += 1;
    match test_case.metadata().passed() {
        None => (),
        Some(s) => {
            let s = match s {
                TestCasePassStatus::Pass => "✅ Pass",
                TestCasePassStatus::Fail => "❌ Fail",
            };
            worksheet.write(row, 1, s)?;
            row += 1;
        }
    }
    if let Some(fields) = test_case.metadata().custom() {
        for (key, value) in fields {
            let field = package
                .metadata()
                .custom_metadata()
                .as_ref()
                // SAFETY: guanteed by EVP spec
                .unwrap()
                .get(key)
                // SAFETY: guanteed by EVP spec
                .unwrap();
            worksheet.write(row, 1, format!("{}: {}", field.name(), value))?;
            row += 1;
        }
    }
    row += 1;

    // Write evidence
    for evidence in test_case.evidence() {
        if let Some(caption) = evidence.caption() {
            worksheet.write_with_format(row, 1, caption, &italic)?;
            row += 1;
        }

        match evidence.kind().as_str() {
            "text/plain" => {
                let data = evidence.value().get_data(&mut package)?;
                let text = String::from_utf8_lossy(data.as_slice());
                for line in text.lines() {
                    worksheet.write_string(row, 1, line)?;
                    row += 1;
                }
            }
            "text/markdown" => {
                let data = evidence.value().get_data(&mut package)?;
                let text = String::from_utf8_lossy(data.as_slice());

                if let Ok(ast) = markdown::to_mdast(&text, &ParseOptions::default()) {
                    let excel_data = markdown_to_excel(ast, &Format::default());
                    for line in excel_data {
                        let line = line
                            .iter()
                            .map(|(a, b)| (a, b.as_str()))
                            .collect::<Vec<_>>();
                        worksheet.write_rich_string_with_format(
                            row,
                            1,
                            line.iter().as_slice(),
                            &Format::default(),
                        )?;
                        row += 1;
                    }
                } else {
                    for line in text.lines() {
                        worksheet.write_string_with_format(
                            row,
                            1,
                            line,
                            &Format::default().set_font_name("Courier New"),
                        )?;
                        row += 1;
                    }
                }
            }
            "text/vnd.angel.http-data" => {
                worksheet.write_string_with_format(row, 1, "HTTP Request", &bold)?;
                row += 1;
                let data = evidence.value().get_data(&mut package)?;
                let text = String::from_utf8_lossy(data.as_slice());
                for line in text.lines() {
                    worksheet.write_string_with_format(row, 1, line, &file_data)?;
                    row += 1;
                }
            }
            mime => {
                if mime.starts_with("image/") {
                    let data = evidence.value().get_data(&mut package)?;
                    let image: Image = Image::new_from_buffer(data.as_slice())?;
                    worksheet.insert_image(row, 1, &image)?;

                    // Calculate row offset
                    let height_in = image.height() / image.height_dpi();
                    let row_units_per_in = 4.87;
                    let num_rows_to_skip = (height_in * row_units_per_in).ceil() as u32;
                    row += num_rows_to_skip;
                } else {
                    let data = evidence.value().get_data(&mut package)?;
                    let text = String::from_utf8_lossy(data.as_slice());

                    if let Some(filename) = evidence.original_filename() {
                        worksheet.write_string(row, 1, filename)?;
                        row += 1;
                    }

                    // Check if plaintext ASCII
                    let mut is_printable = true;
                    for c in text.chars() {
                        if !c.is_ascii() {
                            is_printable = false;
                            break;
                        }
                    }

                    if is_printable {
                        for line in text.lines() {
                            worksheet.write_string_with_format(row, 1, line, &file_data)?;
                            row += 1;
                        }
                    } else {
                        worksheet.write_string_with_format(row, 1, "binary file data", &italic)?;
                        row += 1;
                    }
                }
            }
        }

        row += 1;
    }

    Ok(())
}

/// Convert Markdown AST to an array of lines, each an array of line
/// elements defining a format and associated text.
fn markdown_to_excel(node: Node, format: &Format) -> Vec<Vec<(Format, String)>> {
    match node {
        Node::Root(root) => root
            .children
            .into_iter()
            .flat_map(|c| markdown_to_excel(c, format))
            .collect(),
        Node::Paragraph(para) => para
            .children
            .into_iter()
            .flat_map(|c| markdown_to_excel(c, format))
            .collect(),
        Node::List(list) => list
            .children
            .into_iter()
            .flat_map(|c| markdown_to_excel(c, format))
            .collect(),
        Node::ListItem(item) => {
            let mut item = item
                .children
                .into_iter()
                .flat_map(|c| markdown_to_excel(c, format))
                .collect::<Vec<_>>();
            if let Some(fir) = item.first_mut() {
                fir.insert(0, (format.clone(), "• ".to_string()));
            }
            item
        }
        Node::Heading(hdg) => {
            let font_sizes = [32, 28, 24, 18, 16, 14];
            let size = font_sizes.get(usize::from(hdg.depth)).unwrap_or(&14);
            hdg.children
                .into_iter()
                .flat_map(|c| markdown_to_excel(c, &format.clone().set_font_size(*size)))
                .collect()
        }
        Node::Code(code) => {
            vec![vec![(
                format.clone().set_font_name("Courier New"),
                code.value,
            )]]
        }
        Node::Text(text) => {
            vec![vec![(format.clone(), text.value)]]
        }
        Node::InlineCode(code) => {
            vec![vec![(
                format.clone().set_font_name("Courier New"),
                code.value,
            )]]
        }
        Node::Strong(strong) => strong
            .children
            .into_iter()
            .flat_map(|c| markdown_to_excel(c, &format.clone().set_bold()))
            .collect(),
        Node::Emphasis(emph) => emph
            .children
            .into_iter()
            .flat_map(|c| markdown_to_excel(c, &format.clone().set_italic()))
            .collect(),
        _ => vec![],
    }
}