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