2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/futures/detail/FSM.h>
18 #include <folly/portability/GTest.h>
20 using namespace folly::futures::detail;
22 enum class State { A, B };
25 FSM<State> fsm(State::A);
27 int unprotectedCount = 0;
29 // somebody set up us the switch
30 auto tryTransition = [&]{
31 switch (fsm.getState()) {
33 return fsm.updateState(State::A, State::B, [&]{ count++; });
35 return fsm.updateState(State::B, State::A,
36 [&]{ count--; }, [&]{ unprotectedCount--; });
38 return false; // unreachable
41 // keep retrying until success (like a cas)
42 while (!tryTransition()) {
45 EXPECT_EQ(State::B, fsm.getState());
47 EXPECT_EQ(0, unprotectedCount);
49 while (!tryTransition()) {
52 EXPECT_EQ(State::A, fsm.getState());
54 EXPECT_EQ(-1, unprotectedCount);
57 TEST(FSM, magicMacrosExample) {
61 int unprotectedCount = 0;
62 MyFSM() : fsm_(State::A) {}
65 FSM_CASE(fsm_, State::A, State::B, [&]{ count++; });
66 FSM_CASE2(fsm_, State::B, State::A,
67 [&]{ count--; }, [&]{ unprotectedCount--; });
75 EXPECT_EQ(State::B, fsm.fsm_.getState());
76 EXPECT_EQ(1, fsm.count);
77 EXPECT_EQ(0, fsm.unprotectedCount);
80 EXPECT_EQ(State::A, fsm.fsm_.getState());
81 EXPECT_EQ(0, fsm.count);
82 EXPECT_EQ(-1, fsm.unprotectedCount);
87 FSM<State> fsm(State::A);
88 EXPECT_EQ(State::A, fsm.getState());
92 FSM<State> fsm(State::A);
93 EXPECT_TRUE(fsm.updateState(State::A, State::B, []{}));
94 EXPECT_EQ(State::B, fsm.getState());
97 TEST(FSM, badUpdate) {
98 FSM<State> fsm(State::A);
99 EXPECT_FALSE(fsm.updateState(State::B, State::A, []{}));
102 TEST(FSM, actionOnUpdate) {
103 FSM<State> fsm(State::A);
105 fsm.updateState(State::A, State::B, [&]{ count++; });
109 TEST(FSM, noActionOnBadUpdate) {
110 FSM<State> fsm(State::A);
112 fsm.updateState(State::B, State::A, [&]{ count++; });
116 TEST(FSM, stateTransitionAfterAction) {
117 FSM<State> fsm(State::A);
118 fsm.updateState(State::A, State::B,
119 [&]{ EXPECT_EQ(State::A, fsm.getState()); });