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   std::string msg = "", xmlmsg = "";
165
166   // Message
167   if (TestManager::instantiate().getDumpHex()) {
168     if (a_message.isEmpty()) {
169       msg = "<empty>";
170     }
171     else {
172       msg = "\n"; msg += a_message.asString(); msg += "\n";
173     }
174   }
175
176   if (!a_message.isEmpty()) {
177     try {
178       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
179       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
180       codecMsg.decode(a_message);
181       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
182     }
183     catch (anna::RuntimeException &ex) {
184       ex.trace();
185     }
186   }
187
188   if (msg != "") result->createAttribute("Message", msg);
189   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
190   result->createAttribute("Expired", (a_expired ? "yes":"no"));
191   if (a_waitForRequestStepNumber != -1)
192     result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
193
194   return result;
195 }
196
197 bool TestStepSendxml::do_execute() throw() {
198   anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
199   bool success = false;
200   std::string failReason, s_warn;
201
202   try {
203     // Update sequence for answers:
204     if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
205       // Request which was received:
206       const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
207       const anna::DataBlock &request = tsw->getMsgDataBlock();
208       anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
209       anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
210       // Update sequence:
211       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
212       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
213
214       // Check Session-Id for warning ...
215       std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
216       std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
217       if (sessionIdRequest != sessionIdAnswer) {
218         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());
219         LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
220         a_testCase->addDebugSummaryHint(s_warn);
221       }
222     }
223
224     if (getType() == Type::Sendxml2e) {
225       MyDiameterEntity *entity = a_realmNode->getEntity();
226       if (entity) {
227         //msg->clearBody();
228         msg->setBody(a_message);
229         /* response = NULL =*/entity->send(msg);
230         success = true;
231       }
232       else {
233         failReason = "There is no diameter entity currently configured. Unable to send the message";
234         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
235       }
236     }
237     else if (getType() == Type::Sendxml2c) {
238       MyLocalServer *localServer = a_realmNode->getDiameterServer();
239       if (localServer) {
240         //msg->clearBody();
241         msg->setBody(a_message);
242         /* response = NULL =*/localServer->send(msg);
243         success = true;
244       }
245       else {
246         failReason = "There is no diameter local server currently configured. Unable to send the message";
247         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
248       }
249     }
250   } catch(anna::RuntimeException &ex) {
251     failReason = ex.asString();
252   }
253
254   // release msg
255   a_realmNode->releaseCommMessage(msg);
256
257   if (!success) {
258     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
259     a_testCase->setState(TestCase::State::Failed);
260   }
261   else {
262     complete();
263   }
264
265   return success; // go next if sent was OK
266 }
267
268 void TestStepSendxml::do_reset() throw() {
269   a_expired = false;
270   //a_message.clear();
271 }
272
273 ////////////////////////////////////////////////////////////////////////////////////////////////////////
274 // TestStepDelay
275 ////////////////////////////////////////////////////////////////////////////////////////////////////////
276 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
277 throw() {
278   anna::xml::Node* result = TestStep::asXML(parent);
279   //parent->createChild("TestStepDelay");
280
281   result->createAttribute("Delay", a_delay.asString());
282
283   return result;
284 }
285
286 bool TestStepDelay::do_execute() throw() {
287   try {
288     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
289   }
290   catch (anna::RuntimeException &ex) {
291     ex.trace();
292     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
293     a_testCase->setState(TestCase::State::Failed);
294   }
295
296   return false; // don't go next (wait complete)
297 }
298
299 void TestStepDelay::do_complete() throw() {
300   a_timer = NULL;
301   next(); // next() invoked here because execute() is always false for delay and never dvance the iterator
302 }
303
304 void TestStepDelay::do_reset() throw() {
305   try {
306     TestManager::instantiate().cancelTimer(a_timer);
307   }
308   catch (anna::RuntimeException &ex) {
309     ex.trace();
310   }
311   a_timer = NULL;
312   //a_delay = 0; THIS IS CONFIGURATION INFO
313 }
314
315 ////////////////////////////////////////////////////////////////////////////////////////////////////////
316 // TestStepWait
317 ////////////////////////////////////////////////////////////////////////////////////////////////////////
318 void TestStepWait::setCondition(bool fromEntity,
319                                   const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
320                                   const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
321
322   a_condition.setReceivedFromEntity(fromEntity);
323   a_condition.setCode(code);
324   a_condition.setBitR(bitR);
325   a_condition.setResultCode(resultCode);
326   a_condition.setSessionId(sessionId);
327   a_condition.setHopByHop(hopByHop);
328   a_condition.setMsisdn(msisdn);
329   a_condition.setImsi(imsi);
330   a_condition.setServiceContextId(serviceContextId);
331 }
332
333 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
334
335   a_condition.setReceivedFromEntity(fromEntity);
336   a_condition.setRegexp(regexp);
337 }
338
339 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
340 throw() {
341   anna::xml::Node* result = TestStep::asXML(parent);
342   //parent->createChild("TestStepWait");
343   std::string msg = "", xmlmsg = "";
344
345   // Condition
346   a_condition.asXML(result);
347
348   // Message
349   if (TestManager::instantiate().getDumpHex()) {
350     if (a_message.isEmpty()) {
351       msg = "<empty>";
352     }
353     else {
354       msg = "\n"; msg += a_message.asString(); msg += "\n";
355     }
356   }
357
358   if (!a_message.isEmpty()) {
359     try {
360       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
361       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
362       codecMsg.decode(a_message);
363       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
364     }
365     catch (anna::RuntimeException &ex) {
366       ex.trace();
367     }
368   }
369
370   if (msg != "") result->createAttribute("MatchedMessage", msg);
371   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
372
373   return result;
374 }
375
376 bool TestStepWait::do_execute() throw() {
377   return a_completed;
378 }
379
380 void TestStepWait::do_complete() throw() {
381   next(); // next() invoked here because execute() never do this.
382 }
383
384 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
385   if (a_condition.comply(db/*, matchSessionId*/)) {
386     a_message = db; // store matched
387     complete();
388     return true;
389   }
390
391   return false;
392 }
393
394 void TestStepWait::do_reset() throw() {
395   a_message.clear();
396   a_clientSession = NULL;
397   a_serverSession = NULL;
398 }
399