bb232395bd1440f5c4d9d847064135e0032716f4
[folly.git] / folly / experimental / test / AutoTimerTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <gtest/gtest.h>
17
18 #include <folly/experimental/AutoTimer.h>
19
20 using namespace folly;
21 using namespace std;
22
23 struct StubLogger {
24   void operator()(StringPiece msg, double sec) {
25     m = msg;
26     t = sec;
27   }
28   static StringPiece m;
29   static double t;
30 };
31
32 StringPiece StubLogger::m = "";
33 double StubLogger::t = 0;
34
35 struct StubClock {
36   typedef std::chrono::seconds duration;
37
38   static std::chrono::time_point<StubClock> now() {
39     return std::chrono::time_point<StubClock>(std::chrono::duration<int>(t));
40   }
41   static int t;
42 };
43
44 int StubClock::t = 0;
45
46 TEST(TestAutoTimer, HandleBasic) {
47   StubClock::t = 1;
48   AutoTimer<StubLogger, StubClock> timer;
49   StubClock::t = 3;
50   timer.log("foo");
51   ASSERT_EQ("foo", StubLogger::m);
52   ASSERT_EQ(2, StubLogger::t);
53 }
54
55 TEST(TestAutoTimer, HandleLogOnDestruct) {
56   {
57     StubClock::t = 0;
58     AutoTimer<StubLogger, StubClock> timer("message");
59     StubClock::t = 3;
60     timer.log("foo");
61     EXPECT_EQ("foo", StubLogger::m);
62     EXPECT_EQ(3, StubLogger::t);
63     StubClock::t = 5;
64   }
65   ASSERT_EQ("message", StubLogger::m);
66   ASSERT_EQ(2, StubLogger::t);
67 }
68
69 TEST(TestAutoTimer, HandleRealTimer) {
70   AutoTimer<> t("Third message on destruction");
71   t.log("First message");
72   t.log("Second message");
73 }