Session-Id don't have to be mandatory to programm 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     try {
246       std::string sid = anna::diameter::helpers::base::functions::getSessionId(db);
247       TestManager::instantiate().registerSessionId(sid, this);
248     }
249     catch (anna::RuntimeException &ex) {
250       //ex.trace();
251       // if we don't have session-id ... don't worry
252     }
253   }
254 }
255
256 void TestCase::addTimeout(const anna::Millisecond &timeout) throw(anna::RuntimeException) {
257   assertInitialized();
258   TestStepTimeout *step = new TestStepTimeout(this);
259   step->setTimeout(timeout);
260   addStep(step);
261 }
262
263 void TestCase::addSendxml2e(const anna::DataBlock &db, RealmNode *realm, int stepNumber) throw(anna::RuntimeException) {
264   assertInitialized();
265   assertMessage(db, true /* to entity */);
266
267   if (stepNumber != -1) {
268     const TestStep *stepReferred = getStep(stepNumber);
269     if (!stepReferred)
270       throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
271
272     if (stepReferred->getType() != TestStep::Type::Wait)
273       throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
274
275     const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
276     if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
277       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);
278     }
279   }
280
281   TestStepSendxml2e *step = new TestStepSendxml2e(this);
282   step->setMsgDataBlock(db);
283   step->setRealmNode(realm);
284   step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
285   addStep(step);
286 }
287
288 void TestCase::addSendxml2c(const anna::DataBlock &db, RealmNode *realm, int stepNumber) throw(anna::RuntimeException) {
289   assertInitialized();
290   assertMessage(db, false /* to client */);
291
292   TestStepSendxml2c *step = new TestStepSendxml2c(this);
293   step->setMsgDataBlock(db);
294   step->setRealmNode(realm);
295   addStep(step);
296 }
297
298 void TestCase::addDelay(const anna::Millisecond &delay) throw(anna::RuntimeException) {
299   assertInitialized();
300   TestStepDelay *step = new TestStepDelay(this);
301   step->setDelay(delay);
302   addStep(step);
303 }
304
305 void TestCase::addWait(bool fromEntity,
306               const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
307               const std::string &sessionId, const std::string &resultCode,
308               const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw(anna::RuntimeException) {
309   assertInitialized();
310   std::string usedHopByHop = hopByHop;
311   TestStepWait *step = NULL;
312
313   // Check basic conditions:
314   if (bitR == "1") {
315     if (resultCode != "")
316       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);
317     if (hopByHop != "")
318       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);
319   }
320   else {
321     if (hopByHop != "") {
322       if (hopByHop[0] == '#') {
323         if (steps() == 0)
324           throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu)", a_id), ANNA_FILE_LOCATION);
325
326         int stepNumber = atoi(hopByHop.substr(1).c_str());
327
328         const TestStep *stepReferred = getStep(stepNumber);
329         if (!stepReferred)
330           throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
331
332         if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
333           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu)", a_id), ANNA_FILE_LOCATION);
334
335         const anna::DataBlock &db = (static_cast<const TestStepSendxml*>(stepReferred))->getMsgDataBlock();
336         bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
337         if (isAnswer)
338           throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu)", a_id), ANNA_FILE_LOCATION);
339
340         // Hop-by-hop:
341         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
342         usedHopByHop = anna::functions::asString(hbh);
343         step = new TestStepWait(this);
344         a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
345       }
346     }
347   }
348
349   if (!step) step = new TestStepWait(this);
350   step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
351
352   LOGWARNING(
353     if (hasSameCondition(step->getCondition()))
354       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);
355   );
356
357   addStep(step);
358 }
359
360 void TestCase::addWaitRegexp(bool fromEntity, const std::string &regexp) throw(anna::RuntimeException) {
361   assertInitialized();
362
363   TestStepWait *step = new TestStepWait(this);
364   step->setCondition(fromEntity, regexp);
365
366   LOGWARNING(
367     if (hasSameCondition(step->getCondition()))
368       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);
369   );
370
371   addStep(step);
372 }
373
374 void TestCase::addCommand(const std::string &cmd) throw(anna::RuntimeException) {
375   assertInitialized();
376
377   TestStepCmd *step = new TestStepCmd(this);
378   step->setScript(cmd);
379
380   addStep(step);
381 }
382
383 TestStepWait *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) throw() {
384
385   TestStepWait *result;
386   for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
387     if ((*it)->getType() != TestStep::Type::Wait) continue;
388     if ((*it)->isCompleted()) continue;
389     result = (TestStepWait*)(*it);
390     if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
391       return result;
392   }
393
394   return NULL;
395 }
396
397 const TestStep *TestCase::getStep(int stepNumber) const throw() {
398   if (stepNumber < 1 || stepNumber > steps()) return NULL;
399 //  return a_steps.at(stepNumber-1);  // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
400   return a_steps[stepNumber-1];
401 }