f8d7a986f326d8868c5d5f011e1434863b077c09
[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) throw() {
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() throw() {
44   a_events.clear();
45 }
46
47 anna::xml::Node* TestCase::DebugSummary::asXML(anna::xml::Node* parent) const throw() {
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
61
62 TestCase::TestCase(unsigned int id) :
63     a_id(id),
64     a_state(State::Initialized),
65     a_startTime(0),
66     a_interactiveAmount(-1) {
67
68   /*a_stepsIt = a_steps.end()*/;
69   TestManager &testManager = TestManager::instantiate();
70   testManager.tcsStateStats(State::Initialized, State::Initialized);
71 }
72
73 TestCase::~TestCase() {
74   reset(true); // hard reset
75   std::vector<TestStep*>::const_iterator it;
76   for (it = a_steps.begin(); it != a_steps.end(); it++) delete (*it);
77 }
78
79 const char* TestCase::asText(const State::_v state)
80 throw() {
81   static const char* text [] = { "Initialized", "InProgress", "Failed", "Success" };
82   return text [state];
83 }
84
85 anna::xml::Node* TestCase::asXML(anna::xml::Node* parent) const
86 throw() {
87   anna::xml::Node* result = parent->createChild("TestCase");
88
89   result->createAttribute("Id", a_id);
90   result->createAttribute("State", asText(a_state));
91   result->createAttribute("StartTimestamp", a_startTime.asString());
92   int steps = a_steps.size();
93   if (steps != 0) {
94     result->createAttribute("NumberOfTestSteps", steps);
95     std::vector<TestStep*>::const_iterator it;
96     for (it = a_steps.begin(); it != a_steps.end(); it++) {
97       (*it)->asXML(result);
98     }
99   }
100
101   if (a_debugSummary.events()) {
102     a_debugSummary.asXML(result);
103   }
104
105   result->createAttribute("Interactive", (a_interactiveAmount != -1) ? "yes":"no");
106
107   return result;
108 }
109
110 std::string TestCase::asXMLString() const throw() {
111   anna::xml::Node root("root");
112   return anna::xml::Compiler().apply(asXML(&root));
113 }
114
115 bool TestCase::hasSameCondition(const TestCondition &condition) const throw() {
116   std::vector<TestStep*>::const_iterator it;
117   TestStepWait *step;
118   for (it = a_steps.begin(); it != a_steps.end(); it++) {
119     if ((*it)->getType() != TestStep::Type::Wait) continue;
120     step = (TestStepWait *)(*it);
121     if (step->getCondition() == condition) return true;
122   }
123   return false;
124 }
125
126
127 void TestCase::setState(const State::_v &state) throw() {
128
129   State::_v previousState = a_state;
130   if (state == previousState) return;
131   a_state = state;
132   TestManager &testManager = TestManager::instantiate();
133
134   // stats:
135   testManager.tcsStateStats(previousState, state);
136
137
138   if (isFinished()) {
139     if ((getState() == State::Failed) && (!testManager.getDumpFailedReports())) return;
140     if ((getState() == State::Success) && (!testManager.getDumpSuccessReports())) return;
141     // report file name: cycle-<cycle id>.testcase-<test case id>.xml
142
143     // FORMAT: We tabulate the cycle and test case in order to ease ordering of files by mean ls:
144     int cycles = testManager.getPoolRepeats();
145     int tests = testManager.tests();
146     int cyclesWidth = (cycles<=0) ? 3 /* 1000 cycles !! */: ((int) log10 ((double) cycles) + 1);
147     int testsWidth = (tests<=0) ? 9 /* subscribers */: ((int) log10 ((double) tests) + 1);
148     std::stringstream format;
149     format << "/cycle-%0" << cyclesWidth << "d.testcase-%0" << testsWidth << "llu.xml";
150
151     // FILE NAME:
152     std::string file = testManager.getReportsDirectory() + anna::functions::asString(format.str().c_str(), testManager.getPoolCycle(), a_id);
153     std::ofstream out;
154     out.open(file.c_str(), std::ofstream::out | std::ofstream::app);
155     if(out.is_open() == false) {
156       std::string msg("Error opening '");
157       msg += file;
158       msg += "' for writting";
159       anna::Logger::error(msg, ANNA_FILE_LOCATION);
160     }
161     else {
162       out << asXMLString() << std::endl;
163       out.close();
164     }
165   }
166 }
167
168 bool TestCase::done() throw() {
169   if (a_stepsIt == a_steps.end()) {
170     setState(State::Success);
171     return true;
172   }
173
174   return false;
175 }
176
177 bool TestCase::process() throw() {
178   if (steps() == 0) {
179     LOGWARNING(anna::Logger::warning(anna::functions::asString("Test case %llu is empty, nothing to execute", a_id), ANNA_FILE_LOCATION));
180     return false;
181   }
182   if (isFinished()) {
183     LOGDEBUG(anna::Logger::debug(anna::functions::asString("Test case %llu is finished, nothing done until soft-reset", a_id), ANNA_FILE_LOCATION));
184     return false;
185   }
186
187   if (a_state == State::Initialized) {
188     a_stepsIt = a_steps.begin();
189     setState(State::InProgress);
190
191     // For 'wait' steps (not really useful, but better than nothing: begin timestamp on test case start timestamp...):
192     a_startTime = anna::functions::millisecond();
193   }
194
195   // Check end of the test case:
196   if (done()) return false;
197
198   bool somethingDone = false;
199   while ((*a_stepsIt)->execute()) { // executes returns 'true' if the next step must be also executed (execute until can't stand no more)
200     nextStep();
201     // Check end of the test case:
202     if (done()) return false;
203     somethingDone = true;
204   }
205
206   return somethingDone;
207 }
208
209 bool TestCase::reset(bool hard) throw() {
210
211   // Soft reset if finished:
212   if (!hard /* is soft reset */  && !isFinished()) return false;
213
214   // Clean stage ////////////////////////////
215   // id is kept
216   std::vector<TestStep*>::iterator it;
217   for (it = a_steps.begin(); it != a_steps.end(); it++)
218     (*it)->reset();
219
220   a_debugSummary.clear();
221   a_startTime = 0;
222   a_interactiveAmount = -1;
223
224   setState(State::Initialized);
225
226   return true;
227 }
228
229 void TestCase::assertInitialized() const throw(anna::RuntimeException) {
230   if (isFinished())
231     throw anna::RuntimeException(anna::functions::asString("Cannot program anymore. The test case %llu has finished. You must reset it to append new steps (or do it during execution, which is also allowed).", a_id), ANNA_FILE_LOCATION);
232 }
233
234 void TestCase::assertMessage(const anna::DataBlock &db, bool toEntity) throw(anna::RuntimeException) {
235
236   bool isRequest = anna::diameter::codec::functions::isRequest(db);
237   bool registerKeys = ((isRequest && toEntity) || (!isRequest && !toEntity) /* (*) */);
238   // (*) we register answers Session-Id "assuming" that we will know the Session-Id values created by the client.
239   // This is another solution regarding diameter server testing. No sure about the final implementation.
240   // We will help registering also subscriber data, because certain messages (i.e. SLR) coming from clients could
241   //  have specific Session-Id value (unknown at test programming), and normally are identified by subscriber.
242
243   // Check hop-by-hop:
244   if (isRequest) {
245     anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
246     if (a_hopByHops.find(hbh) != a_hopByHops.end())
247       throw anna::RuntimeException(anna::functions::asString("Another request has been programmed with the same hop-by-hop (%llu) in this test case (%llu)", hbh, a_id), ANNA_FILE_LOCATION);
248     a_hopByHops[hbh] = NULL; // may be assigned to a wait condition
249   }
250
251   if (registerKeys) {
252     TestManager &testManager = TestManager::instantiate();
253     testManager.registerSessionId(anna::diameter::helpers::base::functions::getSessionId(db), this);
254
255
256     std::string subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
257     if (subscriberId == "") // try with IMSI
258       subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
259
260     if (subscriberId != "")
261       testManager.registerSubscriberId(subscriberId, this);
262   }
263 }
264
265 void TestCase::addTimeout(const anna::Millisecond &timeout) throw(anna::RuntimeException) {
266   assertInitialized();
267   TestStepTimeout *step = new TestStepTimeout(this);
268   step->setTimeout(timeout);
269   addStep(step);
270 }
271
272 void TestCase::addSendxml2e(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
273   assertInitialized();
274   assertMessage(db, true /* to entity */);
275
276   if (stepNumber != -1) {
277     const TestStep *stepReferred = getStep(stepNumber);
278     if (!stepReferred)
279       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
280
281     if (stepReferred->getType() != TestStep::Type::Wait)
282       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
283
284     const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
285     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
286       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait for request' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
287     }
288   }
289
290   TestStepSendxml2e *step = new TestStepSendxml2e(this);
291   step->setMsgDataBlock(db);
292   step->setOriginHost(host);
293   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
294   addStep(step);
295 }
296
297 void TestCase::addSendxml2c(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
298   assertInitialized();
299   assertMessage(db, false /* to client */);
300
301   TestStepSendxml2c *step = new TestStepSendxml2c(this);
302   step->setMsgDataBlock(db);
303   step->setOriginHost(host);
304   addStep(step);
305 }
306
307 void TestCase::addDelay(const anna::Millisecond &delay) throw(anna::RuntimeException) {
308   assertInitialized();
309   TestStepDelay *step = new TestStepDelay(this);
310   step->setDelay(delay);
311   addStep(step);
312 }
313
314 void TestCase::addWait(bool fromEntity,
315               const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
316               const std::string &sessionId, const std::string &resultCode,
317               const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw(anna::RuntimeException) {
318   assertInitialized();
319   std::string usedHopByHop = hopByHop;
320   TestStepWait *step = NULL;
321
322   // Check basic conditions:
323   if (bitR == "1") {
324     if (resultCode != "")
325       throw anna::RuntimeException(anna::functions::asString("You cannot specify Result-Code (%s) for a wait condition of a diameter request message (test case %llu)", resultCode.c_str(), a_id), ANNA_FILE_LOCATION);
326     if (hopByHop != "")
327       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)", hopByHop.c_str(), a_id), ANNA_FILE_LOCATION);
328   }
329   else {
330     if (hopByHop != "") {
331       if (hopByHop[0] == '#') {
332         if (steps() == 0)
333           throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu)", a_id), ANNA_FILE_LOCATION);
334
335         int stepNumber = atoi(hopByHop.substr(1).c_str());
336
337         const TestStep *stepReferred = getStep(stepNumber);
338         if (!stepReferred)
339           throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
340
341         if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
342           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu)", a_id), ANNA_FILE_LOCATION);
343
344         const anna::DataBlock &db = (static_cast<const TestStepSendxml*>(stepReferred))->getMsgDataBlock();
345         bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
346         if (isAnswer)
347           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu)", a_id), ANNA_FILE_LOCATION);
348
349         // Hop-by-hop:
350         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
351         usedHopByHop = anna::functions::asString(hbh);
352         step = new TestStepWait(this);
353         a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
354       }
355     }
356   }
357
358   if (!step) step = new TestStepWait(this);
359   step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
360
361   LOGINFORMATION(
362     if (hasSameCondition(step->getCondition()))
363       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
364   );
365
366   addStep(step);
367 }
368
369 void TestCase::addWaitRegexpHex(bool fromEntity, const std::string &regexp) throw(anna::RuntimeException) {
370   assertInitialized();
371
372   TestStepWait *step = new TestStepWait(this);
373   step->setConditionRegexpHex(fromEntity, regexp);
374
375   LOGINFORMATION(
376     if (hasSameCondition(step->getCondition()))
377       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
378   );
379
380   addStep(step);
381 }
382
383 void TestCase::addWaitRegexpXml(bool fromEntity, const std::string &regexp) throw(anna::RuntimeException) {
384   assertInitialized();
385
386   TestStepWait *step = new TestStepWait(this);
387   step->setConditionRegexpXml(fromEntity, regexp);
388
389   LOGINFORMATION(
390     if (hasSameCondition(step->getCondition()))
391       anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
392   );
393
394   addStep(step);
395 }
396
397 void TestCase::addCommand(const std::string &cmd) throw(anna::RuntimeException) {
398   assertInitialized();
399
400   TestStepCmd *step = new TestStepCmd(this);
401   step->setScript(cmd);
402
403   addStep(step);
404 }
405
406 TestStepWait *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) throw() {
407
408   TestStepWait *result;
409   for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
410     if ((*it)->getType() != TestStep::Type::Wait) continue;
411     if ((*it)->isCompleted()) continue;
412     result = (TestStepWait*)(*it);
413     if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
414       return result;
415   }
416
417   return NULL;
418 }
419
420 const TestStep *TestCase::getStep(int stepNumber) const throw() {
421   if (stepNumber < 1 || stepNumber > steps()) return NULL;
422 //  return a_steps.at(stepNumber-1);  // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
423   return a_steps[stepNumber-1];
424 }