File: PeriodicTaskTest.cpp

package info (click to toggle)
cryfs 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 28,412 kB
  • sloc: cpp: 150,187; asm: 10,493; python: 1,455; javascript: 65; sh: 50; makefile: 17; xml: 7
file content (63 lines) | stat: -rw-r--r-- 1,430 bytes parent folder | download
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
#include <gtest/gtest.h>

#include "blockstore/implementations/caching/cache/PeriodicTask.h"

#include <mutex>
#include <condition_variable>
#include <atomic>

using ::testing::Test;
using std::mutex;
using std::unique_lock;
using std::condition_variable;

using namespace blockstore::caching;

class AtomicCounter {
public:
  AtomicCounter(int count): _mutex(), _cv(), _counter(count) {}

  void decrease() {
    const unique_lock<mutex> lock(_mutex);
    --_counter;
    _cv.notify_all();
  }

  void waitForZero() {
    unique_lock<mutex> lock(_mutex);
    _cv.wait(lock, [this] () {return _counter <= 0;});
  }
private:
  mutex _mutex;
  condition_variable _cv;
  int _counter;
};

class PeriodicTaskTest: public Test {
};

TEST_F(PeriodicTaskTest, DoesntDeadlockInDestructorWhenDestructedImmediately) {
  const PeriodicTask task([](){}, 1, "test");
}

TEST_F(PeriodicTaskTest, CallsCallbackAtLeast10Times) {
  AtomicCounter counter(10);

  const PeriodicTask task([&counter](){
    counter.decrease();
  }, 0.001, "test");

  counter.waitForZero();
}

TEST_F(PeriodicTaskTest, DoesntCallCallbackAfterDestruction) {
  std::atomic<int> callCount(0);
  {
    const PeriodicTask task([&callCount](){
      callCount += 1;
    }, 0.001, "test");
  }
  const int callCountDirectlyAfterDestruction = callCount;
  boost::this_thread::sleep_for(boost::chrono::seconds(1));
  EXPECT_EQ(callCountDirectlyAfterDestruction, callCount);
}