2b54c3066a8bf64d6ec6372a99a623b74f4eec2e
[folly.git] / folly / io / async / test / DelayedDestructionBaseTest.cpp
1 /*
2  * Copyright 2017 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 /*
17  * Licensed to the Apache Software Foundation (ASF) under one
18  * or more contributor license agreements. See the NOTICE file
19  * distributed with this work for additional information
20  * regarding copyright ownership. The ASF licenses this file
21  * to you under the Apache License, Version 2.0 (the
22  * "License"); you may not use this file except in compliance
23  * with the License. You may obtain a copy of the License at
24  *
25  *   http://www.apache.org/licenses/LICENSE-2.0
26  *
27  * Unless required by applicable law or agreed to in writing,
28  * software distributed under the License is distributed on an
29  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
30  * KIND, either express or implied. See the License for the
31  * specific language governing permissions and limitations
32  * under the License.
33  */
34 #include <folly/io/async/DelayedDestructionBase.h>
35
36 #include <functional>
37
38 #include <folly/portability/GTest.h>
39
40 using namespace folly;
41
42 class DestructionOnCallback : public DelayedDestructionBase {
43  public:
44   DestructionOnCallback() : state_(0), deleted_(false) {
45   }
46
47   void onComplete(int n, int& state) {
48     DestructorGuard dg(this);
49     for (auto i = n; i >= 0; --i) {
50       onStackedComplete(i);
51     }
52     state = state_;
53   }
54
55   int state() const { return state_; }
56   bool deleted() const { return deleted_; }
57
58  protected:
59   void onStackedComplete(int recur) {
60     DestructorGuard dg(this);
61     ++state_;
62     if (recur <= 0) {
63       return;
64     }
65     onStackedComplete(--recur);
66   }
67  private:
68   int state_;
69   bool deleted_;
70
71   void onDelayedDestroy(bool delayed) override {
72     deleted_ = true;
73     delete this;
74     (void)delayed; // prevent unused variable warnings
75   }
76 };
77
78 struct DelayedDestructionBaseTest : public ::testing::Test {
79 };
80
81 TEST_F(DelayedDestructionBaseTest, basic) {
82   DestructionOnCallback* d = new DestructionOnCallback();
83   EXPECT_NE(d, nullptr);
84   int32_t state;
85   d->onComplete(3, state);
86   EXPECT_EQ(state, 10); // 10 = 6 + 3 + 1
87 }