Changeset a2330fc


Ignore:
Timestamp:
Sep 20, 2015, 2:30:36 PM (11 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
master
Children:
1ebaa4f
Parents:
915dc18
Message:

Build in php webserver is now launched with QProcess::start instead of QProcess::execute in a different thread

Location:
src
Files:
2 deleted
7 edited

Legend:

Unmodified
Added
Removed
  • src/lib/siwebserviceclient.cpp

    r915dc18 ra2330fc  
    6666
    6767        QNetworkRequest request;
    68         request.setUrl(QString("%1%2").arg(_baseUrl.toString()).arg("index.php/stations/register"));
     68        request.setUrl(QString("%1%2").arg(appendSlashToUrl(_baseUrl.toString())).arg("index.php/stations/register"));
    6969        request.setRawHeader("User-Agent", QString("SiWeather Library %1").arg(Library::version()).toUtf8());
    7070        request.setHeader(QNetworkRequest::ContentTypeHeader,
    … …  
    126126        return reply;
    127127}
     128
     129QString SiWebserviceClient::appendSlashToUrl(QString url)
     130{
     131        if(url.right(1) != "/")
     132                url += "/";
     133        return url;
     134}
  • src/lib/siwebserviceclient.h

    r915dc18 ra2330fc  
    6565
    6666                        private:
     67                                static QString appendSlashToUrl(QString url);
     68
    6769                                QNetworkReply* getNetworkReply(QObject *sender, ReplyType type) const;
    6870                                QUrl _baseUrl;
  • src/testing/CMakeLists.txt

    r915dc18 ra2330fc  
    2525SET(files_CPP
    2626        webserverprocess.cpp
    27         private/webserverrunner.cpp
    2827)
    2928
    … …  
    3130        ${CMAKE_CURRENT_BINARY_DIR}
    3231        ${CMAKE_CURRENT_SOURCE_DIR}
    33         ${CMAKE_CURRENT_BINARY_DIR}/private
    34         ${CMAKE_CURRENT_SOURCE_DIR}/private
    3532)
    3633ADD_DEFINITIONS(-DSI_BUILD_TESTING)
    … …  
    5754)
    5855
    59 qt5_use_modules(libsiweather_testing Core Network)
     56qt5_use_modules(libsiweather_testing Core Network Test)
    6057
    6158SET_TARGET_PROPERTIES(libsiweather_testing PROPERTIES
  • src/testing/webserverprocess.cpp

    r915dc18 ra2330fc  
    2323#include "sitestingconfig.h"
    2424
    25 #include "webserverrunner.h"
    26 
    27 #include <QTimer>
     25#include <QTcpSocket>
     26#include <QRegExp>
     27#include <QNetworkAccessManager>
     28#include <QNetworkRequest>
     29#include <QNetworkReply>
    2830#include <QTime>
    2931#include <QCoreApplication>
    30 #include <QTcpSocket>
    31 #include <QRegExp>
     32#include <QTest>
     33#include <QDir>
    3234
    3335WebserverProcess::WebserverProcess(QObject* parent)
    34  : QThread(parent)
    35 {
    36         _runner = NULL;
    37         _finishedStartup = false;
    38         connect(this, SIGNAL(started()), this, SLOT(setStarted()));
     36 : QObject(parent)
     37{
     38        _process = new QProcess(this);
     39        connect(_process, SIGNAL(error(QProcess::ProcessError)),
     40                                        this, SLOT(processError(QProcess::ProcessError)));
     41        connect(_process, SIGNAL(finished(int,QProcess::ExitStatus)),
     42                                        this, SLOT(processFinished(int,QProcess::ExitStatus)));
     43        connect(_process, SIGNAL(readyRead()),
     44                                        this, SLOT(processReadyRead()));
    3945}
    4046
    4147WebserverProcess::~WebserverProcess()
    4248{
    43         if(_runner)
    44                 delete _runner;
     49        if(_process && _process->state() == QProcess::Running){
     50                _process->kill();
     51                _process->waitForFinished(5000);
     52        }
     53        cleanupDataDirectory();
    4554}
    4655
    … …  
    5867bool WebserverProcess::isRunning() const
    5968{
     69        if(!_process)
     70                return false;
     71
    6072        QRegExp regex("http:\\/\\/([^:]+)+:([0-9]+)");
    6173        if(regex.indexIn(webserviceBaseUrl()) < 0){
    62                         qDebug() << QString("Regex %1 to find host and port not matching in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
    63                         return false;
     74                qDebug() << QString("Regex %1 to find host and port not matching in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
     75                return false;
    6476        }
    6577        QStringList capturedTexts = regex.capturedTexts();
    … …  
    7082        QTcpSocket *socket = new QTcpSocket();
    7183        socket->connectToHost(capturedTexts[1], capturedTexts[2].toInt(), QIODevice::ReadOnly);
    72         if (!socket->waitForConnected(2000)){
     84        if (!socket->waitForConnected()){
    7385                qDebug() << QString("Webservice at %1:%2 not reachable").arg(capturedTexts[1]).arg(capturedTexts[2]);
    7486                delete socket;
    … …  
    8092}
    8193
    82 void WebserverProcess::stopThread()
    83 {
    84         // stopping thread
    85         // cancel query first
    86         // stop eventloop
    87         quit();
    88         // wait 2000 seconds to stop the eventloop
    89         wait(2000);
    90 }
    91 
    92 void WebserverProcess::run()
    93 {
    94         _runner = new WebserverRunner();
    95         QTimer::singleShot(1, _runner, SLOT(start()));
    96         exec();
    97 }
    98 
    99 bool WebserverProcess::isStarted()
    100 {
    101         return _finishedStartup;
    102 }
    103 
    104 bool WebserverProcess::waitForStart()
    105 {
    106         if(isStarted())
     94bool WebserverProcess::start()
     95{
     96        if(!_process)
     97                return false;
     98
     99        QStringList arguments;
     100        arguments << QString("-S %1:%2").arg(QString(WEBSERVICE_SERVER_HOST)).arg(QString(WEBSERVICE_SERVER_PORT));
     101        arguments << QString("-t %1").arg(QString(WEBSERVICE_SERVER_DOCROOT));
     102       
     103        connect(_process, SIGNAL(error(QProcess::ProcessError)),
     104                                        this, SLOT(processError(QProcess::ProcessError)));
     105        connect(_process, SIGNAL(finished(int,QProcess::ExitStatus)),
     106                                        this, SLOT(processFinished(int,QProcess::ExitStatus)));
     107        connect(_process, SIGNAL(readyRead()),
     108                                        this, SLOT(processReadyRead()));
     109       
     110        _process->setReadChannelMode(QProcess::ForwardedChannels);
     111        _process->start(QString("/usr/bin/php ")+ arguments.join(" "));
     112        // give the php webserver a few seconds to start
     113        QTest::qWait(5000);
     114        if(!isRunning())
     115                return false;
     116        return true;
     117}
     118
     119bool WebserverProcess::stop()
     120{
     121        if(!_process)
    107122                return true;
    108 
    109         // wait for thread to be started
    110         QTime dieTime = QTime::currentTime().addSecs(2);
    111         // Userevents should be excluded see http://lists.trolltech.com/qt-interest/2007-01/thread00133-0.html
    112         while( QTime::currentTime() < dieTime ){
     123        _process->terminate();
     124        return _process->waitForFinished(5000);
     125}
     126
     127
     128bool WebserverProcess::setup()
     129{
     130        if(!_process)
     131                return false;
     132
     133        QRegExp regex("http:\\/\\/([^:]+)+:([0-9]+)");
     134        if(regex.indexIn(webserviceBaseUrl()) < 0){
     135                qDebug() << QString("Regex %1 to find host and port not matching in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
     136                return false;
     137        }
     138        QStringList capturedTexts = regex.capturedTexts();
     139        if(capturedTexts.size() != 3){
     140                qDebug() << QString("Regex %1 does not matches enough items in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
     141                return false;
     142        }
     143        QNetworkAccessManager *manager = new QNetworkAccessManager(this);
     144        QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(QString("%1%2").arg(webserviceBaseUrl()).arg("index.php/setup"))));
     145        QTime dieTime = QTime::currentTime().addSecs(30);
     146        while(QTime::currentTime() < dieTime){
     147                if(reply->isFinished())
     148                        break;
    113149                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 100);
    114                 if(isStarted())
    115                         return true;
    116         }
    117 
    118         if(isStarted())
     150        }
     151        bool result = reply->isFinished();
     152        reply->deleteLater();
     153        manager->deleteLater();
     154        return result;
     155}
     156
     157bool WebserverProcess::cleanupDataDirectory()
     158{
     159        QDir dir(QString(WEBSERVICE_SERVER_DOCROOT));
     160        if(!dir.exists())
    119161                return true;
    120         return false;
    121 }
    122 
    123 void WebserverProcess::setStarted()
    124 {
    125         // Give the php webserver 5 seconds to start
    126         QTime dieTime = QTime::currentTime().addSecs(5);
    127         // Userevents should be excluded see http://lists.trolltech.com/qt-interest/2007-01/thread00133-0.html
    128         while( QTime::currentTime() < dieTime ){
    129                 QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 100);
    130         }
    131         _finishedStartup = true;
     162        if(!dir.removeRecursively())
     163                return false;
     164        return true;
     165}
     166
     167void WebserverProcess::processError(QProcess::ProcessError error)
     168{
     169        QString errorString;
     170        switch(error){
     171                case QProcess::FailedToStart:
     172                        errorString = "FailedToStart";
     173                        break;
     174                case QProcess::Crashed:
     175                        errorString = "Crashed";
     176                        break;
     177                case QProcess::Timedout:
     178                        errorString = "Timedout";
     179                        break;
     180                case QProcess::WriteError:
     181                        errorString = "WriteError";
     182                        break;
     183                case QProcess::ReadError:
     184                        errorString = "ReadError";
     185                        break;
     186                default:
     187                        errorString = "Unknown";
     188        }
     189
     190        qDebug() << QString("%1: Error %2 (%3)")
     191                                                                .arg(metaObject()->className()).arg(errorString).arg(int(error));
     192}
     193
     194void WebserverProcess::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
     195{
     196        QString exitString;
     197        switch(exitStatus){
     198                case QProcess::NormalExit:
     199                        exitString = "NormalExit";
     200                        break;
     201                case QProcess::CrashExit:
     202                        exitString = "CrashExit";
     203                        break;
     204                default:
     205                        exitString = "Unknown";
     206        }
     207        qDebug() << QString("%1: Finished with exit code %2 and staus %3 (%4)")
     208                                                                .arg(metaObject()->className()).arg(exitCode).arg(exitString).arg(int(exitStatus));
     209}
     210
     211void WebserverProcess::processReadyRead()
     212{
     213        QProcess *process = qobject_cast<QProcess*>(sender());
     214        if(!process)
     215                return;
     216        qDebug() << QString("%1: Read %2")
     217                                                        .arg(metaObject()->className()).arg(QString::fromUtf8(process->readAll()));
    132218}
    133219
  • src/testing/webserverprocess.h

    r915dc18 ra2330fc  
    2121#define WEBSERVERPROCESS_H
    2222
    23 #include <QThread>
     23#include <QObject>
    2424#include <sitestingglobal.h>
    25 
    26 class WebserverRunner;
    2725
    2826#include <QPointer>
    … …  
    3230 * @brief Starts the php build in webserver to allow testing against the webservice
    3331 */
    34 class SI_TESTING_EXPORT WebserverProcess : public QThread {
    35         friend WebserverRunner;
    36        
     32class SI_TESTING_EXPORT WebserverProcess : public QObject {
    3733        Q_OBJECT
    3834        public:
    … …  
    4440               
    4541                bool isRunning() const;
    46        
    47                 void stopThread();
    48                 void run();
    49                 bool isStarted();
    50                 bool waitForStart();
     42                bool start();
     43                /**
     44                 * @brief Stops the webservice with QProcess::terminate(). The destructor ~WebserverProcess() calls QProcess::kill() to stop the webserver process.
     45                 */
     46                bool stop();
     47                /**
     48                 * @brief Calls the setup page of the webservice. Returns true, if the call was successfully. This does not means, the setup was successfully.
     49                 */
     50                bool setup();
     51                /**
     52                 * @brief Removes the webservice data directory to cleanup test case. It is called by ~WebserverProcess().
     53                 */
     54                bool cleanupDataDirectory();
    5155
    5256        private slots:
    53                 void setStarted();
     57                void processError(QProcess::ProcessError error);
     58                void processFinished(int exitCode, QProcess::ExitStatus exitStatus);
     59                void processReadyRead();
    5460
    5561        private:
    5662                static QString appendSlashToUrl(QString url);
    5763
    58 //              QPointer<QProcess> _webserverProcess;
    59 //              int _timeout;
    60                 WebserverRunner *_runner;
    61                 bool _finishedStartup;
     64                QPointer<QProcess> _process;
     65                int _timeout;
    6266};
    6367
  • src/tests/siwebserviceclienttest.cpp

    r915dc18 ra2330fc  
    3434{
    3535        _webserverProcess = new WebserverProcess(this);
    36         _webserverProcess->start();
    37         QCOMPARE(_webserverProcess->waitForStart(), true);
     36        QCOMPARE(_webserverProcess->start(), true);
     37        QCOMPARE(_webserverProcess->isRunning(), true);
     38        QCOMPARE(_webserverProcess->setup(), true);
    3839}
    3940
    40 void SiWebserviceClientTest::cleanUpTestCase()
     41void SiWebserviceClientTest::cleanupTestCase()
    4142{
    4243        QVERIFY(_webserverProcess);
    43 //      QCOMPARE(_webserverProcess->stop(), true);
    44         _webserverProcess->stopThread();
     44        QCOMPARE(_webserverProcess->stop(), true);
    4545}
    4646
    … …  
    107107        QVariantList data = spyFinishedStationsRegister.takeFirst();
    108108        QCOMPARE(data.count(), 3);
     109        if(!data[0].toBool()){
     110                QTest::qWarn(data[2].toString().toUtf8());
     111        }
    109112        QCOMPARE(data[0].toBool(), true);
    110113        QCOMPARE(data[1].toUuid().isNull(), false);
  • src/tests/siwebserviceclienttest.h

    r915dc18 ra2330fc  
    3030        private slots:
    3131                void initTestCase();
    32                 void cleanUpTestCase();
     32                void cleanupTestCase();
    3333               
    3434                void apiVersion();
Note: See TracChangeset for help on using the changeset viewer.