4
0
mirror of https://github.com/QuasarApp/Patronum.git synced 2025-05-02 10:09:35 +00:00

Merge pull request from QuasarApp/simpleRefactoring

Simple refactoring
This commit is contained in:
Andrei Yankovich 2021-04-28 18:46:23 +03:00 committed by GitHub
commit 8462ee2978
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 249 additions and 100 deletions

@ -9,17 +9,24 @@
QString Patronum::IController::errorToString(Patronum::ControllerError error) const { QString Patronum::IController::errorToString(Patronum::ControllerError error) const {
switch (error) { switch (error) {
case Patronum::ControllerError::ServiceUnavailable: return "Service is unavailable. Try send start comand or restart the service manually."; case Patronum::ControllerError::ServiceUnavailable:
return QObject::tr("Service is unavailable. Try send start comand or restart the service manually.");
case Patronum::ControllerError::InvalidPackage: return "Invalid package received"; case Patronum::ControllerError::InvalidPackage:
return QObject::tr("Invalid package received");
case Patronum::ControllerError::WrongCommand: return "Library unsupported command received"; case Patronum::ControllerError::WrongCommand:
return QObject::tr("Library unsupported command received");
case Patronum::ControllerError::SystemError: return "Internal error of the work of the Patronum library." case Patronum::ControllerError::SystemError:
" Contact the developers and provide them with an error report." return QObject::tr("Internal error of the work of the Patronum library."
" https://github.com/QuasarApp/Patronum/issues"; " Contact the developers and provide them with an error report."
" https://github.com/QuasarApp/Patronum/issues");
case Patronum::ControllerError::TimeOutError:
return QObject::tr("Timeout error. service unavailable or not started.");
default: default:
return "Unknown error"; return QObject::tr("Unknown error");
} }
} }

@ -28,12 +28,16 @@ enum class ControllerError {
InvalidPackage, InvalidPackage,
/// Library unsupported command received. /// Library unsupported command received.
WrongCommand, WrongCommand,
/// Timeout error. service unavailable or not started.
TimeOutError,
/// Internal error of the work of the Patronum library. Contact the developers and provide them with an error report. https://github.com/QuasarApp/Patronum/issues /// Internal error of the work of the Patronum library. Contact the developers and provide them with an error report. https://github.com/QuasarApp/Patronum/issues
SystemError SystemError
}; };
/** /**
* @brief The IController class * @brief The IController class This is base interface for the handling network events.
*
*/ */
class PATRONUM_LIBRARYSHARED_EXPORT IController class PATRONUM_LIBRARYSHARED_EXPORT IController
{ {
@ -43,14 +47,36 @@ public:
/** /**
* @brief errorToString This method convert the ControllerError to QString. * @brief errorToString This method convert the ControllerError to QString.
* @param error - Error id. * @param error This is error id.
* @return return text of error. * @return return text of error.
*/ */
QString errorToString(ControllerError error) const; QString errorToString(ControllerError error) const;
/**
* @brief handleFeatures This method should be handle all Command::Features resuests.
* This method will invoked when controller receive commands list for execute (features) from controller or terminal.
* @param features This is list of the requests (@a features)
*/
virtual void handleFeatures(const QList<Feature>& features) = 0; virtual void handleFeatures(const QList<Feature>& features) = 0;
virtual void handleResponce(const QVariantMap& feature) = 0;
virtual void handleError(ControllerError) = 0; /**
* @brief handleResponce This method should be handle all responces of the service.
* This method will invoked when controller receive responce from service.
* @param responce This is responce message.
*/
virtual void handleResponce(const QVariantMap& responce) = 0;
/**
* @brief handleError This method shold be handle all error messages.
* This method will invoked when a controlee receive a error responce from a service.
* @param errorCode This is code of a error.
*/
virtual void handleError(ControllerError errorCode) = 0;
/**
* @brief finished This method ivoked when controler received Command::CloseConnection from the server.
*/
virtual void finished() = 0;
}; };
} }

@ -26,14 +26,14 @@ public:
/** /**
* @brief handleReceiveData This method get all received commnads and process its. * @brief handleReceiveData This method get all received commnads and process its.
* For each command will invoke the handleReceive method. * For each command will invoke the IService::handleReceive method.
* @param data * @param data This is array of the incomming requests (commands)
*/ */
virtual void handleReceiveData(const QSet<Feature>& data) = 0; virtual void handleReceiveData(const QSet<Feature>& data) = 0;
/** /**
* @brief handleReceive This method invoked when service receive a request from terminal. * @brief handleReceive This method invoked when service receive a request from terminal.
* Override this method for work service. * Override this method for work your service.
* @param data This is input data. * @param data This is input data.
* @return This method should be return true if the @a data command is supported and processed successful. * @return This method should be return true if the @a data command is supported and processed successful.
* IF you return false then a negative message will be sent to a terminal app. * IF you return false then a negative message will be sent to a terminal app.
@ -41,7 +41,8 @@ public:
virtual bool handleReceive(const Feature &data) = 0; virtual bool handleReceive(const Feature &data) = 0;
/** /**
* @brief supportedFeatures Override this method for add your features for the service. * @brief supportedFeatures This method should be return the list of the supported fetures.
* Override this method for add your features for the service.
* @return should be return a set of supported features. * @return should be return a set of supported features.
*/ */
virtual QSet<Feature> supportedFeatures() = 0; virtual QSet<Feature> supportedFeatures() = 0;

@ -12,6 +12,7 @@
#include <QVariantMap> #include <QVariantMap>
#include <quasarapp.h> #include <quasarapp.h>
#include <QCoreApplication> #include <QCoreApplication>
#include <QTimer>
namespace Patronum { namespace Patronum {
@ -33,15 +34,11 @@ bool Controller::send(int argc, char **argv) {
bool Controller::send() { bool Controller::send() {
if (QuasarAppUtils::Params::isEndable("start")) { if (QuasarAppUtils::Params::isEndable("install") || QuasarAppUtils::Params::isEndable("i")) {
return !d_ptr->start();
}
if (QuasarAppUtils::Params::isEndable("install")) {
return d_ptr->install(); return d_ptr->install();
} }
if (QuasarAppUtils::Params::isEndable("uninstall")) { if (QuasarAppUtils::Params::isEndable("uninstall") || QuasarAppUtils::Params::isEndable("u")) {
return d_ptr->uninstall(); return d_ptr->uninstall();
} }
@ -86,16 +83,43 @@ bool Controller::send() {
sendData.insert(Feature{val.key(), val.value()}); sendData.insert(Feature{val.key(), val.value()});
} }
return d_ptr->sendCmd(sendData);
if (!d_ptr->sendCmd(sendData)) {
return false;
}
QTimer::singleShot(1000, nullptr, [this]() {
QuasarAppUtils::Params::log(errorToString(ControllerError::TimeOutError), QuasarAppUtils::Error);
QCoreApplication::exit(static_cast<int>(ControllerError::TimeOutError));
});
return true;
} }
int Controller::startDetached() const { int Controller::startDetached() const {
return d_ptr->start(); return d_ptr->start();
} }
bool Controller::waitForResponce(int msec) { QuasarAppUtils::Help::Section Controller::help() const {
QuasarAppUtils::Help::Section help {
{QObject::tr("Options that available after start"), {
{"stop", QObject::tr("Stop a service")},
{"pause", QObject::tr("Pause a service")},
{"resume", QObject::tr("Resume a service")},
{"uninstall / u", QObject::tr("Uninstall a service")}
return d_ptr->waitForResponce(msec); }
},
{QObject::tr("Options that available after instalation"),
{
{"uninstall / u", QObject::tr("Uninstall a service")},
{"start / s", QObject::tr("Start a service as a daemon")},
}
}
};
return help;
} }
void Controller::handleError(ControllerError error) { void Controller::handleError(ControllerError error) {
@ -125,7 +149,6 @@ void Controller::handleFeatures(const QList<Feature> &features) {
} }
QuasarAppUtils::Help::print(options); QuasarAppUtils::Help::print(options);
QCoreApplication::exit(0);
} }
void Controller::handleResponce(const QVariantMap &responce) { void Controller::handleResponce(const QVariantMap &responce) {
@ -136,6 +159,9 @@ void Controller::handleResponce(const QVariantMap &responce) {
} }
QuasarAppUtils::Help::print(options); QuasarAppUtils::Help::print(options);
}
void Controller::finished() {
QCoreApplication::exit(0); QCoreApplication::exit(0);
} }
@ -146,17 +172,7 @@ QList<Feature> Controller::features() {
void Controller::printDefaultHelp() const { void Controller::printDefaultHelp() const {
auto quasarappHelp = QuasarAppUtils::Params::getParamsHelp(); auto quasarappHelp = QuasarAppUtils::Params::getParamsHelp();
QuasarAppUtils::Help::print(quasarappHelp.unite(help()));
QuasarAppUtils::Help::Charters help{{"General options of this controller",{
{"start", QObject::tr("Start a service")},
{"stop", QObject::tr("Stop a service")},
{"pause", QObject::tr("Pause a service")},
{"resume", QObject::tr("Resume a service")},
{"install", QObject::tr("Install a service")},
{"uninstall", QObject::tr("Uninstall a service")}
}}};
QuasarAppUtils::Help::print(quasarappHelp.unite(help));
} }
} }

@ -10,6 +10,7 @@
#include "Patronum_global.h" #include "Patronum_global.h"
#include <IPController.h> #include <IPController.h>
#include "PFeature.h" #include "PFeature.h"
#include <quasarapp.h>
namespace Patronum { namespace Patronum {
@ -29,21 +30,23 @@ public:
/** /**
* @brief Controller - Base constructor. * @brief Controller - Base constructor.
* @param name - Name of you service. * @param name - Name of you service.
* @param servicePath - Path to service executable. @note If servicePath argument well be empty then 'start' commnad not working * @param servicePath - Path to service executable.
* @note If servicePath argument will set to empty then 'start' and install commands will not working
*/ */
Controller(const QString& name, const QString& servicePath = ""); Controller(const QString& name, const QString& servicePath = "");
~Controller() override; ~Controller() override;
/** /**
* @brief send - This method send request to service. * @brief send This method send request to service.
* @param argc - Count of arguments. * @param argc This is count of arguments.
* @param argv - Arguments list. * @param argv This is arguments list.
* @return true if all sendet successful. * @return true if all sendet successful.
*/ */
bool send(int argc, char **argv); bool send(int argc, char **argv);
/** /**
* @brief send - This method send request to service. @warning Invoke this method if you invoked QuasarAppUtils::Params::parse() before invoke this method else use send(int argc, char **argv). * @brief send - This method send request to service.
* @warning Invoke this method if you invoked QuasarAppUtils::Params::parse() before invoke this method else use send(int argc, char **argv).
* @return true if all sendet successful. * @return true if all sendet successful.
*/ */
bool send(); bool send();
@ -55,11 +58,10 @@ public:
int startDetached() const; int startDetached() const;
/** /**
* @brief waitForResponce - Wait for get a responce from servece. * @brief help This method return help of the Controller.
* @param msec Timeout in msec. * @return Available otions list.
* @return true if all seccussful.
*/ */
bool waitForResponce(int msec = 10000); QuasarAppUtils::Help::Section help() const;
// IControler interface // IControler interface
protected: protected:
@ -85,6 +87,13 @@ protected:
*/ */
void handleResponce(const QVariantMap &responce) override; void handleResponce(const QVariantMap &responce) override;
/**
* @brief finished This method invoked when controler receive from service the Command::CloseConnection command
* This implementation invoke he exit method of the QCoreApplication and finished application.
* If do not want to stop application after receive Command::CloseConnection then override this method.
*/
void finished() override;
/** /**
* @brief features - This method return current features of connected service. * @brief features - This method return current features of connected service.
* @note If Respond from service not received then return empty list. * @note If Respond from service not received then return empty list.
@ -97,8 +106,6 @@ private:
ControllerPrivate *d_ptr = nullptr; ControllerPrivate *d_ptr = nullptr;
void printDefaultHelp() const; void printDefaultHelp() const;
}; };
} }
#endif // CONTROLLER_H #endif // CONTROLLER_H

@ -94,23 +94,52 @@ Controller *ServiceBase::controller() {
return _controller; return _controller;
_controller = new Controller(_serviceName, _controller = new Controller(_serviceName,
QuasarAppUtils::Params::getCurrentExecutable()); QuasarAppUtils::Params::getCurrentExecutable());
return _controller; return _controller;
} }
void ServiceBase::printDefaultHelp() {
auto serviceHelp = controller()->help();
serviceHelp.unite(QuasarAppUtils::Params::getParamsHelp());
serviceHelp.unite({{QObject::tr("Options that available befor install"),{
{"start / s", QObject::tr("Start a service in console")},
{"daemon / d", QObject::tr("Start a service as a daemon")},
{"install / i", QObject::tr("Install a service")},
}}});
const auto features = supportedFeatures();
QuasarAppUtils::Help::Options optionsList;
for (const auto& cmd : features) {
optionsList.insert(cmd.cmd(), cmd.description());
}
serviceHelp.unite({{"Available commands of the service:", optionsList}});
QuasarAppUtils::Help::print(serviceHelp);
}
int ServiceBase::exec() { int ServiceBase::exec() {
if (!_core) { if (!_core) {
createApplication(); createApplication();
} }
bool fExec = QuasarAppUtils::Params::isEndable("exec") || QuasarAppUtils::Params::isDebugBuild(); if (!QuasarAppUtils::Params::size()) {
printDefaultHelp();
if (!(QuasarAppUtils::Params::size() || fExec)) { return 0;
return controller()->startDetached();
} }
if (fExec) { bool fStart = QuasarAppUtils::Params::isEndable("start") || QuasarAppUtils::Params::isEndable("s");
bool fDaemon = QuasarAppUtils::Params::isEndable("daemon") || QuasarAppUtils::Params::isEndable("d");
if (fStart || fDaemon) {
if (fDaemon) {
return controller()->startDetached();
}
QTimer::singleShot(0, nullptr, [this](){ QTimer::singleShot(0, nullptr, [this](){
onStart(); onStart();
d_ptr->listen(); d_ptr->listen();

@ -35,7 +35,7 @@ public:
// IService interface // IService interface
/** /**
* @brief exec * @brief exec This is main method of the service. Use this like a QCoreApplication::exec.
* @return Result of work application. * @return Result of work application.
*/ */
virtual int exec(); virtual int exec();
@ -108,6 +108,7 @@ protected:
QCoreApplication *_core = nullptr; QCoreApplication *_core = nullptr;
private: private:
void printDefaultHelp();
ServicePrivate *d_ptr = nullptr; ServicePrivate *d_ptr = nullptr;
Controller *_controller = nullptr; Controller *_controller = nullptr;

@ -5,7 +5,7 @@ Description=Automatet generated service of %0
Type=forking Type=forking
User=root User=root
Group=root Group=root
ExecStart=%0 ExecStart=%0 start
ExecStop=%0 stop ExecStop=%0 stop
[Install] [Install]

@ -6,33 +6,42 @@
*/ */
#include "baseinstaller.h" #include "baseinstaller.h"
#include <QFile>
#include <QSettings> #include <QSettings>
#include <quasarapp.h> #include <quasarapp.h>
namespace Patronum { namespace Patronum {
BaseInstaller::BaseInstaller(const QString &name): BaseInstaller::BaseInstaller(const QString &name):
Installer(name) Installer(name) {
{
} }
bool BaseInstaller::install(const QString &executable) { bool BaseInstaller::install(const QString &executable) {
if (!QFile::exists(executable)) {
QuasarAppUtils::Params::log(QObject::tr("The service executable file is not exists %0\n").arg(executable),
QuasarAppUtils::Error);
return false;
}
_executable = executable; _executable = executable;
if (isInstalled()) { if (isInstalled()) {
QuasarAppUtils::Params::log(QString("the service %0 alredy installed \n"). QuasarAppUtils::Params::log(QObject::tr("the service %0 alredy installed \n").
arg(serviceName()), arg(serviceName()),
QuasarAppUtils::Info); QuasarAppUtils::Info);
return true; return true;
} }
return false; savePath();
return true;
} }
bool BaseInstaller::uninstall() { bool BaseInstaller::uninstall() {
if (!isInstalled()) { if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("the service %0 alredy uninstalled \n"). QuasarAppUtils::Params::log(QObject::tr("the service %0 alredy uninstalled \n").
arg(serviceName()), arg(serviceName()),
QuasarAppUtils::Info); QuasarAppUtils::Info);
return true; return true;
@ -43,7 +52,7 @@ bool BaseInstaller::uninstall() {
bool BaseInstaller::enable() { bool BaseInstaller::enable() {
if (!isInstalled()) { if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("Cannot enabled the service %0 not installed, run install command befor enable. \n"). QuasarAppUtils::Params::log(QObject::tr("Cannot enabled the service %0 not installed, run install command befor enable. \n").
arg(serviceName()), arg(serviceName()),
QuasarAppUtils::Info); QuasarAppUtils::Info);
return false; return false;
@ -54,7 +63,7 @@ bool BaseInstaller::enable() {
bool BaseInstaller::disable() { bool BaseInstaller::disable() {
if (!isInstalled()) { if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("Cannot disabled the service %0 not installed, run install command befor enable. \n"). QuasarAppUtils::Params::log(QObject::tr("Cannot disabled the service %0 not installed, run install command befor enable. \n").
arg(serviceName()), arg(serviceName()),
QuasarAppUtils::Info); QuasarAppUtils::Info);
return false; return false;

@ -10,6 +10,7 @@
#include "localsocket.h" #include "localsocket.h"
#include <QCoreApplication> #include <QCoreApplication>
#include <QDateTime> #include <QDateTime>
#include <QFile>
#include <QProcess> #include <QProcess>
#include <quasarapp.h> #include <quasarapp.h>
#include "package.h" #include "package.h"
@ -63,7 +64,6 @@ bool ControllerPrivate::sendCmd(const QSet<Feature> &result) {
} }
if (_socket->send(_parser->createPackage(Command::Feature, result))) { if (_socket->send(_parser->createPackage(Command::Feature, result))) {
_responce = false;
return true; return true;
} }
@ -73,12 +73,9 @@ bool ControllerPrivate::sendCmd(const QSet<Feature> &result) {
int ControllerPrivate::start() const { int ControllerPrivate::start() const {
QProcess proc; QProcess proc;
proc.setProgram(_serviceExe); proc.setProgram(getExecutable());
if (_installer && _installer->isInstalled() && _installer->getExecutable().size()) {
proc.setProgram(_installer->getExecutable());
}
proc.setArguments({"exec"}); proc.setArguments({"d"});
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
proc.setProcessChannelMode(QProcess::SeparateChannels); proc.setProcessChannelMode(QProcess::SeparateChannels);
@ -104,7 +101,7 @@ bool ControllerPrivate::install() const {
return false; return false;
} }
if (!_installer->install(_serviceExe)) { if (!_installer->install(getExecutable())) {
return false; return false;
} }
@ -126,7 +123,7 @@ bool ControllerPrivate::uninstall() const {
_controller->handleResponce({{"Result", "Uninstall service successful"}}); _controller->handleResponce({{"Result", "Uninstall service successful"}});
return _installer->uninstall(); return true;
} }
bool ControllerPrivate::pause() { bool ControllerPrivate::pause() {
@ -137,24 +134,6 @@ bool ControllerPrivate::resume() {
return sendCmd({Feature("resume")}); return sendCmd({Feature("resume")});
} }
bool Patronum::ControllerPrivate::waitForResponce(int msec) {
if (!dynamic_cast<QCoreApplication*>(QCoreApplication::instance())) {
QuasarAppUtils::Params::log("Before run the waitForResponce method you need run a exec method of your QApplication class.",
QuasarAppUtils::Warning);
return false;
}
qint64 waitFor = QDateTime::currentMSecsSinceEpoch() + msec;
while (!_responce && QDateTime::currentMSecsSinceEpoch() < waitFor) {
QCoreApplication::processEvents();
}
QCoreApplication::processEvents();
return _responce;
}
QList<Feature> ControllerPrivate::features() const { QList<Feature> ControllerPrivate::features() const {
return _features; return _features;
} }
@ -221,7 +200,7 @@ void ControllerPrivate::handleReceve(QByteArray data) {
} }
case Command::CloseConnection: { case Command::CloseConnection: {
_responce = true; _controller->finished();
break; break;
} }
@ -249,4 +228,16 @@ void ControllerPrivate::handleReceve(QByteArray data) {
} }
} }
QString ControllerPrivate::getExecutable() const {
if (QFile::exists(_serviceExe)) {
return _serviceExe;
}
if (!_installer) {
return "";
}
return _installer->getExecutable();
}
} }

@ -33,8 +33,6 @@ public:
bool pause(); bool pause();
bool resume(); bool resume();
bool waitForResponce(int msec);
QList<Feature> features() const; QList<Feature> features() const;
bool isConnected() const; bool isConnected() const;
@ -44,18 +42,21 @@ public:
signals: signals:
void sigListFeatures(QList<Feature>); void sigListFeatures(QList<Feature>);
private slots:
void handleReceve(QByteArray data);
private: private:
QString getExecutable() const;
LocalSocket *_socket = nullptr; LocalSocket *_socket = nullptr;
IController *_controller = nullptr; IController *_controller = nullptr;
bool _responce = false;
QList<Feature> _features; QList<Feature> _features;
QString _serviceExe = ""; QString _serviceExe = "";
Installer *_installer = nullptr; Installer *_installer = nullptr;
Parser * _parser; Parser * _parser;
private slots:
void handleReceve(QByteArray data);
}; };
} }

@ -12,7 +12,7 @@
#include <QProcess> #include <QProcess>
namespace Patronum { namespace Patronum {
const QString systemDPath = "/etc/systemd/system/"; #define SYSTEMD_PATH "/etc/systemd/system/"
InstallerSystemD::InstallerSystemD(const QString& name): InstallerSystemD::InstallerSystemD(const QString& name):
BaseInstaller(name) { BaseInstaller(name) {
@ -106,7 +106,7 @@ bool InstallerSystemD::isInstalled() const {
} }
QString InstallerSystemD::absaluteServicePath() const { QString InstallerSystemD::absaluteServicePath() const {
return systemDPath + serviceName() + ".service"; return SYSTEMD_PATH + serviceName() + ".service";
} }
} }

@ -13,6 +13,39 @@
/** /**
* @brief The Patronum namespace - It is main name space of Patronum Library. * @brief The Patronum namespace - It is main name space of Patronum Library.
* The Patronum library support the two work mode
* 1. Single executable mode.
* 2. Service-terminal mode.
*
* ## Single executable mode
* In this case you have a service with single executable file. All service operations (instalation deinstalation, send commnad and another) will sends from the one executable.
*
* Fits one you need to start service executable as a daemon.
* @code{bash}
* myservice daemon
* @endcode
*
* For send any command to service use the service command.
*
* @code{bash}
* myservice myCommand
* @endcode
*
* ## Service-terminal mode.
* In this mode you create two executable file.
* 1. Service is Patronum::Service
* 2. Terminal is Patronum::Controller
*
* Fits one you need to start service executable as a daemon.
* @code{bash}
* myservice daemon
* @endcode
*
* For send any command to service use the terminal executable.
*
* @code{bash}
* terminal myCommand
* @endcode
*/ */
namespace Patronum {} namespace Patronum {}
#endif // PATRONUM_H #endif // PATRONUM_H

@ -61,7 +61,7 @@ public:
QList<Feature> supportedFeatures() { QList<Feature> supportedFeatures() {
QList<Feature> res; QList<Feature> res;
Feature Ping = {"Ping", ""} Feature Ping = {"Ping", "This is description of the ping command"}
return res << Ping; return res << Ping;
} }
}; };
@ -87,6 +87,8 @@ public:
}; };
int main(int argc, char **argv) { int main(int argc, char **argv) {
QCoreApplication::setApplicationName("MyServiceName"); // <--
QCoreApplication::setOrganizationName("MyCompany"); // <--
QCoreApplcication app QCoreApplcication app
MyControllerApp controller; MyControllerApp controller;
controller.send(argc, argv); controller.send(argc, argv);

@ -9,6 +9,14 @@ QVariantMap DefaultController::getResponce() {
return _receiveData; return _receiveData;
} }
bool DefaultController::isFinished() const {
return _finished;
}
void DefaultController::handleResponce(const QVariantMap &feature) { void DefaultController::handleResponce(const QVariantMap &feature) {
_receiveData = feature; _receiveData = feature;
} }
void DefaultController::finished() {
_finished = true;
}

@ -7,13 +7,15 @@ class DefaultController : public Patronum::Controller
public: public:
DefaultController(); DefaultController();
QVariantMap getResponce(); QVariantMap getResponce();
bool isFinished() const;
protected: protected:
void handleResponce(const QVariantMap &feature); void handleResponce(const QVariantMap &feature);
void finished();
private: private:
QVariantMap _receiveData; QVariantMap _receiveData;
bool _finished = false;
}; };

@ -18,3 +18,12 @@ bool TestUtils::wait(const bool &forWait, int msec) {
return forWait; return forWait;
} }
bool TestUtils::wait(std::function<bool ()> forWait, int msec) {
auto curmsec = QDateTime::currentMSecsSinceEpoch() + msec;
while (curmsec > QDateTime::currentMSecsSinceEpoch() && !forWait()) {
QCoreApplication::processEvents();
}
QCoreApplication::processEvents();
return forWait();
}

@ -8,6 +8,7 @@ class TestUtils
public: public:
TestUtils(); TestUtils();
static bool wait(const bool &forWait, int msec); static bool wait(const bool &forWait, int msec);
static bool wait(std::function<bool ()> forWait, int msec);
}; };

@ -39,6 +39,8 @@ testPatronum::testPatronum() {
} }
void testPatronum::testPing() { void testPatronum::testPing() {
TestUtils utils;
const char* arg[] = { const char* arg[] = {
"/", "/",
"ping" "ping"
@ -46,11 +48,13 @@ void testPatronum::testPing() {
DefaultController cli; DefaultController cli;
QuasarAppUtils::Params::clearParsedData(); QuasarAppUtils::Params::clearParsedData();
QVERIFY(cli.send(2 , const_cast<char**>(arg))); QVERIFY(cli.send(2 , const_cast<char**>(arg)));
QVERIFY(cli.waitForResponce(1000)); QVERIFY(utils.wait([&cli](){return cli.isFinished();}, 1000));
QVERIFY(cli.getResponce().value("Result") == "pong"); QVERIFY(cli.getResponce().value("Result") == "pong");
} }
void testPatronum::testRandomCommad() { void testPatronum::testRandomCommad() {
TestUtils utils;
const char* arg[] = { const char* arg[] = {
"/", "/",
"fd" "fd"
@ -59,7 +63,7 @@ void testPatronum::testRandomCommad() {
QuasarAppUtils::Params::clearParsedData(); QuasarAppUtils::Params::clearParsedData();
QVERIFY(cli.send(2 , const_cast<char**>(arg))); QVERIFY(cli.send(2 , const_cast<char**>(arg)));
QVERIFY(cli.waitForResponce(1000)); QVERIFY(utils.wait([&cli](){return cli.isFinished();}, 1000));
QVERIFY(cli.getResponce().contains("Error")); QVERIFY(cli.getResponce().contains("Error"));
} }
@ -74,6 +78,8 @@ void testPatronum::connectTest() {
QCoreApplication::exit(0); QCoreApplication::exit(0);
}); });
QuasarAppUtils::Params::parseParams({"s"});
QVERIFY(serv.exec() == 0); QVERIFY(serv.exec() == 0);
} }