Fixes and improvs. Basic DRA feature.
[anna.git] / example / diameter / launcher / testing / TestStep.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
12 // Project
13 #include <anna/xml/Compiler.hpp>
14 #include <anna/core/util/Millisecond.hpp>
15 #include <anna/diameter.comm/Message.hpp>
16 #include <anna/core/tracing/Logger.hpp>
17 #include <anna/diameter/codec/functions.hpp>
18 #include <anna/diameter/helpers/base/functions.hpp>
19
20 // Process
21 #include <RealmNode.hpp>
22 #include <MyDiameterEntity.hpp>
23 #include <MyLocalServer.hpp>
24 #include <TestStep.hpp>
25 #include <Launcher.hpp>
26 #include <TestCase.hpp>
27 #include <TestManager.hpp>
28 #include <TestTimer.hpp>
29
30
31 ////////////////////////////////////////////////////////////////////////////////////////////////////////
32 // TestStep
33 ////////////////////////////////////////////////////////////////////////////////////////////////////////
34 void TestStep::initialize(TestCase *testCase) {
35   a_testCase = testCase;
36   a_completed = false;
37   a_type = Type::Unconfigured;
38   a_beginTimestamp = 0;
39   a_endTimestamp = 0;
40   a_number = testCase->steps() + 1; // testCase is not NULL
41 }
42
43 const char* TestStep::asText(const Type::_v type)
44 throw() {
45   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait" };
46   return text [type];
47 }
48
49 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent) const
50 throw() {
51   anna::xml::Node* result = parent->createChild("TestStep");
52
53   result->createAttribute("Number", a_number);
54   result->createAttribute("Type", asText(a_type));
55   result->createAttribute("Completed", (a_completed ? "yes":"no"));
56
57   // Begin
58   std::string s_aux = a_beginTimestamp.asString();
59 //  int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
60 //  if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
61   result->createAttribute("BeginTimestamp", s_aux);
62
63   // End
64   s_aux = a_endTimestamp.asString();
65 //  deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
66 //  if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
67   result->createAttribute("EndTimestamp", s_aux);
68
69   return result;
70 }
71
72 std::string TestStep::asXMLString() const throw() {
73   anna::xml::Node root("root");
74   return anna::xml::Compiler().apply(asXML(&root));
75 }
76
77 bool TestStep::execute() throw() {
78   LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
79   setBeginTimestamp(anna::functions::millisecond());
80   return do_execute();
81 }
82
83 void TestStep::complete() throw() {
84   LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
85   a_completed = true;
86   setEndTimestamp(anna::functions::millisecond());
87   do_complete();
88 }
89
90 void TestStep::reset() throw() {
91   LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
92   // type and testCase kept
93   a_completed = false;
94   a_beginTimestamp = 0;
95   a_endTimestamp = 0;
96   do_reset();
97 }
98
99 void TestStep::next() throw() {
100   a_testCase->nextStep();
101   a_testCase->process();
102 }
103
104
105 ////////////////////////////////////////////////////////////////////////////////////////////////////////
106 // TestStepTimeout
107 ////////////////////////////////////////////////////////////////////////////////////////////////////////
108 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent) const
109 throw() {
110   anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
111   //parent->createChild("TestStepTimeout");
112   result->createAttribute("Timeout", a_timeout.asString());
113
114   return result;
115 }
116
117 bool TestStepTimeout::do_execute() throw() {
118   try {
119     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
120   }
121   catch (anna::RuntimeException &ex) {
122     ex.trace();
123     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
124     a_testCase->setState(TestCase::State::Failed);
125   }
126
127   return true; // go next
128 }
129
130 void TestStepTimeout::do_complete() throw() {
131   int stepNumber = getNumber();
132   if (stepNumber == a_testCase->steps()) {
133     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) but it was the last test case step", stepNumber)); // before report (when set Failed state)
134     a_testCase->setState(TestCase::State::Success);
135   }
136   else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
137     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
138     a_testCase->setState(TestCase::State::Failed);
139   }
140
141   a_timer = NULL;
142 }
143
144 void TestStepTimeout::do_reset() throw() {
145   LOGDEBUG(anna::Logger::debug(anna::functions::asString("REXXXXXET %s for Test Case %llu (%p) (%p) (a_timer %p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this, a_timer), ANNA_FILE_LOCATION));
146
147   try {
148     TestManager::instantiate().cancelTimer(a_timer);
149   }
150   catch (anna::RuntimeException &ex) {
151     ex.trace();
152   }
153   a_timer = NULL;
154   //a_timeout = 0; THIS IS CONFIGURATION INFO
155 }
156
157 ////////////////////////////////////////////////////////////////////////////////////////////////////////
158 // TestStepSendxml
159 ////////////////////////////////////////////////////////////////////////////////////////////////////////
160 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
161 throw() {
162   anna::xml::Node* result = TestStep::asXML(parent);
163   //parent->createChild("TestStepSendxml");
164
165   // Message
166   std::string msg = "", xmlmsg = "";
167   if (a_message.isEmpty()) {
168     msg = "<empty>";
169   }
170   else {
171     msg = "\n"; msg += a_message.asString(); msg += "\n";
172     // Helper
173     try {
174       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
175       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
176       codecMsg.decode(a_message);
177       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
178     }
179     catch (anna::RuntimeException &ex) {
180       ex.trace();
181     }
182   }
183
184   result->createAttribute("Message", msg);
185   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
186   result->createAttribute("Expired", (a_expired ? "yes":"no"));
187
188   return result;
189 }
190
191 bool TestStepSendxml::do_execute() throw() {
192   anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
193   bool success = false;
194   std::string failReason, s_warn;
195
196   try {
197     // Update sequence for answers:
198     if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
199       // Request which was received:
200       const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
201       const anna::DataBlock &request = tsw->getMsgDataBlock();
202       anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
203       anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
204       // Update sequence:
205       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
206       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
207
208       // Check Session-Id for warning ...
209       std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
210       std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
211       if (sessionIdRequest != sessionIdAnswer) {
212         s_warn = anna::functions::asString("Sending an answer which Session-Id (%s) is different than supposed corresponding request (%s)", sessionIdAnswer.c_str(), sessionIdRequest.c_str());
213         LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
214         a_testCase->addDebugSummaryHint(s_warn);
215       }
216     }
217
218     if (getType() == Type::Sendxml2e) {
219       MyDiameterEntity *entity = a_realmNode->getEntity();
220       if (entity) {
221         //msg->clearBody();
222         msg->setBody(a_message);
223         /* response = NULL =*/entity->send(msg);
224         success = true;
225       }
226       else {
227         failReason = "There is no diameter entity currently configured. Unable to send the message";
228         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
229       }
230     }
231     else if (getType() == Type::Sendxml2c) {
232       MyLocalServer *localServer = a_realmNode->getDiameterServer();
233       if (localServer) {
234         //msg->clearBody();
235         msg->setBody(a_message);
236         /* response = NULL =*/localServer->send(msg);
237         success = true;
238       }
239       else {
240         failReason = "There is no diameter local server currently configured. Unable to send the message";
241         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
242       }
243     }
244   } catch(anna::RuntimeException &ex) {
245     failReason = ex.asString();
246   }
247
248   // release msg
249   a_realmNode->releaseCommMessage(msg);
250
251   if (!success) {
252     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
253     a_testCase->setState(TestCase::State::Failed);
254   }
255   else {
256     complete();
257   }
258
259   return success; // go next if sent was OK
260 }
261
262 void TestStepSendxml::do_reset() throw() {
263   a_expired = false;
264   //a_message.clear();
265 }
266
267 ////////////////////////////////////////////////////////////////////////////////////////////////////////
268 // TestStepDelay
269 ////////////////////////////////////////////////////////////////////////////////////////////////////////
270 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
271 throw() {
272   anna::xml::Node* result = TestStep::asXML(parent);
273   //parent->createChild("TestStepDelay");
274
275   result->createAttribute("Delay", a_delay.asString());
276
277   return result;
278 }
279
280 bool TestStepDelay::do_execute() throw() {
281   try {
282     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
283   }
284   catch (anna::RuntimeException &ex) {
285     ex.trace();
286     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
287     a_testCase->setState(TestCase::State::Failed);
288   }
289
290   return false; // don't go next (wait complete)
291 }
292
293 void TestStepDelay::do_complete() throw() {
294   a_timer = NULL;
295   next(); // next() invoked here because execute() is always false for delay and never dvance the iterator
296 }
297
298 void TestStepDelay::do_reset() throw() {
299   try {
300     TestManager::instantiate().cancelTimer(a_timer);
301   }
302   catch (anna::RuntimeException &ex) {
303     ex.trace();
304   }
305   a_timer = NULL;
306   //a_delay = 0; THIS IS CONFIGURATION INFO
307 }
308
309 ////////////////////////////////////////////////////////////////////////////////////////////////////////
310 // TestStepWait
311 ////////////////////////////////////////////////////////////////////////////////////////////////////////
312 void TestStepWait::setCondition(bool fromEntity,
313                                   const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
314                                   const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
315
316   a_condition.setReceivedFromEntity(fromEntity);
317   a_condition.setCode(code);
318   a_condition.setBitR(bitR);
319   a_condition.setResultCode(resultCode);
320   a_condition.setSessionId(sessionId);
321   a_condition.setHopByHop(hopByHop);
322   a_condition.setMsisdn(msisdn);
323   a_condition.setImsi(imsi);
324   a_condition.setServiceContextId(serviceContextId);
325 }
326
327 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
328
329   a_condition.setReceivedFromEntity(fromEntity);
330   a_condition.setRegexp(regexp);
331 }
332
333 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
334 throw() {
335   anna::xml::Node* result = TestStep::asXML(parent);
336   //parent->createChild("TestStepWait");
337
338   // Condition
339   a_condition.asXML(result);
340
341   if (!a_message.isEmpty()) {
342     // Message
343     result->createAttribute("MatchedMessage", a_message.asString());
344     // Helper
345     try {
346       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
347       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
348       codecMsg.decode(a_message);
349       result->createAttribute("MatchedXMLMessage", codecMsg.asXMLString());
350     }
351     catch (anna::RuntimeException &ex) {
352       ex.trace();
353     }
354   }
355
356   return result;
357 }
358
359 bool TestStepWait::do_execute() throw() {
360   return a_completed;
361 }
362
363 void TestStepWait::do_complete() throw() {
364   next(); // next() invoked here because execute() never do this.
365 }
366
367 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
368   if (a_condition.comply(db/*, matchSessionId*/)) {
369     a_message = db; // store matched
370     complete();
371     return true;
372   }
373
374   return false;
375 }
376
377 void TestStepWait::do_reset() throw() {
378   a_message.clear();
379   a_clientSession = NULL;
380   a_serverSession = NULL;
381 }
382