Files
scylladb/tests/observable_test.cc
Avi Kivity 96737d140f utils: add observer/observable templates
An observable is used to decouple an information producer from a consumer
(in the same way as a callback), while allowing multiple consumers (called
observers) to coexist and to manage their lifetime separately.

Two classes are introduced:

 observable: a producer class; when an observable is invoked all observers
        receive the information
 observer: a consumer class; receives information from a observable

Modelled after boost::signals2, with the following changes
 - all signals return void; information is passed from the producer to
   the consumer but not back
 - thread-unsafe
 - modern C++ without preprocessor hacks
 - connection lifetime is always managed rather than leaked by default
 - renamed to avoid the funky "slot" name
Message-Id: <20180709172726.5079-1-avi@scylladb.com>
2018-07-09 18:48:44 +01:00

72 lines
2.0 KiB
C++

/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE observable_test
#include <boost/test/unit_test.hpp>
#include "../utils/observable.hh"
using namespace utils;
BOOST_AUTO_TEST_CASE(test_basic_functionality) {
observable<int> pub;
int v1 = 0, v2 = 0;
observer<int> sub1 = pub.observe([&] (int x) { v1 = x; });
observer<int> sub2 = pub.observe([&] (int x) { v2 = x; });
pub(7);
BOOST_REQUIRE_EQUAL(v1, 7);
BOOST_REQUIRE_EQUAL(v2, 7);
sub1.disconnect();
pub(3);
BOOST_REQUIRE_EQUAL(v1, 7);
BOOST_REQUIRE_EQUAL(v2, 3);
sub1 = std::move(sub2);
pub(4);
BOOST_REQUIRE_EQUAL(v1, 7);
BOOST_REQUIRE_EQUAL(v2, 4);
pub = observable<int>();
pub(5);
BOOST_REQUIRE_EQUAL(v1, 7);
BOOST_REQUIRE_EQUAL(v2, 4);
}
BOOST_AUTO_TEST_CASE(test_exceptions) {
observable<> pub;
bool saw1 = false;
observer<> sub1 = pub.observe([&] { saw1 = true; });
observer<> sub2 = pub.observe([&] { throw 2; });
bool saw3 = false;
observer<> sub3 = pub.observe([&] { saw3 = true; });
observer<> sub4 = pub.observe([&] { throw 4; });
bool caught = false;
try {
pub();
} catch (int v) {
BOOST_REQUIRE(saw1);
BOOST_REQUIRE(saw3);
BOOST_REQUIRE(v == 2 || v == 4);
caught = true;
}
BOOST_REQUIRE(caught);
}