1d7ab3fc20129d14108df8192fd50da225f386b2
[folly.git] / folly / io / async / test / DelayedDestructionBaseTest.cpp
1 /*
2  * Copyright 2016 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 #include <gtest/gtest.h>
38 #include <list>
39 #include <vector>
40
41 using namespace folly;
42
43 class DestructionOnCallback : public DelayedDestructionBase {
44  public:
45   DestructionOnCallback() : state_(0), deleted_(false) {
46   }
47
48   void onComplete(int n, int& state) {
49     DestructorGuard dg(this);
50     for (auto i = n; i >= 0; --i) {
51       onStackedComplete(i);
52     }
53     state = state_;
54   }
55
56   int state() const { return state_; }
57   bool deleted() const { return deleted_; }
58
59  protected:
60   void onStackedComplete(int recur) {
61     DestructorGuard dg(this);
62     ++state_;
63     if (recur <= 0) {
64       return;
65     }
66     onStackedComplete(--recur);
67   }
68  private:
69   int state_;
70   bool deleted_;
71
72   void onDelayedDestroy(bool delayed) override {
73     deleted_ = true;
74     delete this;
75     (void)delayed; // prevent unused variable warnings
76   }
77 };
78
79 struct DelayedDestructionBaseTest : public ::testing::Test {
80 };
81
82 TEST_F(DelayedDestructionBaseTest, basic) {
83   DestructionOnCallback* d = new DestructionOnCallback();
84   EXPECT_NE(d, nullptr);
85   int32_t state;
86   d->onComplete(3, state);
87   EXPECT_EQ(state, 10); // 10 = 6 + 3 + 1
88 }