Copyright 2013 -> 2014
[folly.git] / folly / test / LazyTest.cpp
1 /*
2  * Copyright 2014 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 "folly/Lazy.h"
17
18 #include <map>
19 #include <functional>
20 #include <iostream>
21
22 #include <gtest/gtest.h>
23
24 namespace folly {
25
26 TEST(Lazy, Simple) {
27   int computeCount = 0;
28
29   auto const val = folly::lazy([&]() -> int {
30     EXPECT_EQ(++computeCount, 1);
31     return 12;
32   });
33   EXPECT_EQ(computeCount, 0);
34
35   for (int i = 0; i < 100; ++i) {
36     if (i > 50) {
37       EXPECT_EQ(val(), 12);
38       EXPECT_EQ(computeCount, 1);
39     } else {
40       EXPECT_EQ(computeCount, 0);
41     }
42   }
43   EXPECT_EQ(val(), 12);
44   EXPECT_EQ(computeCount, 1);
45 }
46
47 auto globalCount = folly::lazy([]{ return 0; });
48 auto const foo = folly::lazy([]() -> std::string {
49   EXPECT_EQ(++globalCount(), 1);
50   return std::string("YEP");
51 });
52
53 TEST(Lazy, Global) {
54   EXPECT_EQ(globalCount(), 0);
55   EXPECT_EQ(foo(), "YEP");
56   EXPECT_EQ(globalCount(), 1);
57 }
58
59 TEST(Lazy, Map) {
60   auto lazyMap = folly::lazy([]() -> std::map<std::string,std::string> {
61     return {
62       { "foo", "bar" },
63       { "baz", "quux" }
64     };
65   });
66
67   EXPECT_EQ(lazyMap().size(), 2);
68   lazyMap()["blah"] = "asd";
69   EXPECT_EQ(lazyMap().size(), 3);
70 }
71
72 struct CopyCount {
73   CopyCount() {}
74   CopyCount(const CopyCount&) { ++count; }
75   CopyCount(CopyCount&&)      {}
76
77   static int count;
78
79   bool operator()() const { return true ; }
80 };
81
82 int CopyCount::count = 0;
83
84 TEST(Lazy, NonLambda) {
85   auto const rval = folly::lazy(CopyCount());
86   EXPECT_EQ(CopyCount::count, 0);
87   EXPECT_EQ(rval(), true);
88   EXPECT_EQ(CopyCount::count, 0);
89
90   CopyCount cpy;
91   auto const lval = folly::lazy(cpy);
92   EXPECT_EQ(CopyCount::count, 1);
93   EXPECT_EQ(lval(), true);
94   EXPECT_EQ(CopyCount::count, 1);
95
96   std::function<bool()> f = [&]{ return 12; };
97   auto const lazyF = folly::lazy(f);
98   EXPECT_EQ(lazyF(), true);
99 }
100
101 TEST(Lazy, Consty) {
102   std::function<int ()> const f = [&] { return 12; };
103   auto lz = folly::lazy(f);
104   EXPECT_EQ(lz(), 12);
105 }
106
107 }
108