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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! This crate provides helper functions for testing architecture tests.

use {
    anyhow::{bail, Context as _, Error},
    fidl_fuchsia_io as fio,
    fidl_fuchsia_test_manager::{
        self as ftest_manager, SuiteControllerProxy, SuiteEvent as FidlSuiteEvent,
        SuiteEventPayload as FidlSuiteEventPayload, SuiteEventPayloadUnknown,
    },
    fuchsia_async as fasync,
    futures::{channel::mpsc, prelude::*},
    linked_hash_map::LinkedHashMap,
    std::{collections::HashMap, sync::Arc},
    test_diagnostics::{collect_and_send_string_output, LogStream},
    tracing::*,
};

pub fn default_run_option() -> ftest_manager::RunOptions {
    ftest_manager::RunOptions {
        parallel: None,
        arguments: None,
        run_disabled_tests: Some(false),
        timeout: None,
        case_filters_to_run: None,
        log_iterator: None,
        ..Default::default()
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct AttributedLog {
    pub log: String,
    pub moniker: String,
}

pub async fn collect_suite_events(
    suite_instance: SuiteRunInstance,
) -> Result<(Vec<RunEvent>, Vec<AttributedLog>), Error> {
    let (sender, mut recv) = mpsc::channel(1);
    let execution_task =
        fasync::Task::spawn(async move { suite_instance.collect_events(sender).await });
    let mut events = vec![];
    let mut log_tasks = vec![];
    while let Some(event) = recv.next().await {
        match event.payload {
            SuiteEventPayload::RunEvent(RunEvent::CaseStdout { name, mut stdout_message }) => {
                if stdout_message.ends_with("\n") {
                    stdout_message.truncate(stdout_message.len() - 1)
                }
                let logs = stdout_message.split("\n");
                for log in logs {
                    // gtest produces this line when tests are randomized. As of
                    // this writing, our gtest_main binary *always* randomizes.
                    if log.contains("Note: Randomizing tests' orders with a seed of") {
                        continue;
                    }
                    events.push(RunEvent::case_stdout(name.clone(), log.to_string()));
                }
            }
            SuiteEventPayload::RunEvent(RunEvent::CaseStderr { name, mut stderr_message }) => {
                if stderr_message.ends_with("\n") {
                    stderr_message.truncate(stderr_message.len() - 1)
                }
                let logs = stderr_message.split("\n");
                for log in logs {
                    events.push(RunEvent::case_stderr(name.clone(), log.to_string()));
                }
            }
            SuiteEventPayload::RunEvent(e) => events.push(e),
            SuiteEventPayload::SuiteLog { log_stream } => {
                let t = fasync::Task::spawn(log_stream.collect::<Vec<_>>());
                log_tasks.push(t);
            }
            SuiteEventPayload::TestCaseLog { .. } => {
                panic!("not supported yet!")
            }
        }
    }
    execution_task.await.context("test execution failed")?;

    let mut collected_logs = vec![];
    for t in log_tasks {
        let logs = t.await;
        for log_result in logs {
            let log = log_result?;
            collected_logs.push(AttributedLog {
                log: log.msg().unwrap().to_string(),
                moniker: log.moniker.clone(),
            });
        }
    }

    Ok((events, collected_logs))
}

/// Builds and runs test suite(s).
pub struct TestBuilder {
    proxy: ftest_manager::RunBuilderProxy,
    filter_debug_data: bool,
}

impl TestBuilder {
    /// Create new instance
    pub fn new(proxy: ftest_manager::RunBuilderProxy) -> Self {
        Self { proxy, filter_debug_data: false }
    }

    /// Filter out debug data. On coverage builders, tests executed under
    /// test_manager produce coverage profile. This option is useful for
    /// ignoring these and ensuring the caller observes the same events on
    /// all builders.
    pub fn filter_debug_data(self) -> Self {
        let Self { proxy, .. } = self;
        Self { proxy, filter_debug_data: true }
    }

    pub fn take_proxy(self) -> ftest_manager::RunBuilderProxy {
        self.proxy
    }

    pub fn set_scheduling_options(&self, accumulate_debug_data: bool) -> Result<(), Error> {
        self.proxy
            .with_scheduling_options(&ftest_manager::SchedulingOptions {
                accumulate_debug_data: Some(accumulate_debug_data),
                ..Default::default()
            })
            .map_err(Error::from)
    }

    /// Add suite to run.
    pub async fn add_suite(
        &self,
        test_url: &str,
        run_options: ftest_manager::RunOptions,
    ) -> Result<SuiteRunInstance, Error> {
        let (controller_proxy, controller) =
            fidl::endpoints::create_proxy().context("Cannot create proxy")?;
        self.proxy.add_suite(test_url, &run_options, controller)?;
        Ok(SuiteRunInstance { controller_proxy: controller_proxy.into() })
    }

    /// Add suite to run in a realm.
    pub async fn add_suite_in_realm(
        &self,
        realm: fidl::endpoints::ClientEnd<fidl_fuchsia_component::RealmMarker>,
        offers: &[fidl_fuchsia_component_decl::Offer],
        test_collection: &str,
        test_url: &str,
        run_options: ftest_manager::RunOptions,
    ) -> Result<SuiteRunInstance, Error> {
        let (controller_proxy, controller) =
            fidl::endpoints::create_proxy().context("Cannot create proxy")?;
        self.proxy.add_suite_in_realm(
            realm,
            offers,
            test_collection,
            test_url,
            &run_options,
            controller,
        )?;
        Ok(SuiteRunInstance { controller_proxy: controller_proxy.into() })
    }

    /// Runs all tests to completion and collects events.
    pub async fn run(self) -> Result<Vec<TestRunEvent>, Error> {
        let (controller_proxy, controller) =
            fidl::endpoints::create_proxy().context("Cannot create proxy")?;
        self.proxy.build(controller).context("Error starting tests")?;
        // wait for test to end
        let mut events = vec![];
        loop {
            let fidl_events = controller_proxy.get_events().await.context("Get run events")?;
            if fidl_events.is_empty() {
                break;
            }
            for fidl_event in fidl_events {
                match fidl_event.payload.expect("Payload cannot be empty") {
                    ftest_manager::RunEventPayload::Artifact(
                        ftest_manager::Artifact::DebugData(iterator),
                    ) => {
                        if !self.filter_debug_data {
                            let proxy = iterator.into_proxy().context("Create proxy")?;
                            loop {
                                let data = proxy.get_next().await?;
                                if data.is_empty() {
                                    break;
                                }
                                for data_file in data {
                                    let socket = data_file.socket.expect("File cannot be empty");
                                    events.push(TestRunEvent::debug_data(
                                        fidl_event.timestamp,
                                        data_file.name.expect("Name cannot be empty"),
                                        socket,
                                    ));
                                }
                            }
                        }
                    }
                    other => bail!("Expected only debug data run events but got {:?}", other),
                }
            }
        }
        Ok(events)
    }
}

#[derive(Debug)]
pub struct TestRunEvent {
    pub timestamp: Option<i64>,
    pub payload: TestRunEventPayload,
}

impl TestRunEvent {
    pub fn debug_data<S: Into<String>>(
        timestamp: Option<i64>,
        filename: S,
        socket: fidl::Socket,
    ) -> Self {
        Self {
            timestamp,
            payload: TestRunEventPayload::DebugData { filename: filename.into(), socket },
        }
    }
}

#[derive(Debug)]
pub enum TestRunEventPayload {
    DebugData { filename: String, socket: fidl::Socket },
}

/// Events produced by test suite.
pub struct SuiteEvent {
    pub timestamp: Option<i64>,
    pub payload: SuiteEventPayload,
}

impl SuiteEvent {
    pub fn case_found(timestamp: Option<i64>, name: String) -> Self {
        SuiteEvent { timestamp, payload: SuiteEventPayload::RunEvent(RunEvent::case_found(name)) }
    }

    pub fn case_started(timestamp: Option<i64>, name: String) -> Self {
        SuiteEvent { timestamp, payload: SuiteEventPayload::RunEvent(RunEvent::case_started(name)) }
    }

    pub fn case_stdout<N, L>(timestamp: Option<i64>, name: N, stdout_message: L) -> Self
    where
        N: Into<String>,
        L: Into<String>,
    {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::case_stdout(
                name.into(),
                stdout_message.into(),
            )),
        }
    }

    pub fn case_stderr<N, L>(timestamp: Option<i64>, name: N, stderr_message: L) -> Self
    where
        N: Into<String>,
        L: Into<String>,
    {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::case_stderr(
                name.into(),
                stderr_message.into(),
            )),
        }
    }

    pub fn case_stopped(
        timestamp: Option<i64>,
        name: String,
        status: ftest_manager::CaseStatus,
    ) -> Self {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::case_stopped(name, status)),
        }
    }

    pub fn case_finished(timestamp: Option<i64>, name: String) -> Self {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::case_finished(name)),
        }
    }

    pub fn suite_stopped(timestamp: Option<i64>, status: ftest_manager::SuiteStatus) -> Self {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::suite_stopped(status)),
        }
    }

    pub fn suite_custom(
        timestamp: Option<i64>,
        component: String,
        filename: String,
        contents: String,
    ) -> Self {
        SuiteEvent {
            timestamp,
            payload: SuiteEventPayload::RunEvent(RunEvent::suite_custom(
                component, filename, contents,
            )),
        }
    }

    pub fn suite_log(timestamp: Option<i64>, log_stream: LogStream) -> Self {
        SuiteEvent { timestamp, payload: SuiteEventPayload::SuiteLog { log_stream } }
    }

    pub fn test_case_log(timestamp: Option<i64>, name: String, log_stream: LogStream) -> Self {
        SuiteEvent { timestamp, payload: SuiteEventPayload::TestCaseLog { name, log_stream } }
    }
}

pub enum SuiteEventPayload {
    /// Logger for test suite
    SuiteLog { log_stream: LogStream },

    /// Logger for a test case in suite.
    TestCaseLog { name: String, log_stream: LogStream },

    /// Test events.
    RunEvent(RunEvent),
}

#[derive(PartialEq, Debug, Eq, Hash, Ord, PartialOrd, Clone)]
pub enum RunEvent {
    CaseFound { name: String },
    CaseStarted { name: String },
    CaseStdout { name: String, stdout_message: String },
    CaseStderr { name: String, stderr_message: String },
    CaseStopped { name: String, status: ftest_manager::CaseStatus },
    CaseFinished { name: String },
    SuiteStarted,
    SuiteCustom { component: String, filename: String, contents: String },
    SuiteStopped { status: ftest_manager::SuiteStatus },
}

impl RunEvent {
    pub fn case_found<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self::CaseFound { name: name.into() }
    }

    pub fn case_started<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self::CaseStarted { name: name.into() }
    }

    pub fn case_stdout<S, L>(name: S, stdout_message: L) -> Self
    where
        S: Into<String>,
        L: Into<String>,
    {
        Self::CaseStdout { name: name.into(), stdout_message: stdout_message.into() }
    }

    pub fn case_stderr<S, L>(name: S, stderr_message: L) -> Self
    where
        S: Into<String>,
        L: Into<String>,
    {
        Self::CaseStderr { name: name.into(), stderr_message: stderr_message.into() }
    }

    pub fn case_stopped<S>(name: S, status: ftest_manager::CaseStatus) -> Self
    where
        S: Into<String>,
    {
        Self::CaseStopped { name: name.into(), status }
    }

    pub fn case_finished<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self::CaseFinished { name: name.into() }
    }

    pub fn suite_started() -> Self {
        Self::SuiteStarted
    }

    pub fn suite_custom<T, U, V>(component: T, filename: U, contents: V) -> Self
    where
        T: Into<String>,
        U: Into<String>,
        V: Into<String>,
    {
        Self::SuiteCustom {
            component: component.into(),
            filename: filename.into(),
            contents: contents.into(),
        }
    }

    pub fn suite_stopped(status: ftest_manager::SuiteStatus) -> Self {
        Self::SuiteStopped { status }
    }
    /// Returns the name of the test case to which the event belongs, if applicable.
    pub fn test_case_name(&self) -> Option<&String> {
        match self {
            RunEvent::CaseFound { name }
            | RunEvent::CaseStarted { name }
            | RunEvent::CaseStdout { name, .. }
            | RunEvent::CaseStderr { name, .. }
            | RunEvent::CaseStopped { name, .. }
            | RunEvent::CaseFinished { name } => Some(name),
            RunEvent::SuiteStarted
            | RunEvent::SuiteStopped { .. }
            | RunEvent::SuiteCustom { .. } => None,
        }
    }

    /// Same as `test_case_name`, but returns an owned `Option<String>`.
    pub fn owned_test_case_name(&self) -> Option<String> {
        self.test_case_name().map(String::from)
    }
}

/// Groups events by stdout, stderr and non stdout/stderr events to make it easy to compare them
/// in tests.
#[derive(Default, Debug, Eq, PartialEq, Clone)]
pub struct GroupedRunEvents {
    // order of events is maintained.
    pub non_artifact_events: Vec<RunEvent>,
    // order of stdout events is maintained.
    pub stdout_events: Vec<RunEvent>,
    // order of stderr events is maintained.
    pub stderr_events: Vec<RunEvent>,
}

/// Trait allowing iterators over `RunEvent` to be partitioned by test case name.
pub trait GroupRunEventByTestCase: Iterator<Item = RunEvent> + Sized {
    /// Groups the `RunEvent`s by test case name into a map that preserves insertion order of
    /// various types of events.
    /// The overall order of test cases (by first event) and the orders of events within each test
    /// case are preserved, but events from different test cases are effectively de-interleaved.
    ///
    /// Example:
    /// ```rust
    /// use test_diagnostics::{RunEvent, GroupRunEventByTestCase as _};
    /// use linked_hash_map::LinkedHashMap;
    ///
    /// let events: Vec<RunEvent> = get_events();
    /// let grouped: LinkedHashMap<Option<String>, GroupedRunEvents> =
    ///     events.into_iter().group_by_test_case_ordered();
    /// ```
    fn group_by_test_case_ordered(self) -> LinkedHashMap<Option<String>, GroupedRunEvents> {
        let mut map = LinkedHashMap::new();
        for run_event in self {
            match run_event {
                RunEvent::CaseStderr { .. } => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .stderr_events
                    .push(run_event),

                RunEvent::CaseStdout { .. } => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .stdout_events
                    .push(run_event),

                _ => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .non_artifact_events
                    .push(run_event),
            }
        }
        map
    }

    /// Groups the `RunEvent`s by test case name into an unordered map. The orders of events within
    /// each test case are preserved, but the test cases themselves are not in a defined order.
    fn group_by_test_case_unordered(self) -> HashMap<Option<String>, GroupedRunEvents> {
        let mut map = HashMap::new();
        for run_event in self {
            match run_event {
                RunEvent::CaseStderr { .. } => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .stderr_events
                    .push(run_event),

                RunEvent::CaseStdout { .. } => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .stdout_events
                    .push(run_event),

                _ => map
                    .entry(run_event.owned_test_case_name())
                    .or_insert(GroupedRunEvents::default())
                    .non_artifact_events
                    .push(run_event),
            }
        }
        map
    }

    /// Group `RunEvent`s by stdout, stderr and non-stdout/err events and returns `GroupedRunEvents`.
    fn group(self) -> GroupedRunEvents {
        let mut events = GroupedRunEvents::default();
        for run_event in self {
            match run_event {
                RunEvent::CaseStderr { .. } => events.stderr_events.push(run_event),

                RunEvent::CaseStdout { .. } => events.stdout_events.push(run_event),

                _ => events.non_artifact_events.push(run_event),
            }
        }
        events
    }
}

impl<T> GroupRunEventByTestCase for T where T: Iterator<Item = RunEvent> + Sized {}

#[derive(Default)]
struct FidlSuiteEventProcessor {
    case_map: HashMap<u32, String>,
    std_output_map: HashMap<u32, Vec<fasync::Task<Result<(), Error>>>>,
}

impl FidlSuiteEventProcessor {
    fn new() -> Self {
        FidlSuiteEventProcessor::default()
    }

    fn get_test_case_name(&self, identifier: u32) -> String {
        self.case_map
            .get(&identifier)
            .unwrap_or_else(|| panic!("invalid test case identifier: {:?}", identifier))
            .clone()
    }

    async fn process(
        &mut self,
        event: FidlSuiteEvent,
        mut sender: mpsc::Sender<SuiteEvent>,
    ) -> Result<(), Error> {
        let timestamp = event.timestamp;
        let e = match event.payload.expect("Payload cannot be null, please file bug.") {
            FidlSuiteEventPayload::CaseFound(cf) => {
                self.case_map.insert(cf.identifier, cf.test_case_name.clone());
                SuiteEvent::case_found(timestamp, cf.test_case_name).into()
            }
            FidlSuiteEventPayload::CaseStarted(cs) => {
                let test_case_name = self.get_test_case_name(cs.identifier);
                SuiteEvent::case_started(timestamp, test_case_name).into()
            }
            FidlSuiteEventPayload::CaseStopped(cs) => {
                let test_case_name = self.get_test_case_name(cs.identifier);
                if let Some(outputs) = self.std_output_map.remove(&cs.identifier) {
                    for s in outputs {
                        s.await.context(format!(
                            "error collecting stdout/stderr of {}",
                            test_case_name
                        ))?;
                    }
                }
                SuiteEvent::case_stopped(timestamp, test_case_name, cs.status).into()
            }
            FidlSuiteEventPayload::CaseFinished(cf) => {
                let test_case_name = self.get_test_case_name(cf.identifier);
                SuiteEvent::case_finished(timestamp, test_case_name).into()
            }
            FidlSuiteEventPayload::CaseArtifact(ca) => {
                let name = self.get_test_case_name(ca.identifier);
                match ca.artifact {
                    ftest_manager::Artifact::Stdout(stdout) => {
                        let (s, mut r) = mpsc::channel(1024);
                        let stdout_task =
                            fasync::Task::spawn(collect_and_send_string_output(stdout, s));
                        let mut sender_clone = sender.clone();
                        let send_stdout_task = fasync::Task::spawn(async move {
                            while let Some(msg) = r.next().await {
                                sender_clone
                                    .send(SuiteEvent::case_stdout(None, &name, msg))
                                    .await
                                    .context(format!("cannot send logs for {}", name))?;
                            }
                            Ok(())
                        });
                        match self.std_output_map.get_mut(&ca.identifier) {
                            Some(v) => {
                                v.push(stdout_task);
                                v.push(send_stdout_task);
                            }
                            None => {
                                self.std_output_map
                                    .insert(ca.identifier, vec![stdout_task, send_stdout_task]);
                            }
                        }
                        None
                    }
                    ftest_manager::Artifact::Stderr(stderr) => {
                        let (s, mut r) = mpsc::channel(1024);
                        let stderr_task =
                            fasync::Task::spawn(collect_and_send_string_output(stderr, s));
                        let mut sender_clone = sender.clone();
                        let send_stderr_task = fasync::Task::spawn(async move {
                            while let Some(msg) = r.next().await {
                                sender_clone
                                    .send(SuiteEvent::case_stderr(None, &name, msg))
                                    .await
                                    .context(format!("cannot send logs for {}", name))?;
                            }
                            Ok(())
                        });
                        match self.std_output_map.get_mut(&ca.identifier) {
                            Some(v) => {
                                v.push(stderr_task);
                                v.push(send_stderr_task);
                            }
                            None => {
                                self.std_output_map
                                    .insert(ca.identifier, vec![stderr_task, send_stderr_task]);
                            }
                        }
                        None
                    }
                    ftest_manager::Artifact::Log(log) => match LogStream::from_syslog(log) {
                        Ok(log_stream) => {
                            SuiteEvent::test_case_log(timestamp, name, log_stream).into()
                        }
                        Err(e) => {
                            warn!("Cannot collect logs for test suite: {:?}", e);
                            None
                        }
                    },
                    _ => {
                        panic!("not supported")
                    }
                }
            }
            FidlSuiteEventPayload::SuiteArtifact(sa) => match sa.artifact {
                ftest_manager::Artifact::Stdout(_) => {
                    panic!("not supported")
                }
                ftest_manager::Artifact::Stderr(_) => {
                    panic!("not supported")
                }
                ftest_manager::Artifact::Log(log) => match LogStream::from_syslog(log) {
                    Ok(log_stream) => SuiteEvent::suite_log(timestamp, log_stream).into(),
                    Err(e) => {
                        warn!("Cannot collect logs for test suite: {:?}", e);
                        None
                    }
                },
                ftest_manager::Artifact::Custom(custom_artifact) => {
                    let ftest_manager::DirectoryAndToken { directory, token } =
                        custom_artifact.directory_and_token.unwrap();
                    let component_moniker = custom_artifact.component_moniker.unwrap();
                    let mut sender_clone = sender.clone();
                    fasync::Task::spawn(async move {
                        let directory = directory.into_proxy().unwrap();
                        let entries: Vec<_> =
                            fuchsia_fs::directory::readdir_recursive(&directory, None)
                                .try_collect()
                                .await
                                .expect("read custom artifact directory");
                        for entry in entries.into_iter() {
                            let file = fuchsia_fs::directory::open_file_no_describe(
                                &directory,
                                &entry.name,
                                fio::OpenFlags::RIGHT_READABLE,
                            )
                            .unwrap();
                            let contents = fuchsia_fs::file::read_to_string(&file).await.unwrap();
                            sender_clone
                                .send(SuiteEvent::suite_custom(
                                    timestamp,
                                    component_moniker.clone(),
                                    entry.name,
                                    contents,
                                ))
                                .await
                                .unwrap();
                        }
                        // Drop the token here - we must keep the token open for the duration that
                        // the directory is in use.
                        drop(token);
                    })
                    .detach();
                    None
                }
                _ => {
                    panic!("not supported")
                }
            },
            FidlSuiteEventPayload::SuiteStarted(_started) => SuiteEvent {
                timestamp,
                payload: SuiteEventPayload::RunEvent(RunEvent::SuiteStarted),
            }
            .into(),
            FidlSuiteEventPayload::SuiteStopped(stopped) => SuiteEvent {
                timestamp,
                payload: SuiteEventPayload::RunEvent(RunEvent::SuiteStopped {
                    status: stopped.status,
                }),
            }
            .into(),
            SuiteEventPayloadUnknown!() => panic!("Unrecognized SuiteEvent"),
        };
        if let Some(item) = e {
            sender.send(item).await.context("Cannot send event")?;
        }
        Ok(())
    }
}

#[derive(Debug, thiserror::Error, Eq, PartialEq, Copy, Clone)]
pub enum SuiteLaunchError {
    #[error("Cannot enumerate tests")]
    CaseEnumeration,

    #[error("Cannot resolve test url")]
    InstanceCannotResolve,

    #[error("Invalid arguments passed")]
    InvalidArgs,

    #[error("Cannot connect to test suite")]
    FailedToConnectToTestSuite,

    #[error("resource unavailable")]
    ResourceUnavailable,

    #[error("Some internal error occurred. Please file bug")]
    InternalError,

    #[error("No test cases matched the provided filters")]
    NoMatchingCases,
}

impl From<ftest_manager::LaunchError> for SuiteLaunchError {
    fn from(error: ftest_manager::LaunchError) -> Self {
        match error {
            ftest_manager::LaunchError::ResourceUnavailable => {
                SuiteLaunchError::ResourceUnavailable
            }
            ftest_manager::LaunchError::InstanceCannotResolve => {
                SuiteLaunchError::InstanceCannotResolve
            }
            ftest_manager::LaunchError::InvalidArgs => SuiteLaunchError::InvalidArgs,
            ftest_manager::LaunchError::FailedToConnectToTestSuite => {
                SuiteLaunchError::FailedToConnectToTestSuite
            }
            ftest_manager::LaunchError::CaseEnumeration => SuiteLaunchError::CaseEnumeration,
            ftest_manager::LaunchError::InternalError => SuiteLaunchError::InternalError,
            ftest_manager::LaunchError::NoMatchingCases => SuiteLaunchError::NoMatchingCases,
            ftest_manager::LaunchErrorUnknown!() => panic!("Encountered unknown launch error"),
        }
    }
}

/// Instance to control a single test suite run.
pub struct SuiteRunInstance {
    controller_proxy: Arc<SuiteControllerProxy>,
}

impl SuiteRunInstance {
    pub fn controller(&self) -> Arc<SuiteControllerProxy> {
        self.controller_proxy.clone()
    }

    pub async fn collect_events(&self, sender: mpsc::Sender<SuiteEvent>) -> Result<(), Error> {
        let controller_proxy = self.controller_proxy.clone();
        let mut processor = FidlSuiteEventProcessor::new();
        loop {
            match controller_proxy.get_events().await? {
                Err(e) => return Err(SuiteLaunchError::from(e).into()),
                Ok(events) => {
                    if events.len() == 0 {
                        break;
                    }
                    for event in events {
                        if let Err(e) = processor.process(event, sender.clone()).await {
                            warn!("error running test suite: {:?}", e);
                            let _ = controller_proxy.kill();
                            return Ok(());
                        }
                    }
                }
            }
        }
        Ok(())
    }
}