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