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