1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #pragma once
6 
7 #include <cstdint>
8 
9 #include <fbl/function.h>
10 #include <fbl/string.h>
11 #include <fbl/vector.h>
12 #include <zxtest/base/observer.h>
13 #include <zxtest/base/test-info.h>
14 #include <zxtest/base/types.h>
15 
16 namespace zxtest {
17 
18 // Represents a collection of |TestInfo| with a unique name. Here all the logic for
19 // unique test definition per testcase exists. Also provides the mechanisms for
20 // |Test::SetUpTestCase| and |Test::TearDownTestCase|.
21 class TestCase {
22 public:
23     // Alias for a Filter function. Parameter names are provided for clarity.
24     // This function returns true if |test| in |test_case| should be selected.
25     using FilterFn = fbl::Function<bool(const fbl::String& test_case, const fbl::String test)>;
26 
27     TestCase() = delete;
28     TestCase(const fbl::String& name, internal::SetUpTestCaseFn set_up,
29              internal::TearDownTestCaseFn tear_down);
30     TestCase(const TestCase&) = delete;
31     TestCase(TestCase&&);
32     ~TestCase();
33 
34     TestCase& operator=(const TestCase&) = delete;
35     TestCase& operator=(TestCase&&) = delete;
36 
37     // Returns the number of registered tests.
38     size_t TestCount() const;
39 
40     // Returns the number of registered tests, matching a given filter.
41     size_t MatchingTestCount() const;
42 
43     // Filters the tests from |test_infos_| that do
44     void Filter(FilterFn filter);
45 
46     // Shuffles the test execution order |selected_indexes_|.
47     void Shuffle(std::uint32_t random_seed);
48 
49     // Restores the test execution order to match registration order. This does
50     // not remove the effects of filter.
51     void UnShuffle();
52 
53     // Returns true if registration of |test_info| into this testcase was succesful.
54     bool RegisterTest(const fbl::String& name, const SourceLocation& location,
55                       internal::TestFactory factory);
56 
57     // Executes all registered tests with the provided |driver|.
58     void Run(LifecycleObserver* lifecycle_observer, internal::TestDriver* driver);
59 
60     // Returns the name of test case.
name()61     const fbl::String& name() const { return name_; }
62 
63 private:
64     // Keeps track of the tests that were selected
65     fbl::Vector<unsigned long> selected_indexes_;
66 
67     // Tests in registration order.
68     fbl::Vector<TestInfo> test_infos_;
69 
70     // Test case name.
71     fbl::String name_;
72 
73     // Called before any test in |test_infos_| is executed.
74     internal::SetUpTestCaseFn set_up_;
75 
76     // Called after all tests in |test_infos_| are executed.
77     internal::TearDownTestCaseFn tear_down_;
78 };
79 
80 } // namespace zxtest
81