• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_TEST_HELPERS_H_
18 #define ANDROID_TEST_HELPERS_H_
19 
20 #include <future>
21 #include <thread>
22 
23 namespace android {
24 
25 /**
26  * Runs the given function after the specified delay.
27  * NOTE: if the std::future returned from std::async is not bound, this function
28  * will block until the task completes. This is almost certainly NOT what you
29  * want, so save the return value from delay_async into a variable:
30  *
31  * auto f = delay_async(100ms, []{ ALOGD("Hello world"); });
32  */
33 template<class Function, class Duration>
decltype(auto)34 decltype(auto) delay_async(Duration&& delay, Function&& task)
35 {
36     return std::async(std::launch::async, [=]{ std::this_thread::sleep_for(delay); task(); });
37 }
38 
39 /**
40  * Creates and opens a temporary file at the given path. The file is unlinked
41  * and closed in the destructor.
42  */
43 class TempFile {
44 public:
45     explicit TempFile(const char* path);
46     ~TempFile();
47 
48     // No copy or assign
49     TempFile(const TempFile&) = delete;
50     TempFile& operator=(const TempFile&) = delete;
51 
getName()52     const char* getName() const { return mName; }
getFd()53     int getFd() const { return mFd; }
54 
55 private:
56     char* mName;
57     int mFd;
58 };
59 
60 /**
61  * Creates a temporary directory that can create temporary files. The directory
62  * is emptied and deleted in the destructor.
63  */
64 class TempDir {
65 public:
66     TempDir();
67     ~TempDir();
68 
69     // No copy or assign
70     TempDir(const TempDir&) = delete;
71     TempDir& operator=(const TempDir&) = delete;
72 
getName()73     const char* getName() const { return mName; }
74 
75     TempFile* newTempFile();
76 
77 private:
78     char* mName;
79 };
80 
81 }  // namespace android
82 
83 #endif  // ANDROID_TEST_HELPERS_H_
84