818093b4de0483242e627eee14c56674978fecc4
[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   // Dump as failed if still in progress (hard reset):
215   if (getState() == State::InProgress) {
216     addDebugSummaryHint("Testcase hard reset while in progress");
217     setState(State::Failed);
218   }
219
220   // Clean stage ////////////////////////////
221   // id is kept
222   std::vector<TestStep*>::iterator it;
223   for (it = a_steps.begin(); it != a_steps.end(); it++)
224     (*it)->reset();
225
226   a_debugSummary.clear();
227   a_startTime = 0;
228   a_interactiveAmount = -1;
229
230   setState(State::Initialized);
231
232   return true;
233 }
234
235 void TestCase::assertInitialized() const throw(anna::RuntimeException) {
236   if (isFinished())
237     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);
238 }
239
240 void TestCase::assertMessage(const anna::DataBlock &db, bool toEntity) throw(anna::RuntimeException) {
241
242   bool isRequest = anna::diameter::codec::functions::isRequest(db);
243   bool registerKeys = ((isRequest && toEntity) || (!isRequest && !toEntity) /* (*) */);
244   // (*) we register answers Session-Id "assuming" that we will know the Session-Id values created by the client.
245   // This is another solution regarding diameter server testing. No sure about the final implementation.
246   // We will help registering also subscriber data, because certain messages (i.e. SLR) coming from clients could
247   //  have specific Session-Id value (unknown at test programming), and normally are identified by subscriber.
248
249   // Check hop-by-hop:
250   if (isRequest) {
251     anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
252     if (a_hopByHops.find(hbh) != a_hopByHops.end())
253       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);
254     a_hopByHops[hbh] = NULL; // may be assigned to a wait condition
255   }
256
257   if (registerKeys) {
258     TestManager &testManager = TestManager::instantiate();
259     testManager.registerKey1(anna::diameter::helpers::base::functions::getSessionId(db), this);
260
261
262     std::string subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
263     if (subscriberId == "") // try with IMSI
264       subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
265
266     if (subscriberId != "")
267       testManager.registerKey2(subscriberId, this);
268   }
269 }
270
271 void TestCase::addTimeout(const anna::Millisecond &timeout) throw(anna::RuntimeException) {
272   assertInitialized();
273   TestStepTimeout *step = new TestStepTimeout(this);
274   step->setTimeout(timeout);
275   addStep(step);
276 }
277
278 void TestCase::addSendxml2e(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
279   assertInitialized();
280   assertMessage(db, true /* to entity */);
281
282   if (stepNumber != -1) {
283     const TestStep *stepReferred = getStep(stepNumber);
284     if (!stepReferred)
285       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
286
287     if (stepReferred->getType() != TestStep::Type::Wait)
288       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
289
290     const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
291     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
292       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);
293     }
294   }
295
296   TestStepSendxml2e *step = new TestStepSendxml2e(this);
297   step->setMsgDataBlock(db);
298   step->setOriginHost(host);
299   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
300   addStep(step);
301 }
302
303 void TestCase::addSendxml2c(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
304   assertInitialized();
305   assertMessage(db, false /* to client */);
306
307   if (stepNumber != -1) {
308     const TestStep *stepReferred = getStep(stepNumber);
309     if (!stepReferred)
310       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
311
312     if (stepReferred->getType() != TestStep::Type::Wait)
313       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
314
315     const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
316     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
317       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);
318     }
319   }
320
321   TestStepSendxml2c *step = new TestStepSendxml2c(this);
322   step->setMsgDataBlock(db);
323   step->setOriginHost(host);
324   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
325   addStep(step);
326 }
327
328 void TestCase::addDelay(const anna::Millisecond &delay) throw(anna::RuntimeException) {
329   assertInitialized();
330   TestStepDelay *step = new TestStepDelay(this);
331   step->setDelay(delay);
332   addStep(step);
333 }
334
335 void TestCase::addWait(bool fromEntity,
336               const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
337               const std::string &sessionId, const std::string &resultCode,
338               const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw(anna::RuntimeException) {
339   assertInitialized();
340   std::string usedHopByHop = hopByHop;
341   TestStepWait *step = NULL;
342
343   // Check basic conditions:
344   if (bitR == "1") {
345     if (resultCode != "")
346       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);
347     if (hopByHop != "")
348       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);
349   }
350   else {
351     if (hopByHop != "") {
352       if (hopByHop[0] == '#') {
353         if (steps() == 0)
354           throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu)", a_id), ANNA_FILE_LOCATION);
355
356         int stepNumber = atoi(hopByHop.substr(1).c_str());
357
358         const TestStep *stepReferred = getStep(stepNumber);
359         if (!stepReferred)
360           throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
361
362         if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
363           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu)", a_id), ANNA_FILE_LOCATION);
364
365         const anna::DataBlock &db = (static_cast<const TestStepSendxml*>(stepReferred))->getMsgDataBlock();
366         bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
367         if (isAnswer)
368           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu)", a_id), ANNA_FILE_LOCATION);
369
370         // Hop-by-hop:
371         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
372         usedHopByHop = anna::functions::asString(hbh);
373         step = new TestStepWait(this);
374         a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
375       }
376     }
377   }
378
379   if (!step) step = new TestStepWait(this);
380   step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
381
382   LOGINFORMATION(
383     if (hasSameCondition(step->getCondition()))
384       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);
385   );
386
387   addStep(step);
388 }
389
390 void TestCase::addWaitRegexpHex(bool fromEntity, const std::string &regexp) throw(anna::RuntimeException) {
391   assertInitialized();
392
393   TestStepWait *step = new TestStepWait(this);
394   step->setConditionRegexpHex(fromEntity, regexp);
395
396   LOGINFORMATION(
397     if (hasSameCondition(step->getCondition()))
398       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);
399   );
400
401   addStep(step);
402 }
403
404 void TestCase::addWaitRegexpXml(bool fromEntity, const std::string &regexp) throw(anna::RuntimeException) {
405   assertInitialized();
406
407   TestStepWait *step = new TestStepWait(this);
408   step->setConditionRegexpXml(fromEntity, regexp);
409
410   LOGINFORMATION(
411     if (hasSameCondition(step->getCondition()))
412       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);
413   );
414
415   addStep(step);
416 }
417
418 void TestCase::addCommand(const std::string &cmd) throw(anna::RuntimeException) {
419   assertInitialized();
420
421   TestStepCmd *step = new TestStepCmd(this);
422   step->setScript(cmd);
423
424   addStep(step);
425 }
426
427 TestStepWait *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) throw() {
428
429   TestStepWait *result;
430   for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
431     if ((*it)->getType() != TestStep::Type::Wait) continue;
432     if ((*it)->isCompleted()) continue;
433     result = (TestStepWait*)(*it);
434     if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
435       return result;
436   }
437
438   return NULL;
439 }
440
441 const TestStep *TestCase::getStep(int stepNumber) const throw() {
442   if (stepNumber < 1 || stepNumber > steps()) return NULL;
443 //  return a_steps.at(stepNumber-1);  // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
444   return a_steps[stepNumber-1];
445 }