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