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