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    }
34
35    void stop(ProcessClock::time_point time) {
36        stopTimes.emplace_back(time);
37    }
38
39    std::vector<ProcessClock::time_point>& startTimes;
40    std::vector<ProcessClock::time_point>& stopTimes;
41};
42
43class ScopeTimerTest : public ::testing::Test {
44protected:
45    std::vector<ProcessClock::time_point> start;
46    std::vector<ProcessClock::time_point> stop;
47};
48
49TEST_F(ScopeTimerTest, SingleListener) {
50    { ScopeTimer1<MockTimer> timer(MockTimer(start, stop)); }
51
52    EXPECT_EQ(1u, start.size());
53    EXPECT_EQ(1u, stop.size());
54    EXPECT_GT(stop[0], start[0]);
55}
56
57TEST_F(ScopeTimerTest, TwoListeners) {
58    {
59        ScopeTimer2<MockTimer, MockTimer> timer(MockTimer(start, stop),
60                                                MockTimer(start, stop));
61    }
62
63    EXPECT_EQ(2u, start.size());
64    EXPECT_EQ(2u, stop.size());
65    EXPECT_GT(stop[0], start[0]);
66    EXPECT_GT(stop[1], start[1]);
67    EXPECT_EQ(start[0], start[1])
68            << "ScopeTimer listeners did not receive the same start time.";
69    EXPECT_EQ(stop[0], stop[1])
70            << "ScopeTimer listeners did not receive the same stop time.";
71}
72