2 * Copyright 2014 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 <gtest/gtest.h>
18 #include <folly/futures/detail/FSM.h>
20 using namespace folly::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()) ;
43 EXPECT_EQ(State::B, fsm.getState());
45 EXPECT_EQ(0, unprotectedCount);
47 while (!tryTransition()) ;
48 EXPECT_EQ(State::A, fsm.getState());
50 EXPECT_EQ(-1, unprotectedCount);
53 TEST(FSM, magicMacrosExample) {
57 int unprotectedCount = 0;
58 MyFSM() : fsm_(State::A) {}
61 FSM_CASE(fsm_, State::A, State::B, [&]{ count++; });
62 FSM_CASE2(fsm_, State::B, State::A,
63 [&]{ count--; }, [&]{ unprotectedCount--; });
71 EXPECT_EQ(State::B, fsm.fsm_.getState());
72 EXPECT_EQ(1, fsm.count);
73 EXPECT_EQ(0, fsm.unprotectedCount);
76 EXPECT_EQ(State::A, fsm.fsm_.getState());
77 EXPECT_EQ(0, fsm.count);
78 EXPECT_EQ(-1, fsm.unprotectedCount);
83 FSM<State> fsm(State::A);
84 EXPECT_EQ(State::A, fsm.getState());
88 FSM<State> fsm(State::A);
89 EXPECT_TRUE(fsm.updateState(State::A, State::B, []{}));
90 EXPECT_EQ(State::B, fsm.getState());
93 TEST(FSM, badUpdate) {
94 FSM<State> fsm(State::A);
95 EXPECT_FALSE(fsm.updateState(State::B, State::A, []{}));
98 TEST(FSM, actionOnUpdate) {
99 FSM<State> fsm(State::A);
101 fsm.updateState(State::A, State::B, [&]{ count++; });
105 TEST(FSM, noActionOnBadUpdate) {
106 FSM<State> fsm(State::A);
108 fsm.updateState(State::B, State::A, [&]{ count++; });
112 TEST(FSM, stateTransitionAfterAction) {
113 FSM<State> fsm(State::A);
114 fsm.updateState(State::A, State::B,
115 [&]{ EXPECT_EQ(State::A, fsm.getState()); });