yarp-devices
FutureObserverLib.hpp
1 // -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
2 
3 #ifndef __FUTURE_OBSERVER_HPP__
4 #define __FUTURE_OBSERVER_HPP__
5 
6 #include "gtest/gtest.h"
7 
8 #include <chrono>
9 #include <functional>
10 #include <future>
11 #include <thread>
12 #include <utility>
13 #include <vector>
14 
15 namespace roboticslab::test
16 {
17 
29 {
30 public:
32  virtual ~FutureObserver() = default;
33 
35  void shutdown()
36  {
37  for (auto f : futures)
38  {
39  if (f->valid())
40  {
41  f->wait();
42  }
43 
44  delete f;
45  }
46  }
47 
49  std::future<void> & f()
50  {
51  auto * f = new std::future<void>;
52  futures.push_back(f);
53  return *f;
54  }
55 
56  static constexpr int MILLIS = 50;
57 
58 private:
59  std::vector<std::future<void> *> futures;
60 };
61 
66 class observer_timer final
67 {
68 public:
70  template<typename Fn>
71  observer_timer(int _milliseconds, Fn && _fn)
72  : milliseconds(_milliseconds), fn(std::move(_fn))
73  { }
74 
76  void operator()()
77  {
78  std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
79  ASSERT_TRUE(fn());
80  }
81 
82 private:
83  int milliseconds;
84  std::function<bool()> fn;
85 };
86 
87 } // namespace roboticslab::test
88 
89 #endif // __FUTURE_OBSERVER_HPP__
Registers asynchronous operations.
Definition: FutureObserverLib.hpp:29
virtual ~FutureObserver()=default
Virtual destructor.
void shutdown()
Finalize all pending tasks and clean queue.
Definition: FutureObserverLib.hpp:35
std::future< void > & f()
Register an asynchronous operation that can be assigned thereafter.
Definition: FutureObserverLib.hpp:49
Functor wait-with-callback class.
Definition: FutureObserverLib.hpp:67
void operator()()
Wait and call stored function.
Definition: FutureObserverLib.hpp:76
observer_timer(int _milliseconds, Fn &&_fn)
Register function object and configure wait time.
Definition: FutureObserverLib.hpp:71
Contains classes related to unit testing.
Definition: groups.dox:10