summaryrefslogtreecommitdiff
path: root/test/TestRunnerClient.cpp
blob: fcb9c757ca67d1cdcf25eefe0e37423610d156ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*******************************************************************************
 * Copyright (c) 2008 Gerhard Leonhartsberger.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

#include "TestRunnerClient.h"

#ifdef CPPUNIT_MAIN

#include "cppunit/XmlOutputter.h"
#include "cppunit/TextOutputter.h"
#include "cppunit/TestSuite.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestFailure.h"
#include "cppunit/SourceLine.h"
#include "cppunit/Exception.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/extensions/TestDecorator.h"
#include "cppunit/ui/text/TestRunner.h"

#include <iostream>
#include <sstream>
#include <typeinfo>
#include <vector>

#include <errno.h>
#include <unistd.h>
#include <sys/time.h>

#ifdef _WIN32 // Bugzilla 40710
#include <windows.h>
#include <winbase.h>
#include <winsock.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif

#define MAX_HOSTNAME_SIZE       255

/*
 * CppUnitServer protocol constants
 */
static const std::string TRACE_START = "%TRACES ";
static const std::string TRACE_END = "%TRACEE ";
static const std::string TEST_RUN_START = "%TESTC  ";
static const std::string TEST_START = "%TESTS  ";
static const std::string TEST_END = "%TESTE  ";
static const std::string TEST_ERROR = "%ERROR  ";
static const std::string TEST_FAILED = "%FAILED ";
static const std::string TEST_RUN_END = "%RUNTIME";
static const std::string TEST_STOPPED = "%TSTSTP ";
static const std::string TEST_TREE = "%TSTTREE";

TestRunnerClient::TestRunnerClient()
{
    fTestResult = 0;
    fClientSocket = -1;
    fPort = 0;
    fKeepAlive = 0;
    fDebugMode = 0;

    fHost = (char *) malloc(MAX_HOSTNAME_SIZE);
    strcpy(fHost, "");
}

TestRunnerClient::~TestRunnerClient() {

    if (fHost != NULL) {
        free(fHost);
    }
}

int TestRunnerClient::Run()
{
    if (fDebugMode)
    {
        std::cerr << "TestRunnerClient: Starting client." << std::endl;
    }

    if (Connect() == -1) {
        return -1;
    }

    InstallListeners();

    RunTests();

    UninstallListeners();

    if(fTestResult != NULL)
    {
        fTestResult->stop();
        fTestResult= NULL;
    }

    ShutDown();

    return 0;
}

void TestRunnerClient::Init(int n, char *args[])
{
    ParseCommandLine(n, args);
    DefineHostName();
}

void TestRunnerClient::ParseCommandLine(int n, char *args[])
{
    // parse all arguments passed by args
    for(int i = 0; i < n; i++)
    {
        std::string arg(args[i]);

        // port option
        std::string portOption("-port=");
        int pos = arg.find(portOption);
        if(pos> -1)
        {
            std::string v = arg.substr(pos + portOption.length(), arg.length());
            fPort = atoi(v.c_str());
        }

        // debug option
        std::string debugOption("-debug");
        pos = arg.find(debugOption);
        if(pos> - 1)
        {
            fDebugMode = 1;
        }
    }
}

void TestRunnerClient::DefineHostName()
{
    // set fHost to hostname or localhost
    int ret = gethostname(fHost, MAX_HOSTNAME_SIZE);
    if (ret == -1)
    {
        strcpy(fHost, "localhost");
    }
}

int TestRunnerClient::Connect()
{

#ifdef _WIN32 // Bugzilla 40710
    if (fDebugMode)
    {
        std::cerr << "TestRunnerClient: Starting Windows Sockets WSAStartup()." << std:endl;
    }

    // start up Windows Sockets
    WSADATA WSAData;
    int result = WSAStartup (MAKEWORD(1, 1), &WSAData);
    if (result != NO_ERROR)
    {
        std::cerr << "TestRunnerClient: WSAStartup() failed! Error code: " << result << std::endl;
        return -1;
    }
#endif

    if (fDebugMode)
    {
        std::cerr << "TestRunnerClient: Trying to connect to " << fHost << ":" << fPort << std::endl;
    }

    fClientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (fClientSocket == -1)
    {
        std::cerr << "TestRunnerClient: Socket creation failed! error code: " << fClientSocket << std::endl;
        return -1;
    }

    struct hostent *host = gethostbyname(fHost);
    if (host == NULL)
    {
        std::cerr << "TestRunnerClient: Cannot find host address for " << fHost << "." << std::endl;
        fClientSocket = -1;
        return -1;
    }

    struct sockaddr_in name;
    memset((void *)&name, 0, sizeof(struct sockaddr_in));
    name.sin_family = AF_INET;
    name.sin_port = htons(fPort);

    memcpy(&name.sin_addr, host->h_addr, host->h_length);

    if (fDebugMode) {
        std::cerr << "TestRunnerClient: Waiting for the JVM to listen ... (trying 3 times)" << std::endl;
    }

    int ret = -1;
    int j = 0;
    while ((j < 3) && (ret == -1))
    {
        ret = ::connect(fClientSocket, (struct sockaddr *) &name, sizeof(struct sockaddr_in));
        if (ret == -1)
        {
            if (fDebugMode) {
                std::cerr << "TestRunnerClient: Connection request, waiting 1 second. "
                << ((j-3)*-1) << " times left." << std::endl;
            }
            PrivateSleep(1000);
            j++;
        }
    }
    if (ret == -1)
    {
        std::cerr << "TestRunnerClient: No connection established. Error code: " << errno << std::endl;
        fClientSocket = -1;
        return -1;
    }

    if (fDebugMode) {
        std::cerr << "TestRunnerClient: Connection established." << std::endl;
    }
    return 0;
}

void TestRunnerClient::InstallListeners()
{
    fTestResult = new CppUnit::TestResult();
    fTestResult->addListener(this);
    fTestResult->addListener(&resultCollector);
}

void TestRunnerClient::UninstallListeners()
{
    fTestResult->removeListener(this);
}

void TestRunnerClient::RunTests()
{

    CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
    CppUnit::Test *suite = registry.makeTest();
    int count = suite->countTestCases();
    NotifyTestRunStarted(count);

    if (count == 0)
    {
        NotifyTestRunEnded(0);
    }

    long startTime = CurrentTimeMillis();
    if (fDebugMode)
    {
        std::cerr <<"TestRunnerClient: Start sending test case tree ..." << std::endl;
    }

    SendTestTree(suite);

    int elapsedTime = CurrentTimeMillis() - startTime;
    if (fDebugMode) {
        std::cerr << "TestRunnerClient: Done sending test case tree. Elapsed time is "
        << elapsedTime << "ms." << std::endl;
    }

    long testStartTime = CurrentTimeMillis();
    if (fDebugMode) {
        std::cerr << "TestRunnerClient: Test start time is " << testStartTime
        << "ms." << std::endl;
    }

    suite->run(fTestResult);

    if (fTestResult == NULL || fTestResult->shouldStop())
    {
        NotifyTestRunStopped(CurrentTimeMillis() - testStartTime);
    }
    else
    {
        NotifyTestRunEnded(CurrentTimeMillis() - testStartTime);
    }
}

void TestRunnerClient::ShutDown()
{
    if (fClientSocket != -1)
    {
        if (fDebugMode) {
            std::cerr << "TestRunnerClient: Closing connection to CppUnit sever at "
            << fHost << ":" << fPort << std::endl;
        }

#ifdef _WIN32 // Bugzilla 40710
        // TODO: std:err output for error return codes
        closesocket(fClientSocket);
        WSACleanup();
#else
        int result = close(fClientSocket);
        if (result != 0)
        {
            std::cerr << "TestRunnerClient: Close connection error: " << errno << std::endl;
        }
#endif

        fClientSocket = -1;
    }
}

void TestRunnerClient::Stop()
{
    if (fTestResult != NULL)
    {
        fTestResult->stop();
    }
}

void TestRunnerClient::SendTestTree(CppUnit::Test *test)
{
    if (typeid(*test) == typeid(CppUnit::TestDecorator))
    {
        class TmpClass : public CppUnit::TestDecorator {

        public:
            TmpClass(Test *t):CppUnit::TestDecorator(t)
            {
                // nothing to do
            }

            ~TmpClass() // Bugzilla 39894
            {
                // nothing to do
            }

            CppUnit::Test *getTest()
            {
                return m_test;
            }
        };

        TmpClass *t = (TmpClass *)test;
        SendTestTree(t->getTest());
    }
    else if (typeid(*test) == typeid(CppUnit::TestSuite))
    {
        CppUnit::TestSuite *suite = (CppUnit::TestSuite *)test;
        const std::vector<CppUnit::Test *> &x = suite->getTests();

        std::ostringstream os;
        os << suite->getName() << ",true," << x.size();
        NotifyTestTreeEntry(os.str());

        for(unsigned int i=0; i < x.size(); i++)
        {
            SendTestTree(x[i]);
        }
    }
    else
    {
        std::ostringstream os;
        os << test->getName() << ",false," << test->countTestCases();
        NotifyTestTreeEntry(os.str());
    }
}

void TestRunnerClient::SendMessage(std::string msg)
{
    if (fClientSocket == -1)
    {
        return;
    }

#ifdef _WIN32 // Bugzilla 40710
    send (fClientSocket, msg.c_str(), msg.length(), 0);
    send (fClientSocket, "\n", 1, 0);
#else
    write(fClientSocket, msg.c_str(), msg.length());
    write(fClientSocket, "\n", 1);
#endif

    if (fDebugMode)
    {
        std::cerr << "TestRunnerClient: Sent message \"" << msg << "\""
        << std::endl;
    }
}

void TestRunnerClient::NotifyTestRunStarted(int testCount)
{
    std::ostringstream os;
    os << TEST_RUN_START << testCount;
    SendMessage(os.str());
}

void TestRunnerClient::NotifyTestRunEnded(long elapsedTime)
{
    std::ostringstream os;
    os << TEST_RUN_END << elapsedTime;
    SendMessage(os.str());
}

void TestRunnerClient::NotifyTestRunStopped(long elapsedTime)
{
    std::ostringstream os;
    os << TEST_STOPPED << elapsedTime;
    SendMessage(os.str());
}

void TestRunnerClient::NotifyTestTreeEntry(std::string treeEntry)
{
    SendMessage(TEST_TREE + treeEntry);
}

void TestRunnerClient::NotifyTestStarted(std::string testName)
{
    SendMessage(TEST_START + testName);
}

void TestRunnerClient::NotifyTestEnded(std::string testName)
{
    SendMessage(TEST_END + testName);
}

void TestRunnerClient::NotifyTestFailed(std::string status, std::string testName, std::string trace)
{
    SendMessage(status + testName);
    SendMessage(TRACE_START);
    SendMessage(trace);
    SendMessage(TRACE_END);
}

// From TestListener
void TestRunnerClient::startTest(CppUnit::Test *test)
{
    NotifyTestStarted(test->getName());
}

// From TestListener
void TestRunnerClient::addFailure(const CppUnit::TestFailure &failure)
{
    if(failure.isError())
    {
        NotifyTestFailed(TEST_ERROR,failure.failedTestName(),GetTrace(failure));
    }
    else
    {
        NotifyTestFailed(TEST_FAILED,failure.failedTestName(),GetTrace(failure));
    }
}

// From TestListener
void TestRunnerClient::endTest(CppUnit::Test *test)
{
    NotifyTestEnded(test->getName());
}

std::string TestRunnerClient::GetTrace(const CppUnit::TestFailure &failure)
{
    std::ostringstream os;

    CppUnit::Exception *e=failure.thrownException();
    if(e->sourceLine().lineNumber()!=-1)
    {
        os << "File " << e->sourceLine().fileName() << ":" << e->sourceLine().lineNumber() << "\n";
    }
    else
    {
        os << "File Unknown:1\n";
    }
    /* TODO: expected, actual value implementation
     if(typeid(*e)==typeid(CppUnit::NotEqualException))
     {
     CppUnit::NotEqualException *ne=(CppUnit::NotEqualException *)e;

     os << "Expected Value: " << ne->expectedValue() << "\n";
     os << "Actual Value: " << ne->expectedValue() << "\n";
     os << "Additional Message: " << ne->additionalMessage() << "\n";
     }
     else
     {
     End        */
    os << "Message: " << std::string(e->what()) << "\n";
    /*      } */

    return(os.str());
}

long TestRunnerClient::CurrentTimeMillis()
{
#ifdef _WIN32 // Bugzilla 40710
    unsigned long long p;
    __asm__ __volatile__ ("rdtsc" : "=A" (p));
    return (unsigned long)p;
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);

    return((long)(tv.tv_sec*1000) + (tv.tv_usec/1000));
#endif
}

void TestRunnerClient::PrivateSleep(int millisecs)
{
    struct timeval delta;
    delta.tv_sec = (millisecs * 1000L) / 1000000L;
    delta.tv_usec = (millisecs * 1000L) % 1000000L;
    select (0, NULL, NULL, NULL, &delta);
}

CppUnit::TestResultCollector& TestRunnerClient::getResultCollector() {
    return resultCollector;
}

/*!
 * This is the main routine. The TestRunnerClient is initialized and run. The
 * CppUnit tests are created, executed, and sent to the CppUnitServer.
 * If no connection to the CppUnitServer was established the CppUnit tests are
 * displayed on the console.
 *
 * @return <code>0</code> if the results of the CppUnit tests were sent to the
 *         CppUnitServer successfully.
 *         <code>-1</code> if a connection could not be established to the
 *         CppUnitServer.
 */
int CPPUNIT_MAIN(int n, char *arg[])
{
    std::ofstream xmlFileOut("cppunit_results.xml");

    TestRunnerClient client;
    client.Init(n, arg);
    int ret = client.Run();
    if (ret == -1)
    {
        //The Test Runner Client has failed
        //Create the event manager and test controller

        CppUnit::TestResult controller;

        // Add a listener that collects test result
        CppUnit::TestResultCollector result;
        controller.addListener ( &result );

        CppUnit::XmlOutputter xmlOutputter ( &result, xmlFileOut );
        CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
        CppUnit::Test *suite = registry.makeTest();

        CppUnit::TextUi::TestRunner *runner = new CppUnit::TextUi::TestRunner();
        runner->addTest(suite);
        runner->run(controller);

        // Output to XML
        xmlOutputter.write();
    } else {

        CppUnit::TextOutputter textOutputter (&client.getResultCollector(), std::cout);
        textOutputter.write();

        // Output to XML
        CppUnit::XmlOutputter xmlOutputter ( &client.getResultCollector(), xmlFileOut );
        xmlOutputter.write();
    }


    xmlFileOut.close();
}

#endif /*CPPUNIT_MAIN*/