blob: d26adfb302a0f24dabf2099f5e9ad35893aa4a7d [file] [log] [blame]
Tim Kilbourn73475a42015-02-13 10:35:20 -08001/*
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
23namespace 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 */
33template<class Function, class Duration>
34decltype(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 */
43class TempFile {
44public:
Chih-Hung Hsieh928e6792016-06-30 14:17:31 -070045 explicit TempFile(const char* path);
Tim Kilbourn73475a42015-02-13 10:35:20 -080046 ~TempFile();
47
48 // No copy or assign
49 TempFile(const TempFile&) = delete;
50 TempFile& operator=(const TempFile&) = delete;
51
52 const char* getName() const { return mName; }
53 int getFd() const { return mFd; }
54
55private:
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 */
64class TempDir {
65public:
66 TempDir();
67 ~TempDir();
68
69 // No copy or assign
70 TempDir(const TempDir&) = delete;
71 TempDir& operator=(const TempDir&) = delete;
72
73 const char* getName() const { return mName; }
74
75 TempFile* newTempFile();
76
77private:
78 char* mName;
79};
80
81} // namespace android
82
83#endif // ANDROID_TEST_HELPERS_H_