1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /***************************************************************************
3 * semaphoretest.cc
4 *
5 * Tue Jun 14 22:04:24 CEST 2016
6 * Copyright 2016 Bent Bisballe Nyeng
7 * deva@aasimon.org
8 ****************************************************************************/
9
10 /*
11 * This file is part of DrumGizmo.
12 *
13 * DrumGizmo is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU Lesser General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * DrumGizmo is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License for more details.
22 *
23 * You should have received a copy of the GNU Lesser General Public License
24 * along with DrumGizmo; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
26 */
27 #include <uunit.h>
28
29 #include <cassert>
30
31 #include <chrono>
32 #include <iostream>
33
34 #include "../src/sem.h"
35
dist(const std::chrono::duration<float> & a,const std::chrono::duration<float> & b)36 std::chrono::nanoseconds dist(const std::chrono::duration<float>& a,
37 const std::chrono::duration<float>& b)
38 {
39 if(a > b)
40 {
41 return std::chrono::duration_cast<std::chrono::nanoseconds>(a - b);
42 }
43
44 return std::chrono::duration_cast<std::chrono::nanoseconds>(b - a);
45 }
46
47 class SemaphoreTest
48 : public uUnit
49 {
50 public:
SemaphoreTest()51 SemaphoreTest()
52 {
53 uUNIT_TEST(SemaphoreTest::timeoutTest);
54 }
55
56 public:
timeoutTest()57 void timeoutTest()
58 {
59 Semaphore sem(0);
60
61 { // 1000ms timeout
62 auto start = std::chrono::steady_clock::now();
63 bool res = sem.wait(std::chrono::milliseconds(1000));
64 uUNIT_ASSERT(!res); // false means timeout
65 auto stop = std::chrono::steady_clock::now();
66
67 // Allow +/-1ms skew
68 uUNIT_ASSERT(dist((stop - start), std::chrono::milliseconds(1000))
69 < std::chrono::milliseconds(60));
70 }
71
72 { // 100ms timeout
73 auto start = std::chrono::steady_clock::now();
74 bool res = sem.wait(std::chrono::milliseconds(100));
75 uUNIT_ASSERT(!res); // false means timeout
76 auto stop = std::chrono::steady_clock::now();
77
78 // Allow +/-1ms skew
79 uUNIT_ASSERT(dist((stop - start), std::chrono::milliseconds(100))
80 < std::chrono::milliseconds(60));
81 }
82 }
83 };
84
85 // Registers the fixture into the 'registry'
86 static SemaphoreTest test;
87