1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2018 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17
18#include <platform/scope_timer.h>
19
20#include <gtest/gtest.h>
21
22#include <vector>
23
24class MockTimer {
25public:
26    MockTimer(std::vector<ProcessClock::time_point>& startTimes,
27              std::vector<ProcessClock::time_point>& stopTimes)
28        : startTimes(startTimes), stopTimes(stopTimes) {
29    }
30
31    void start(ProcessClock::time_point time) {
32        startTimes.emplace_back(time);
33        startCalled = true;
34    }
35
36    void stop(ProcessClock::time_point time) {
37        EXPECT_TRUE(startCalled);
38        stopTimes.emplace_back(time);
39    }
40
41    bool startCalled = false;
42    std::vector<ProcessClock::time_point>& startTimes;
43    std::vector<ProcessClock::time_point>& stopTimes;
44};
45
46class ScopeTimerTest : public ::testing::Test {
47protected:
48    std::vector<ProcessClock::time_point> start;
49    std::vector<ProcessClock::time_point> stop;
50};
51
52TEST_F(ScopeTimerTest, SingleListener) {
53    { ScopeTimer1<MockTimer> timer(MockTimer(start, stop)); }
54
55    EXPECT_EQ(1u, start.size());
56    EXPECT_EQ(1u, stop.size());
57    EXPECT_GT(stop[0], start[0]);
58}
59
60TEST_F(ScopeTimerTest, TwoListeners) {
61    {
62        ScopeTimer2<MockTimer, MockTimer> timer(MockTimer(start, stop),
63                                                MockTimer(start, stop));
64    }
65
66    EXPECT_EQ(2u, start.size());
67    EXPECT_EQ(2u, stop.size());
68    EXPECT_GT(stop[0], start[0]);
69    EXPECT_GT(stop[1], start[1]);
70    EXPECT_EQ(start[0], start[1])
71            << "ScopeTimer listeners did not receive the same start time.";
72    EXPECT_EQ(stop[0], stop[1])
73            << "ScopeTimer listeners did not receive the same stop time.";
74}
75