1#include <csf/BasicNetwork.h>
3#include <csf/Scheduler.h>
4#include <gtest/gtest.h>
18 Peer(Peer
const&) =
default;
19 Peer(Peer&&) =
default;
21 explicit Peer(
int id) : id(id)
27 start(csf::Scheduler& scheduler, Net& net)
29 using namespace std::chrono_literals;
30 auto t = scheduler.in(1s, [&] { set.insert(0); });
33 for (
auto const link : net.links(
this))
35 net.send(
this, link.target, [&, to = link.target] { to->receive(net, this, 1); });
46 receive(Net& net, Peer* from,
int m)
52 for (
auto const link : net.links(
this))
54 net.send(
this, link.target, [&, mm = m, to = link.target] {
55 to->receive(net, this, mm);
64TEST(BasicNetworkTest, network)
66 using namespace std::chrono_literals;
73 EXPECT_TRUE(!net.
connect(&pv[0], &pv[0]));
74 EXPECT_TRUE(net.
connect(&pv[0], &pv[1], 1s));
75 EXPECT_TRUE(net.
connect(&pv[1], &pv[2], 1s));
76 EXPECT_TRUE(!net.
connect(&pv[0], &pv[1]));
78 peer.start(scheduler, net);
79 EXPECT_TRUE(scheduler.
stepFor(0s));
80 EXPECT_TRUE(scheduler.
stepFor(1s));
81 EXPECT_TRUE(scheduler.
step());
82 EXPECT_TRUE(!scheduler.
step());
83 EXPECT_TRUE(!scheduler.
stepFor(1s));
84 net.
send(&pv[0], &pv[1], [] {});
85 net.
send(&pv[1], &pv[0], [] {});
90 auto const links = net.
links(&pv[1]);
93 EXPECT_TRUE(net.
disconnect(&pv[1], links[0].target));
100TEST(BasicNetworkTest, disconnect)
102 using namespace std::chrono_literals;
105 EXPECT_TRUE(net.
connect(0, 1, 1s));
106 EXPECT_TRUE(net.
connect(0, 2, 2s));
109 net.
send(0, 1, [&]() { delivered.
insert(1); });
110 net.
send(0, 2, [&]() { delivered.
insert(2); });
112 scheduler.
in(1000ms, [&]() { EXPECT_TRUE(net.
disconnect(0, 2)); });
113 scheduler.
in(1100ms, [&]() { EXPECT_TRUE(net.
connect(0, 2)); });
Peer to peer network simulator.
bool connect(Peer const &from, Peer const &to, duration const &delay=std::chrono::seconds{0})
Connect two peers.
auto links(Peer const &from)
Return the range of active links.
bool disconnect(Peer const &peer1, Peer const &peer2)
Break a link.
void send(Peer const &from, Peer const &to, Function &&f)
Send a message to a peer.
Simulated discrete-event scheduler.
bool step()
Run the scheduler until no events remain.
CancelToken in(duration const &delay, Function &&f)
Schedule an event after a specified duration passes.
bool stepFor(std::chrono::duration< Period, Rep > const &amount)
Run the scheduler until time has elapsed.
T emplace_back(T... args)
bool set(T &target, std::string const &name, Section const §ion)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...