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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Library to parse JUnit XML files

mod errors;

pub use errors::Error;
use quick_xml::events::BytesStart as XMLBytesStart;
use quick_xml::events::Event as XMLEvent;
use quick_xml::Error as XMLError;
use quick_xml::Reader as XMLReader;
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::prelude::*;
use std::str;

#[derive(Debug, Clone)]
/// Value from a `<failure />` tag
pub struct TestFailure {
    /// The `message` attribute
    pub message: String,
    /// Body of the `<failure />` tag
    pub text: String,
    /// The `type` attribute
    pub failure_type: String,
}
impl TestFailure {
    pub fn new() -> Self {
        Self {
            message: String::new(),
            text: String::new(),
            failure_type: String::new(),
        }
    }
    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"type" => self.failure_type = try_from_attribute_value_string(a.value)?,
                b"message" => self.message = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut tf = Self::new();
        tf.parse_attributes(e)?;
        Ok(tf)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut tf = Self::new();
        tf.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"failure" => break,
                Ok(XMLEvent::Text(e)) => {
                    tf.text = e.unescape_and_decode(&r)?.trim().to_string();
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("failure".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(tf)
    }
}

#[derive(Debug, Clone)]
/// Value from an `<error />` tag
pub struct TestError {
    /// The `message` attribute
    pub message: String,
    /// Body of the `<error />` tag
    pub text: String,
    /// The `type` attribute
    pub error_type: String,
}
impl TestError {
    pub fn new() -> Self {
        Self {
            message: String::new(),
            text: String::new(),
            error_type: String::new(),
        }
    }
    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"type" => self.error_type = try_from_attribute_value_string(a.value)?,
                b"message" => self.message = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut te = Self::new();
        te.parse_attributes(e)?;
        Ok(te)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut te = Self::new();
        te.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"error" => break,
                Ok(XMLEvent::Text(e)) => {
                    te.text = e.unescape_and_decode(&r)?.trim().to_string();
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("error".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(te)
    }
}

#[derive(Debug, Clone)]
/// Value from a `<skipped />` tag
pub struct TestSkipped {
    /// The `message` attribute
    pub message: String,
    /// Body of the `<skipped />` tag
    pub text: String,
    /// The `type` attribute
    pub skipped_type: String,
}
impl TestSkipped {
    pub fn new() -> Self {
        Self {
            message: String::new(),
            text: String::new(),
            skipped_type: String::new(),
        }
    }
    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"type" => self.skipped_type = try_from_attribute_value_string(a.value)?,
                b"message" => self.message = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        Ok(ts)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"skipped" => break,
                Ok(XMLEvent::Text(e)) => {
                    ts.text = e.unescape_and_decode(&r)?.trim().to_string();
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("skipped".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(ts)
    }
}

#[derive(Debug, Clone)]
/// Status of a test case
pub enum TestStatus {
    /// Success
    Success,
    /// Test case has a `<error />` tag
    Error(TestError),
    /// Test case has a `<failure />` tag
    Failure(TestFailure),
    /// Test case has a `<skipped />` tag
    Skipped(TestSkipped),
}
impl TestStatus {
    /// Returns `true` if the `TestStatus` is [`Success`](#variant.Success).
    pub fn is_success(&self) -> bool {
        match self {
            TestStatus::Success => true,
            _ => false,
        }
    }
    /// Returns `true` if the `TestStatus` is [`Error(_)`](#variant.Error).
    pub fn is_error(&self) -> bool {
        match self {
            TestStatus::Error(_) => true,
            _ => false,
        }
    }
    /// Returns the contained [`Error(_)`](#variant.Error) value as a reference
    ///
    /// # Panics
    ///
    /// Panics if the value is not an [`Errror(_)`](#variant.Error)
    pub fn error_as_ref<'a>(&'a self) -> &'a TestError {
        if let TestStatus::Error(ref e) = self {
            return e;
        }
        panic!("called `TestStatus::error()` on a value that is not TestStatus::Error(_)");
    }

    /// Returns `true` if the `TestStatus` is [`Failure(_)`](#variant.Failure).
    pub fn is_failure(&self) -> bool {
        match self {
            TestStatus::Failure(_) => true,
            _ => false,
        }
    }
    /// Returns the contained [`Failure(_)`](#variant.Failure) value as a reference
    ///
    /// # Panics
    ///
    /// Panics if the value is not a [`Failure(_)`](#variant.Failure)
    pub fn failure_as_ref<'a>(&'a self) -> &'a TestFailure {
        if let TestStatus::Failure(ref e) = self {
            return e;
        }
        panic!("called `TestStatus::failure()` on a value that is not TestStatus::Failure(_)");
    }

    /// Returns `true` if the `TestStatus` is [`Skipped(_)`](#variant.Skipped).
    pub fn is_skipped(&self) -> bool {
        match self {
            TestStatus::Skipped(_) => true,
            _ => false,
        }
    }
    /// Returns the contained [`Skipped(_)`](#variant.Skipped) value as a reference
    ///
    /// # Panics
    ///
    /// Panics if the value is not a [`Skipped(_)`](#variant.Skipped)
    pub fn skipped_as_ref<'a>(&'a self) -> &'a TestSkipped {
        if let TestStatus::Skipped(ref e) = self {
            return e;
        }
        panic!("called `TestStatus::skipped()` on a value that is not TestStatus::Skipped(_)");
    }
}

#[derive(Debug)]
/// A test case
pub struct TestCase {
    /// How long the test case took to run, from the `time` attribute
    pub time: f64,
    /// Name of the test case, from the `name` attribute
    pub name: String,
    /// Status of the test case
    pub status: TestStatus,
}
impl TestCase {
    fn new() -> Self {
        Self {
            time: 0f64,
            name: String::new(),
            status: TestStatus::Success,
        }
    }
    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"time" => self.time = try_from_attribute_value_f64(a.value)?,
                b"name" => self.name = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut tc = Self::new();
        tc.parse_attributes(e)?;
        Ok(tc)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut tc = Self::new();
        tc.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"testcase" => break,
                Ok(XMLEvent::Start(ref e)) if e.name() == b"skipped" => {
                    let ts = TestSkipped::new_from_reader(e, r)?;
                    tc.status = TestStatus::Skipped(ts);
                }
                Ok(XMLEvent::Empty(ref e)) if e.name() == b"skipped" => {
                    let ts = TestSkipped::new_empty(e)?;
                    tc.status = TestStatus::Skipped(ts);
                }
                Ok(XMLEvent::Start(ref e)) if e.name() == b"failure" => {
                    let tf = TestFailure::new_from_reader(e, r)?;
                    tc.status = TestStatus::Failure(tf);
                }
                Ok(XMLEvent::Empty(ref e)) if e.name() == b"failure" => {
                    let tf = TestFailure::new_empty(e)?;
                    tc.status = TestStatus::Failure(tf);
                }
                Ok(XMLEvent::Start(ref e)) if e.name() == b"error" => {
                    let te = TestError::new_from_reader(e, r)?;
                    tc.status = TestStatus::Error(te);
                }
                Ok(XMLEvent::Empty(ref e)) if e.name() == b"error" => {
                    let te = TestError::new_empty(e)?;
                    tc.status = TestStatus::Error(te);
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("testcase".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(tc)
    }
}

#[derive(Debug)]
/// A test suite, containing test cases [`TestCase`](struct.TestCase.html)
pub struct TestSuite {
    pub cases: HashMap<String, TestCase>,
    /// How long the test suite took to run, from the `time` attribute
    pub time: f64,
    /// Number of tests in the test suite, from the `tests` attribute
    pub tests: u64,
    /// Number of tests in error in the test suite, from the `errors` attribute
    pub errors: u64,
    /// Number of tests in failure in the test suite, from the `failures` attribute
    pub failures: u64,
    /// Number of tests skipped in the test suites, from the `skipped` attribute
    pub skipped: u64,
    /// Name of the test suite, from the `name` attribute
    pub name: String,
}
impl TestSuite {
    fn new() -> Self {
        Self {
            cases: HashMap::new(),
            time: 0f64,
            tests: 0u64,
            errors: 0u64,
            failures: 0u64,
            skipped: 0u64,
            name: String::new(),
        }
    }
    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"time" => self.time = try_from_attribute_value_f64(a.value)?,
                b"tests" => self.tests = try_from_attribute_value_u64(a.value)?,
                b"errors" => self.errors = try_from_attribute_value_u64(a.value)?,
                b"failures" => self.failures = try_from_attribute_value_u64(a.value)?,
                b"skipped" => self.skipped = try_from_attribute_value_u64(a.value)?,
                b"name" => self.name = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        Ok(ts)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"testsuite" => break,
                Ok(XMLEvent::Start(ref e)) if e.name() == b"testcase" => {
                    let testcase = TestCase::new_from_reader(e, r)?;
                    if ts.cases.contains_key(&testcase.name) {
                        return Err(Error::DuplicateError {
                            kind: "testcase".to_string(),
                            name: testcase.name,
                        });
                    }
                    ts.cases.insert(testcase.name.clone(), testcase);
                }
                Ok(XMLEvent::Empty(ref e)) if e.name() == b"testcase" => {
                    let testcase = TestCase::new_empty(e)?;
                    if ts.cases.contains_key(&testcase.name) {
                        return Err(Error::DuplicateError {
                            kind: "testcase".to_string(),
                            name: testcase.name,
                        });
                    }
                    ts.cases.insert(testcase.name.clone(), testcase);
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("testsuite".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(ts)
    }
}

#[derive(Debug)]
/// Struct representing a JUnit report, containing test suites [`TestSuite`](struct.TestSuite.html)
pub struct TestSuites {
    pub suites: HashMap<String, TestSuite>,
    /// How long the test suites took to run, from the `time` attribute
    pub time: f64,
    /// Number of tests in the test suites, from the `tests` attribute
    pub tests: u64,
    /// Number of tests in error in the test suites, from the `errors` attribute
    pub errors: u64,
    /// Number of tests in failure in the test suites, from the `failures` attribute
    pub failures: u64,
    /// Number of tests skipped in the test suites, from the `skipped` attribute
    pub skipped: u64,
    /// Name of the test suites, from the `name` attribute
    pub name: String,
}
impl TestSuites {
    fn new() -> Self {
        Self {
            suites: HashMap::new(),
            time: 0f64,
            tests: 0u64,
            errors: 0u64,
            failures: 0u64,
            skipped: 0u64,
            name: String::new(),
        }
    }

    fn parse_attributes<'a>(&mut self, e: &'a XMLBytesStart) -> Result<(), Error> {
        for a in e.attributes() {
            let a = a?;
            match a.key {
                b"time" => self.time = try_from_attribute_value_f64(a.value)?,
                b"tests" => self.tests = try_from_attribute_value_u64(a.value)?,
                b"errors" => self.errors = try_from_attribute_value_u64(a.value)?,
                b"failures" => self.failures = try_from_attribute_value_u64(a.value)?,
                b"skipped" => self.skipped = try_from_attribute_value_u64(a.value)?,
                b"name" => self.name = try_from_attribute_value_string(a.value)?,
                _ => {}
            };
        }
        Ok(())
    }

    fn new_empty<'a>(e: &'a XMLBytesStart) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        Ok(ts)
    }

    fn new_from_reader<'a, B: BufRead>(
        e: &'a XMLBytesStart,
        r: &mut XMLReader<B>,
    ) -> Result<Self, Error> {
        let mut ts = Self::new();
        ts.parse_attributes(e)?;
        let mut buf = Vec::new();
        loop {
            match r.read_event(&mut buf) {
                Ok(XMLEvent::End(ref e)) if e.name() == b"testsuites" => break,
                Ok(XMLEvent::Start(ref e)) if e.name() == b"testsuite" => {
                    let suite = TestSuite::new_from_reader(e, r)?;
                    if ts.suites.contains_key(&suite.name) {
                        return Err(Error::DuplicateError {
                            kind: "testsuite".to_string(),
                            name: suite.name,
                        });
                    }
                    ts.suites.insert(suite.name.clone(), suite);
                }
                Ok(XMLEvent::Empty(ref e)) if e.name() == b"testsuite" => {
                    let suite = TestSuite::new_empty(e)?;
                    if ts.suites.contains_key(&suite.name) {
                        return Err(Error::DuplicateError {
                            kind: "testsuite".to_string(),
                            name: suite.name,
                        });
                    }
                    ts.suites.insert(suite.name.clone(), suite);
                }
                Ok(XMLEvent::Eof) => {
                    return Err(XMLError::UnexpectedEof("testsuites".to_string()).into())
                }
                Err(err) => return Err(err.into()),
                _ => (),
            }
        }
        buf.clear();
        Ok(ts)
    }
}

fn try_from_attribute_value_f64<'a>(value: Cow<'a, [u8]>) -> Result<f64, Error> {
    match value {
        Cow::Borrowed(b) => {
            let s = str::from_utf8(b)?;
            if s.len() == 0 {
                return Ok(0f64);
            }
            Ok(s.parse::<f64>()?)
        }
        Cow::Owned(ref b) => {
            let s = str::from_utf8(b)?;
            if s.len() == 0 {
                return Ok(0f64);
            }
            Ok(s.parse::<f64>()?)
        }
    }
}

fn try_from_attribute_value_u64<'a>(value: Cow<'a, [u8]>) -> Result<u64, Error> {
    match value {
        Cow::Borrowed(b) => {
            let s = str::from_utf8(b)?;
            if s.len() == 0 {
                return Ok(0u64);
            }
            Ok(s.parse::<u64>()?)
        }
        Cow::Owned(ref b) => {
            let s = str::from_utf8(b)?;
            if s.len() == 0 {
                return Ok(0u64);
            }
            Ok(s.parse::<u64>()?)
        }
    }
}

fn try_from_attribute_value_string<'a>(value: Cow<'a, [u8]>) -> Result<String, Error> {
    match value {
        Cow::Borrowed(b) => Ok(str::from_utf8(b)?.to_owned()),
        Cow::Owned(ref b) => Ok(str::from_utf8(b)?.to_owned()),
    }
}

/// Creates a [`TestSuites`](struct.TestSuites.html) structure from a JUnit XML data read from `reader`
///
/// # Example
/// ```
/// use std::io::Cursor;
///     let xml = r#"
/// <testsuite tests="3" failures="1">
///   <testcase classname="foo1" name="ASuccessfulTest"/>
///   <testcase classname="foo2" name="AnotherSuccessfulTest"/>
///   <testcase classname="foo3" name="AFailingTest">
///     <failure type="NotEnoughFoo"> details about failure </failure>
///   </testcase>
/// </testsuite>
/// "#;
///     let cursor = Cursor::new(xml);
///     let r = junit_parser::from_reader(cursor);
///     assert!(r.is_ok());
/// ```

pub fn from_reader<B: BufRead>(reader: B) -> Result<TestSuites, Error> {
    let mut r = XMLReader::from_reader(reader);
    let mut buf = Vec::new();
    loop {
        match r.read_event(&mut buf) {
            Ok(XMLEvent::Empty(ref e)) if e.name() == b"testsuites" => {
                return TestSuites::new_empty(e);
            }
            Ok(XMLEvent::Start(ref e)) if e.name() == b"testsuites" => {
                return TestSuites::new_from_reader(e, &mut r);
            }
            Ok(XMLEvent::Empty(ref e)) if e.name() == b"testsuite" => {
                let ts = TestSuite::new_empty(e)?;
                let mut suites = TestSuites::new();
                suites.suites.insert(ts.name.clone(), ts);
                return Ok(suites);
            }
            Ok(XMLEvent::Start(ref e)) if e.name() == b"testsuite" => {
                let ts = TestSuite::new_from_reader(e, &mut r)?;
                let mut suites = TestSuites::new();
                suites.suites.insert(ts.name.clone(), ts);
                return Ok(suites);
            }
            Ok(XMLEvent::Eof) => {
                return Err(XMLError::UnexpectedEof("testsuites".to_string()).into())
            }
            Err(err) => return Err(err.into()),
            _ => (),
        }
    }
}