Remove dynamic exceptions
[anna.git] / source / testing / TestCase.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 // Standard
10 #include <string>
11 #include <fstream>
12 #include <sstream>
13 #include <cmath>
14 #include <iostream>
15
16 // Project
17 #include <anna/testing/TestCase.hpp>
18 #include <anna/testing/TestStep.hpp>
19
20 #include <anna/xml/Compiler.hpp>
21 #include <anna/diameter/defines.hpp>
22 #include <anna/diameter/helpers/dcca/defines.hpp>
23 #include <anna/diameter/codec/functions.hpp>
24 #include <anna/diameter.comm/OriginHost.hpp>
25 #include <anna/diameter/helpers/base/functions.hpp>
26 #include <anna/diameter/helpers/dcca/functions.hpp>
27 #include <anna/core/util/Millisecond.hpp>
28 #include <anna/core/tracing/Logger.hpp>
29 #include <anna/testing/TestManager.hpp>
30
31
32 using namespace anna::testing;
33
34
35 ///////////////////////////////////////////////////////////////////////////////////////////////////
36 void TestCase::DebugSummary::addHint(const std::string &hint) {
37   event_t event;
38   event.Timestamp = anna::functions::millisecond();
39   event.Hint = hint;
40   a_events.push_back(event);
41 }
42
43 void TestCase::DebugSummary::clear() {
44   a_events.clear();
45 }
46
47 anna::xml::Node* TestCase::DebugSummary::asXML(anna::xml::Node* parent) const {
48   anna::xml::Node* result = parent->createChild("DebugSummary");
49
50   std::vector<event_t>::const_iterator it;
51   for (it = a_events.begin(); it != a_events.end(); it++) {
52     anna::xml::Node* event = result->createChild("Event");
53     event->createAttribute("Timestamp", (*it).Timestamp.asString());
54     event->createAttribute("Hint", (*it).Hint);
55   }
56
57   return result;
58 };
59
60 std::string TestCase::DebugSummary::asString() const {
61   std::string result = "";
62
63   std::vector<event_t>::const_iterator it;
64   for (it = a_events.begin(); it != a_events.end(); it++) {
65     result += anna::functions::asString("[Timestamp: %s] %s", (*it).Timestamp.asString().c_str(), (*it).Hint.c_str());
66   }
67
68   return result;
69 };
70
71 ///////////////////////////////////////////////////////////////////////////////////////////////////
72
73
74 TestCase::TestCase(unsigned int id, const std::string &description) :
75     a_id(id),
76     a_description((description != "") ? description : (anna::functions::asString("Testcase_%d", id))),
77     a_state(State::Initialized),
78     a_startTimestamp(0),
79     a_finishTimestamp(0),
80     a_interactiveAmount(-1) {
81
82   /*a_stepsIt = a_steps.end()*/;
83   TestManager &testManager = TestManager::instantiate();
84   testManager.tcsStateStats(State::Initialized, State::Initialized);
85 }
86
87 TestCase::~TestCase() {
88   // TestCase should not be deleted until is safeToClear()
89   reset(true); // hard reset
90   std::vector<TestStep*>::const_iterator it;
91   for (it = a_steps.begin(); it != a_steps.end(); it++) delete (*it);
92 }
93
94
95 const char* TestCase::asText(const State::_v state)
96 {
97   static const char* text [] = { "Initialized", "InProgress", "Failed", "Success" };
98   return text [state];
99 }
100
101 anna::Millisecond TestCase::getLapseMs() const {
102   return ((a_finishTimestamp >= a_startTimestamp) ? (a_finishTimestamp - a_startTimestamp) : (anna::Millisecond)0);
103 }
104
105 anna::xml::Node* TestCase::asXML(anna::xml::Node* parent) const
106 {
107   anna::xml::Node* result = parent->createChild("TestCase");
108
109   result->createAttribute("Id", a_id);
110   result->createAttribute("Description", a_description);
111   result->createAttribute("State", asText(a_state));
112   result->createAttribute("StartTimestamp", a_startTimestamp.asString());
113
114   if (a_finishTimestamp != 0) {
115     result->createAttribute("FinishTimestamp", a_finishTimestamp.asString());
116     result->createAttribute("LapseMs", getLapseMs());
117   }
118
119   int steps = a_steps.size();
120   if (steps != 0) {
121     result->createAttribute("NumberOfTestSteps", steps);
122     std::vector<TestStep*>::const_iterator it;
123     for (it = a_steps.begin(); it != a_steps.end(); it++) {
124       (*it)->asXML(result);
125     }
126   }
127
128   if (a_debugSummary.events()) {
129     a_debugSummary.asXML(result);
130   }
131
132   result->createAttribute("Interactive", (a_interactiveAmount != -1) ? "yes":"no");
133
134   return result;
135 }
136
137 std::string TestCase::asXMLString() const {
138   anna::xml::Node root("root");
139   return anna::xml::Compiler().apply(asXML(&root));
140 }
141
142 bool TestCase::hasSameCondition(const TestDiameterCondition &condition) const {
143   std::vector<TestStep*>::const_iterator it;
144   TestStepWaitDiameter *step;
145   for (it = a_steps.begin(); it != a_steps.end(); it++) {
146     if ((*it)->getType() != TestStep::Type::Wait) continue;
147     step = (TestStepWaitDiameter *)(*it);
148     if (step->getCondition() == condition) return true;
149   }
150   return false;
151 }
152
153
154 void TestCase::setState(const State::_v &state) {
155
156   State::_v previousState = a_state;
157   if (state == previousState) return;
158   a_state = state;
159   TestManager &testManager = TestManager::instantiate();
160
161   // stats:
162   testManager.tcsStateStats(previousState, state);
163
164
165   if (isFinished()) {
166     const char *literal = "FINISHED Test Case %llu/%llu [%s] => %s";
167     TestManager& testManager (TestManager::instantiate ());
168     LOGDEBUG(anna::Logger::debug(anna::functions::asString(literal, getId(), testManager.tests(), getDescription().c_str(), asText(a_state)), ANNA_FILE_LOCATION));
169
170     if (testManager.getDumpStdout()) {
171       std::cout << std::endl << anna::functions::asString(literal, getId(), testManager.tests(), getDescription().c_str(), asText(a_state)) << std::endl;
172     }
173
174     a_finishTimestamp = anna::functions::millisecond();
175
176     // Cancel existing timers:
177     std::vector<TestStep*>::iterator it;
178     for (it = a_steps.begin(); it != a_steps.end(); it++) {
179       if ((*it)->getType() == TestStep::Type::Timeout) {
180         TestStepTimeout *step = (TestStepTimeout *)(*it);
181         step->cancelTimer();
182       }
183       else if ((*it)->getType() == TestStep::Type::Delay) {
184         TestStepDelay *step = (TestStepDelay *)(*it);
185         step->cancelTimer();
186       }
187     }
188
189     if ((getState() == State::Failed) && (!testManager.getDumpFailedReports())) return;
190     if ((getState() == State::Success) && (!testManager.getDumpSuccessReports())) return;
191     // report file name: cycle-<cycle id>.testcase-<test case id>.xml
192
193     // FORMAT: We tabulate the cycle and test case in order to ease ordering of files by mean ls:
194     int cycles = testManager.getPoolRepeats();
195     int tests = testManager.tests();
196     int cyclesWidth = (cycles<=0) ? 3 /* 1000 cycles !! */: ((int) log10 ((double) cycles) + 1);
197     int testsWidth = (tests<=0) ? 9 /* subscribers */: ((int) log10 ((double) tests) + 1);
198     std::stringstream format;
199     format << "/cycle-%0" << cyclesWidth << "d.testcase-%0" << testsWidth << "llu.xml";
200
201     // FILE NAME:
202     std::string file = testManager.getReportsDirectory() + anna::functions::asString(format.str().c_str(), testManager.getPoolCycle(), a_id);
203     std::ofstream out;
204     out.open(file.c_str(), std::ofstream::out | std::ofstream::app);
205     if(out.is_open() == false) {
206       std::string msg("Error opening '");
207       msg += file;
208       msg += "' for writting";
209       anna::Logger::error(msg, ANNA_FILE_LOCATION);
210     }
211     else {
212       out << asXMLString() << std::endl;
213       out.close();
214     }
215   }
216 }
217
218 bool TestCase::done() {
219   if (a_stepsIt == a_steps.end()) {
220     setState(State::Success);
221     return true;
222   }
223
224   return false;
225 }
226
227 bool TestCase::process() {
228   if (steps() == 0) {
229     LOGWARNING(anna::Logger::warning(anna::functions::asString("Test case %llu (%s) is empty, nothing to execute", a_id, a_description.c_str()), ANNA_FILE_LOCATION));
230     return false;
231   }
232   if (isFinished()) {
233     LOGDEBUG(anna::Logger::debug(anna::functions::asString("Test case %llu (%s) is finished, nothing done until soft-reset", a_id, a_description.c_str()), ANNA_FILE_LOCATION));
234     return false;
235   }
236
237   const char *literal = "PROCESS Test Case %llu/%llu [%s]";
238   TestManager& testManager (TestManager::instantiate ());
239   LOGDEBUG(anna::Logger::debug(anna::functions::asString(literal, getId(), testManager.tests(), getDescription().c_str()), ANNA_FILE_LOCATION));
240
241   if (a_state == State::Initialized) {
242     if (testManager.getDumpStdout()) {
243       std::cout << std::endl << std::endl << anna::functions::asString(literal, getId(), testManager.tests(), getDescription().c_str()) << std::endl;
244     }
245
246     a_stepsIt = a_steps.begin();
247     setState(State::InProgress);
248
249     // For 'wait' steps (not really useful, but better than nothing: begin timestamp on test case start timestamp...):
250     a_startTimestamp = anna::functions::millisecond();
251   }
252
253   // Check end of the test case:
254   if (done()) return false;
255
256   bool somethingDone = false;
257   while ((*a_stepsIt)->execute()) { // executes returns 'true' if the next step must be also executed (execute until can't stand no more)
258     nextStep();
259     // Check end of the test case:
260     if (done()) return false;
261     somethingDone = true;
262   }
263
264   return somethingDone;
265 }
266
267 bool TestCase::reset(bool hard) {
268
269   // Soft reset if finished:
270   if (!hard /* is soft reset */  && !isFinished()) return false;
271
272   // Dump as failed if still in progress (hard reset):
273   if (getState() == State::InProgress) {
274     addDebugSummaryHint("Testcase hard reset while in progress");
275     setState(State::Failed);
276   }
277
278   // Clean stage ////////////////////////////
279   // id is kept
280   std::vector<TestStep*>::iterator it;
281   for (it = a_steps.begin(); it != a_steps.end(); it++)
282     (*it)->reset();
283
284   a_debugSummary.clear();
285   a_startTimestamp = 0;
286   a_finishTimestamp = 0;
287   a_interactiveAmount = -1;
288
289   setState(State::Initialized);
290
291   return true;
292 }
293
294 bool TestCase::safeToClear() {
295
296   // Check if any step is running (command steps):
297   std::vector<TestStep*>::const_iterator it;
298   for (it = a_steps.begin(); it != a_steps.end(); it++) {
299     if ((*it)->getType() == TestStep::Type::Cmd) {
300       const TestStepCmd *tscmd = static_cast<const TestStepCmd*>(*it);
301       if(tscmd->threadRunning())
302         return false;
303     }
304   }
305
306   return true;
307 }
308
309 void TestCase::assertInitialized() const noexcept(false) {
310   if (isFinished())
311     throw anna::RuntimeException(anna::functions::asString("Cannot program anymore. The test case %llu (%s) has finished. You must reset it to append new steps (or do it during execution, which is also allowed).", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
312 }
313
314 void TestCase::assertMessage(const anna::DataBlock &db, bool toEntity) noexcept(false) {
315
316   bool isRequest = anna::diameter::codec::functions::isRequest(db);
317   bool registerKeys = ((isRequest && toEntity) || (!isRequest && !toEntity) /* (*) */);
318   // (*) we register answers Session-Id "assuming" that we will know the Session-Id values created by the client.
319   // This is another solution regarding diameter server testing. No sure about the final implementation.
320   // We will help registering also subscriber data, because certain messages (i.e. SLR) coming from clients could
321   //  have specific Session-Id value (unknown at test programming), and normally are identified by subscriber.
322
323   // Check hop-by-hop:
324   if (isRequest) {
325     anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
326     if (a_hopByHops.find(hbh) != a_hopByHops.end())
327       throw anna::RuntimeException(anna::functions::asString("Another request has been programmed with the same hop-by-hop (%llu) in this test case (%llu, '%s')", hbh, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
328     a_hopByHops[hbh] = NULL; // may be assigned to a wait condition
329   }
330
331   if (registerKeys) {
332     TestManager &testManager = TestManager::instantiate();
333     testManager.registerKey1(anna::diameter::helpers::base::functions::getSessionId(db), this);
334
335
336     std::string subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
337     if (subscriberId == "") // try with IMSI
338       subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
339
340     if (subscriberId != "")
341       testManager.registerKey2(subscriberId, this);
342   }
343 }
344
345 void TestCase::addTimeout(const anna::Millisecond &timeout) noexcept(false) {
346   assertInitialized();
347   TestStepTimeout *step = new TestStepTimeout(this);
348   step->setTimeout(timeout);
349   addStep(step);
350 }
351
352 void TestCase::addSendDiameterXml2e(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) noexcept(false) {
353   assertInitialized();
354   assertMessage(db, true /* to entity */);
355
356   if (stepNumber != -1) {
357     const TestStep *stepReferred = getStep(stepNumber);
358     if (!stepReferred)
359       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
360
361     if (stepReferred->getType() != TestStep::Type::Wait)
362       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
363
364     const TestDiameterCondition &tc = (static_cast<const TestStepWaitDiameter*>(stepReferred))->getCondition();
365     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
366       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait for request' step (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
367     }
368   }
369
370   TestStepSendDiameterXml2e *step = new TestStepSendDiameterXml2e(this);
371   step->setMsgDataBlock(db);
372   step->setOriginHost(host);
373   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
374   addStep(step);
375 }
376
377 void TestCase::addSendDiameterXml2c(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) noexcept(false) {
378   assertInitialized();
379   assertMessage(db, false /* to client */);
380
381   if (stepNumber != -1) {
382     const TestStep *stepReferred = getStep(stepNumber);
383     if (!stepReferred)
384       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
385
386     if (stepReferred->getType() != TestStep::Type::Wait)
387       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
388
389     const TestDiameterCondition &tc = (static_cast<const TestStepWaitDiameter*>(stepReferred))->getCondition();
390     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
391       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait for request' step (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
392     }
393   }
394
395   TestStepSendDiameterXml2c *step = new TestStepSendDiameterXml2c(this);
396   step->setMsgDataBlock(db);
397   step->setOriginHost(host);
398   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
399   addStep(step);
400 }
401
402 void TestCase::addDelay(const anna::Millisecond &delay) noexcept(false) {
403   assertInitialized();
404   TestStepDelay *step = new TestStepDelay(this);
405   step->setDelay(delay);
406   addStep(step);
407 }
408
409 void TestCase::addWaitDiameter(bool fromEntity,
410               const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
411               const std::string &sessionId, const std::string &resultCode,
412               const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) noexcept(false) {
413   assertInitialized();
414   std::string usedHopByHop = hopByHop;
415   TestStepWaitDiameter *step = NULL;
416
417   // Check basic conditions:
418   if (bitR == "1") {
419     if (resultCode != "")
420       throw anna::RuntimeException(anna::functions::asString("You cannot specify Result-Code (%s) for a wait condition of a diameter request message (test case %llu, '%s')", resultCode.c_str(), a_id, a_description.c_str()), ANNA_FILE_LOCATION);
421     if (hopByHop != "")
422       throw anna::RuntimeException(anna::functions::asString("You cannot specify Hop-by-hop (%s) for a wait condition of a diameter request message (test case %llu, '%s')", hopByHop.c_str(), a_id, a_description.c_str()), ANNA_FILE_LOCATION);
423   }
424   else {
425     if (hopByHop != "") {
426       if (hopByHop[0] == '#') {
427         if (steps() == 0)
428           throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu, '%s')", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
429
430         int stepNumber = atoi(hopByHop.substr(1).c_str());
431
432         const TestStep *stepReferred = getStep(stepNumber);
433         if (!stepReferred)
434           throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu, '%s')", stepNumber, a_id, a_description.c_str()), ANNA_FILE_LOCATION);
435
436         if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
437           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu, '%s')", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
438
439         const anna::DataBlock &db = (static_cast<const TestStepSendDiameterXml*>(stepReferred))->getMsgDataBlock();
440         bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
441         if (isAnswer)
442           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu, '%s')", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
443
444         // Hop-by-hop:
445         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
446         usedHopByHop = anna::functions::asString(hbh);
447         step = new TestStepWaitDiameter(this);
448         a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
449       }
450     }
451   }
452
453   if (!step) step = new TestStepWaitDiameter(this);
454   step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
455
456   LOGINFORMATION(
457     if (hasSameCondition(step->getCondition()))
458       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu, '%s'). Are you sure ?", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
459   );
460
461   addStep(step);
462 }
463
464 void TestCase::addWaitDiameterRegexpHex(bool fromEntity, const std::string &regexp) noexcept(false) {
465   assertInitialized();
466
467   TestStepWaitDiameter *step = new TestStepWaitDiameter(this);
468   step->setConditionRegexpHex(fromEntity, regexp);
469
470   LOGINFORMATION(
471     if (hasSameCondition(step->getCondition()))
472       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu, '%s'). Are you sure ?", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
473   );
474
475   addStep(step);
476 }
477
478 void TestCase::addWaitDiameterRegexpXml(bool fromEntity, const std::string &regexp) noexcept(false) {
479   assertInitialized();
480
481   TestStepWaitDiameter *step = new TestStepWaitDiameter(this);
482   step->setConditionRegexpXml(fromEntity, regexp);
483
484   LOGINFORMATION(
485     if (hasSameCondition(step->getCondition()))
486       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu, '%s'). Are you sure ?", a_id, a_description.c_str()), ANNA_FILE_LOCATION);
487   );
488
489   addStep(step);
490 }
491
492 void TestCase::addCommand(const std::string &cmd) noexcept(false) {
493   assertInitialized();
494
495   TestStepCmd *step = new TestStepCmd(this);
496   step->setScript(cmd);
497
498   addStep(step);
499 }
500
501 void TestCase::addIpLimit(unsigned int ipLimit) noexcept(false) {
502   assertInitialized();
503
504   TestStepIpLimit *step = new TestStepIpLimit(this);
505   step->setIpLimit(ipLimit);
506
507   addStep(step);
508 }
509
510 TestStepWaitDiameter *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) {
511
512   TestStepWaitDiameter *result;
513   for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
514     if ((*it)->getType() != TestStep::Type::Wait) continue;
515     if ((*it)->isCompleted()) continue;
516     result = (TestStepWaitDiameter*)(*it);
517     if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
518       return result;
519   }
520
521   return NULL;
522 }
523
524 const TestStep *TestCase::getStep(int stepNumber) const {
525   if (stepNumber < 1 || stepNumber > steps()) return NULL;
526 //  return a_steps.at(stepNumber-1);  // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
527   return a_steps[stepNumber-1];
528 }