Commit b37fc34b authored by Pavel Vainerman's avatar Pavel Vainerman

[uwebsocketgate]: added simple tests

parent dedec481
......@@ -594,6 +594,7 @@ AC_CONFIG_FILES([Makefile
extensions/HttpResolver/Makefile
extensions/HttpResolver/tests/Makefile
extensions/UWebSocketGate/Makefile
extensions/UWebSocketGate/tests/Makefile
testsuite/Makefile
wrappers/Makefile
wrappers/python/lib/Makefile
......
......@@ -7,7 +7,7 @@ SUBDIRS = lib include SharedMemory SharedMemory/tests IOControl IOControl/tests
ModbusMaster ModbusSlave SMViewer UniNetwork UNetUDP UNetUDP/tests \
DBServer-MySQL DBServer-SQLite DBServer-PostgreSQL MQTTPublisher \
RRDServer tests ModbusMaster/tests ModbusSlave/tests LogDB LogDB/tests \
Backend-OpenTSDB HttpResolver HttpResolver/tests UWebSocketGate
Backend-OpenTSDB HttpResolver HttpResolver/tests UWebSocketGate UWebSocketGate/tests
pkgconfigdir = $(libdir)/pkgconfig
......
......@@ -190,7 +190,7 @@ Poco::JSON::Object::Ptr UWebSocketGate::to_json( const SensorMessage* sm, const
json->set("name", uniset::ORepHelpers::getShortName(uniset_conf()->oind->getMapName(sm->id)));
json->set("sm_tv_sec", sm->sm_tv.tv_sec);
json->set("sm_tv_nsec", sm->sm_tv.tv_nsec);
json->set("sm_type", uniset::iotype2str(sm->sensor_type));
json->set("iotype", uniset::iotype2str(sm->sensor_type));
json->set("undefined", sm->undefined );
json->set("supplier", sm->supplier );
json->set("tv_sec", sm->tm.tv_sec);
......@@ -537,20 +537,20 @@ std::shared_ptr<UWebSocketGate::UWebSocket> UWebSocketGate::newWebSocket( Poco::
auto idlist = uniset::explode(slist);
if( idlist.empty() )
{
resp->setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp->setContentType("text/html");
resp->setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
resp->setContentLength(0);
std::ostream& err = resp->send();
err << "Error: no list of sensors for '" << slist << "'. Use: http://host:port/wsgate/?s1,s2,s3";
err.flush();
// if( idlist.empty() )
// {
// resp->setStatus(HTTPResponse::HTTP_BAD_REQUEST);
// resp->setContentType("text/html");
// resp->setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
// resp->setContentLength(0);
// std::ostream& err = resp->send();
// err << "Error: no list of sensors for '" << slist << "'. Use: http://host:port/wsgate/?s1,s2,s3";
// err.flush();
mywarn << myname << "(newWebSocket): error: no list of sensors for '" << slist << "'" << endl;
// mywarn << myname << "(newWebSocket): error: no list of sensors for '" << slist << "'" << endl;
return nullptr;
}
// return nullptr;
// }
{
uniset_rwmutex_wrlock lock(wsocksMutex);
......@@ -799,7 +799,14 @@ void UWebSocketGate::UWebSocket::set( uniset::ObjectId id, long value )
{
s->second.value = value;
s->second.cmd = "set";
return;
}
sinfo si;
si.id = id;
si.value = value;
si.cmd = "set";
smap.emplace(id, si);
}
// -----------------------------------------------------------------------------
void UWebSocketGate::UWebSocket::sensorInfo( const uniset::SensorMessage* sm )
......
if HAVE_TESTS
noinst_PROGRAMS = tests-with-sm
tests_with_sm_SOURCES = tests_with_sm.cc test_uwebsocketgate.cc $(top_builddir)/extensions/UWebSocketGate/UWebSocketGate.cc
tests_with_sm_LDADD = $(top_builddir)/lib/libUniSet2.la $(top_builddir)/extensions/lib/libUniSet2Extensions.la \
$(top_builddir)/extensions/SharedMemory/libUniSet2SharedMemory.la \
$(SIGC_LIBS) $(POCO_LIBS)
tests_with_sm_CPPFLAGS = -I$(top_builddir)/include -I$(top_builddir)/extensions/include \
-I$(top_builddir)/extensions/UWebSocketGate \
-I$(top_builddir)/extensions/SharedMemory $(SIGC_CFLAGS) $(POCO_CFLAGS)
include $(top_builddir)/testsuite/testsuite-common.mk
check-local: atconfig package.m4 $(TESTSUITE) uwebsocketgate-tests.at
$(SHELL) $(TESTSUITE) $(TESTSUITEFLAGS)
clean-local:
rm -rf $(CLEANFILES)
rm -rf $(COVERAGE_REPORT_DIR)
include $(top_builddir)/include.mk
endif
#include <catch.hpp>
// -----------------------------------------------------------------------------
#include <time.h>
#include <limits>
#include <memory>
#include <iostream>
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/JSON/Parser.h"
#include "UniSetTypes.h"
#include "UInterface.h"
// -----------------------------------------------------------------------------
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::Net::WebSocket;
using namespace std;
using namespace uniset;
// -----------------------------------------------------------------------------
static int port = 8081;
static string addr("127.0.0.1"); // conf->getArgParam("--mbs-inet-addr");
static std::shared_ptr<UInterface> ui;
// -----------------------------------------------------------------------------
static void InitTest()
{
auto conf = uniset_conf();
CHECK( conf != nullptr );
if( !ui )
{
ui = std::make_shared<UInterface>();
// UI понадобиться для проверки записанных в SM значений.
CHECK( ui->getObjectIndex() != nullptr );
CHECK( ui->getConf() == conf );
}
}
// -----------------------------------------------------------------------------
TEST_CASE("[UWebSocketGate]: set", "[uwebsocketgate]")
{
InitTest();
HTTPClientSession cs(addr, port);
HTTPRequest request(HTTPRequest::HTTP_GET, "/wsgate", HTTPRequest::HTTP_1_1);
HTTPResponse response;
WebSocket ws(cs, request, response);
std::string cmd("set:1=10,2=20,3=30");
ws.sendFrame(cmd.data(), (int)cmd.size());
msleep(50);
REQUIRE( ui->getValue(1) == 10 );
REQUIRE( ui->getValue(2) == 20 );
REQUIRE( ui->getValue(3) == 30 );
// char buffer[1024] = {};
// int flags;
// ws.receiveFrame(buffer, sizeof(buffer), flags);
// REQUIRE(flags == WebSocket::FRAME_TEXT);
}
// -----------------------------------------------------------------------------
TEST_CASE("[UWebSocketGate]: ask", "[uwebsocketgate]")
{
InitTest();
HTTPClientSession cs(addr, port);
HTTPRequest request(HTTPRequest::HTTP_GET, "/wsgate", HTTPRequest::HTTP_1_1);
HTTPResponse response;
WebSocket ws(cs, request, response);
ui->setValue(1, 1);
ui->setValue(2, 42);
ui->setValue(3, 42);
std::string cmd("ask:1,2,3");
ws.sendFrame(cmd.data(), (int)cmd.size());
char buffer[1024] = {};
int flags;
ws.receiveFrame(buffer, sizeof(buffer), flags);
REQUIRE(flags == WebSocket::FRAME_TEXT);
Poco::JSON::Parser parser;
auto result = parser.parse(buffer);
Poco::JSON::Object::Ptr json = result.extract<Poco::JSON::Object::Ptr>();
REQUIRE(json);
// {
// "data": [
// {"type": "SensorInfo"...},
// {"type": "SensorInfo"...},
// {"type": "SensorInfo"...}
// ...
// ]
// }
auto jdata = json->get("data").extract<Poco::JSON::Array::Ptr>();
REQUIRE(jdata);
REQUIRE(jdata->size() == 3);
for( int i = 0; i < 3; i++ )
{
auto j = jdata->getObject(i);
REQUIRE(j);
REQUIRE( j->get("type").convert<std::string>() == "SensorInfo" );
long id = j->get("id").convert<long>();
if( id == 1 )
{
REQUIRE( j->get("iotype").convert<std::string>() == "DI" );
REQUIRE( j->get("value").convert<long>() == 1 );
}
else
{
REQUIRE( j->get("iotype").convert<std::string>() == "AI" );
REQUIRE( j->get("value").convert<long>() == 42 );
}
}
// sensorInfo
ui->setValue(2, 84);
memset(buffer, 0, sizeof(buffer));
ws.receiveFrame(buffer, sizeof(buffer), flags);
REQUIRE(flags == WebSocket::FRAME_TEXT);
result = parser.parse(buffer);
json = result.extract<Poco::JSON::Object::Ptr>();
REQUIRE(json);
jdata = json->get("data").extract<Poco::JSON::Array::Ptr>();
REQUIRE(jdata);
REQUIRE(jdata->size() == 1);
auto j = jdata->getObject(0);
REQUIRE(j);
REQUIRE( j->get("type").convert<std::string>() == "SensorInfo" );
REQUIRE( j->get("iotype").convert<std::string>() == "AI" );
REQUIRE( j->get("value").convert<long>() == 84 );
}
// -----------------------------------------------------------------------------
TEST_CASE("[UWebSocketGate]: del", "[uwebsocketgate]")
{
InitTest();
HTTPClientSession cs(addr, port);
HTTPRequest request(HTTPRequest::HTTP_GET, "/wsgate", HTTPRequest::HTTP_1_1);
HTTPResponse response;
WebSocket ws(cs, request, response);
ui->setValue(1, 1);
std::string cmd("ask:1");
ws.sendFrame(cmd.data(), (int)cmd.size());
char buffer[1024] = {};
int flags;
ws.receiveFrame(buffer, sizeof(buffer), flags);
REQUIRE(flags == WebSocket::FRAME_TEXT);
cmd = ("del:1");
ws.sendFrame(cmd.data(), (int)cmd.size());
msleep(100);
ui->setValue(1, 0);
memset(buffer, 0, sizeof(buffer));
ws.receiveFrame(buffer, sizeof(buffer), flags);
string str(buffer);
REQUIRE( str.find("Ping") != string::npos );
}
// -----------------------------------------------------------------------------
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <string>
#include "Debug.h"
#include "UniSetActivator.h"
#include "PassiveTimer.h"
#include "SharedMemory.h"
#include "Extensions.h"
#include "UWebSocketGate.h"
// --------------------------------------------------------------------------
using namespace std;
using namespace uniset;
using namespace uniset::extensions;
// --------------------------------------------------------------------------
int main(int argc, const char* argv[] )
{
try
{
Catch::Session session;
if( argc > 1 && ( strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0 ) )
{
cout << "--confile - Использовать указанный конф. файл. По умолчанию configure.xml" << endl;
SharedMemory::help_print(argc, argv);
cout << endl << endl << "--------------- CATCH HELP --------------" << endl;
session.showHelp("test_with_sm");
return 0;
}
int returnCode = session.applyCommandLine( argc, argv, Catch::Session::OnUnusedOptions::Ignore );
if( returnCode != 0 ) // Indicates a command line error
return returnCode;
auto conf = uniset_init(argc, argv);
bool apart = findArgParam("--apart", argc, argv) != -1;
auto shm = SharedMemory::init_smemory(argc, argv);
if( !shm )
return 1;
auto ws = UWebSocketGate::init_wsgate(argc, argv, "ws-");
if( !ws )
return 1;
auto act = UniSetActivator::Instance();
act->add(shm);
act->add(ws);
SystemMessage sm(SystemMessage::StartUp);
act->broadcast( sm.transport_msg() );
act->run(true);
int tout = 6000;
PassiveTimer pt(tout);
while( !pt.checkTime() && !act->exist() && !ws->exist() )
msleep(100);
if( !act->exist() )
{
cerr << "(tests_with_sm): SharedMemory not exist! (timeout=" << tout << ")" << endl;
return 1;
}
if( !ws->exist() )
{
cerr << "(tests_with_sm): UWebSocketGate not exist! (timeout=" << tout << ")" << endl;
return 1;
}
return session.run();
}
catch( const SystemError& err )
{
cerr << "(tests_with_sm): " << err << endl;
}
catch( const uniset::Exception& ex )
{
cerr << "(tests_with_sm): " << ex << endl;
}
catch( const std::exception& e )
{
cerr << "(tests_with_sm): " << e.what() << endl;
}
catch(...)
{
cerr << "(tests_with_sm): catch(...)" << endl;
}
return 1;
}
#!/bin/sh
# '--' - нужен для отделения аргументов catch, от наших..
cd ../../../Utilities/Admin/
./uniset2-start.sh -f ./create_links.sh
./uniset2-start.sh -f ./create
./uniset2-start.sh -f ./exist | grep -q UNISET_PLC/Controllers || exit 1
cd -
./uniset2-start.sh -f ./tests-with-sm $* -- --confile uwebsocketgate-test-configure.xml --e-startup-pause 10 \
--ws-name UWebSocketGate1 --ws-httpserverhost-addr 127.0.0.1 --ws-httpserver-port 8081
#--ws-log-add-levels any
m4_include(package.m4)
AT_COLOR_TESTS
AT_INIT([UWebSocketGate tests])
m4_include(uwebsocketgate-tests.at)
../../../Utilities/scripts/uniset2-functions.sh
\ No newline at end of file
../../../Utilities/scripts/uniset2-start.sh
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<UNISETPLC xmlns:xi="http://www.w3.org/2001/XInclude">
<UserData/>
<!-- Общие(стартовые) параметры по UniSet -->
<UniSet>
<NameService host="localhost" port="2809"/>
<LocalNode name="LocalhostNode"/>
<RootSection name="UNISET_PLC"/>
<CountOfNet name="1"/>
<RepeatCount name="3"/>
<RepeatTimeoutMS name="50"/>
<WatchDogTime name="0"/>
<PingNodeTime name="0"/>
<AutoStartUpTime name="1"/>
<DumpStateTime name="10"/>
<SleepTickMS name="500"/>
<UniSetDebug levels="" name="ulog"/>
<ConfDir name="./"/>
<DataDir name="./"/>
<BinDir name="./"/>
<LogDir name="./"/>
<DocDir name="./"/>
<LockDir name="./"/>
<Services></Services>
</UniSet>
<dlog name="dlog"/>
<settings>
<SharedMemory name="SharedMemory" shmID="SharedMemory"/>
<UWebSocketGate name="UWebSocketGate1"/>
</settings>
<ObjectsMap idfromfile="1">
<!--
Краткие пояснения к полям секции 'sensors'
==========================================
node - узел на котором физически находится данный датчик
iotype - тип датчика
priority - приоритет сообщения об изменении данного датчика
textname - текстовое имя датчика
-->
<nodes port="2809">
<item id="3000" infserver="InfoServer" ip="127.0.0.1" name="LocalhostNode" textname="Локальный узел"/>
</nodes>
<!-- ************************ Датчики ********************** -->
<sensors name="Sensors">
<item id="1" iotype="DI" name="DI1_S" textname="DI sensor 1"/>
<item id="2" iotype="AI" name="AI1_S" textname="AI sensor 1" default="2" undefined_value="65635"/>
<item id="3" iotype="AI" name="AI2_S" textname="AI sensor 2" default="3"/>
</sensors>
<thresholds/>
<controllers name="Controllers">
<item id="5000" name="SharedMemory"/>
</controllers>
<!-- ******************* Идентификаторы сервисов ***************** -->
<services name="Services">
</services>
<!-- ******************* Идентификаторы объектов ***************** -->
<objects name="UniObjects">
<item id="6000" name="TestProc"/>
<item id="6004" name="UWebSocketGate1"/>
</objects>
</ObjectsMap>
<messages idfromfile="1" name="messages"/>
</UNISETPLC>
AT_SETUP([UWebSocketGate tests])
AT_CHECK([$abs_top_builddir/testsuite/at-test-launch.sh $abs_top_builddir/extensions/UWebSocketGate/tests tests_with_sm.sh],[0],[ignore],[ignore])
AT_CLEANUP
......@@ -14,3 +14,4 @@ m4_include(../extensions/LogicProcessor/tests/lproc-tests.at)
m4_include(../extensions/IOControl/tests/iocontrol-tests.at)
m4_include(../extensions/LogDB/tests/logdb-tests.at)
m4_include(../extensions/HttpResolver/tests/uresolver-tests.at)
m4_include(../extensions/UWebSocketGate/tests/uwebsocketgate-tests.at)
......@@ -297,6 +297,14 @@
./extensions/UniNetwork/uninet.cc
./extensions/UWebSocketGate/main.cc
./extensions/UWebSocketGate/Makefile.am
./extensions/UWebSocketGate.old/main.cc
./extensions/UWebSocketGate.old/Makefile.am
./extensions/UWebSocketGate.old/UWebSocketGate.cc
./extensions/UWebSocketGate.old/UWebSocketGate.h
./extensions/UWebSocketGate.old/UWebSocketGateSugar.h
./extensions/UWebSocketGate/tests/Makefile.am
./extensions/UWebSocketGate/tests/tests_with_sm.cc
./extensions/UWebSocketGate/tests/test_uwebsocketgate.cc
./extensions/UWebSocketGate/UWebSocketGate.cc
./extensions/UWebSocketGate/UWebSocketGate.h
./extensions/UWebSocketGate/UWebSocketGateSugar.h
......@@ -390,7 +398,6 @@
./include/UTCPStream.h
./include/VMonitor.h
./include/WDTInterface.h
./lib/dummy.cc
./lib/Makefile.am
./Makefile.am
./src/Communications/ComPort485F.cc
......@@ -555,6 +562,8 @@
./tests/umutex.cc
./tests/UniXmlTest/Makefile.am
./tests/UniXmlTest/XmlTest.cc
./tests/wasm-test/main.cc
./tests/wasm-test/Makefile.am
./uniset-config.h
./Utilities/Admin/admin.cc
./Utilities/Admin/c.cc
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment