Browse Source

handle json response with type fields on message

master
Jørgen Lien Sellæg 9 years ago
parent
commit
23ad2e63a0
  1. 10
      toREST/include/ws.hpp
  2. 41
      toREST/tests/ws_test.cpp

10
toREST/include/ws.hpp

@ -3,6 +3,7 @@
#include <boost/system/error_code.hpp> #include <boost/system/error_code.hpp>
#include <iostream> #include <iostream>
#include <util.hpp>
namespace tr { namespace tr {
namespace ws { namespace ws {
@ -32,6 +33,15 @@ void on_open(Server &server, Session &session, Connection con) {
template <class Session, class Connection, class Message> template <class Session, class Connection, class Message>
void on_message(Session &session, Connection con, Message message) { void on_message(Session &session, Connection con, Message message) {
nlohmann::json obj = util::json::parse(*message);
if (!obj.is_null() && obj.is_object()) {
auto type = util::json::get("type", obj, std::string());
if (!type.empty()) {
if (type == "POST_TORRENT_UPDATES") {
session.post_torrent_updates();
}
}
}
} }
} }
} }

41
toREST/tests/ws_test.cpp

@ -12,6 +12,12 @@ struct TestConnection {
int status_ = 0; int status_ = 0;
}; };
struct TestMessage : public std::stringstream {
std::string string() {
return str();
}
};
struct TestWsServer { struct TestWsServer {
void send_close(std::shared_ptr<TestConnection> con, int status, const std::string &reason) { void send_close(std::shared_ptr<TestConnection> con, int status, const std::string &reason) {
send_close_calls_++; send_close_calls_++;
@ -44,4 +50,39 @@ SCENARIO("we have a websocket resource") {
} }
} }
} }
auto message = std::make_shared<TestMessage>();
GIVEN("we recive an json request") {
WHEN("the json isn't valid") {
*message << "Not valid";
THEN("the server should reject the action") {
tr::ws::on_message(session, connection, message);
REQUIRE(server.send_close_calls_ == 0);
REQUIRE(session.post_torrent_updates_calls_ == 0);
}
}
WHEN("the json is valid but doesn't have any of the required fields") {
*message << "{}";
THEN("the server should reject the action") {
tr::ws::on_message(session, connection, message);
REQUIRE(server.send_close_calls_ == 0);
REQUIRE(session.post_torrent_updates_calls_ == 0);
}
}
WHEN("the json is valid and have the required fields but not of valid type") {
*message << nlohmann::json({{"type", "N/A"}});
THEN("the server should reject the action") {
tr::ws::on_message(session, connection, message);
REQUIRE(server.send_close_calls_ == 0);
REQUIRE(session.post_torrent_updates_calls_ == 0);
}
}
WHEN("the json is valid and have the required fields") {
*message << nlohmann::json({{"type", "POST_TORRENT_UPDATES"}});
THEN("the server should post torrent updates") {
tr::ws::on_message(session, connection, message);
REQUIRE(server.send_close_calls_ == 0);
REQUIRE(session.post_torrent_updates_calls_ == 1);
}
}
}
} }
Loading…
Cancel
Save