Command execution for system test cases
[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 #include <iostream>
12 #include <stdio.h>
13
14 // Project
15 #include <anna/xml/Compiler.hpp>
16 #include <anna/core/util/Millisecond.hpp>
17 #include <anna/diameter.comm/Message.hpp>
18 #include <anna/core/tracing/Logger.hpp>
19 #include <anna/diameter/codec/functions.hpp>
20 #include <anna/diameter/helpers/base/functions.hpp>
21
22 // Process
23 #include <RealmNode.hpp>
24 #include <MyDiameterEntity.hpp>
25 #include <MyLocalServer.hpp>
26 #include <TestStep.hpp>
27 #include <Launcher.hpp>
28 #include <TestCase.hpp>
29 #include <TestManager.hpp>
30 #include <TestTimer.hpp>
31
32
33 namespace {
34   void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
35     step->setThreadRunning(true);
36     int rc = system(cmd.c_str());
37     if (rc != -1) rc >>= 8; // divide by 256
38     step->setResultCode(rc);
39     step->complete();
40     // TODO: timeout the system call
41   }
42 }
43
44
45 ////////////////////////////////////////////////////////////////////////////////////////////////////////
46 // TestStep
47 ////////////////////////////////////////////////////////////////////////////////////////////////////////
48 void TestStep::initialize(TestCase *testCase) {
49   a_testCase = testCase;
50   a_completed = false;
51   a_type = Type::Unconfigured;
52   a_beginTimestamp = 0;
53   a_endTimestamp = 0;
54   a_number = testCase->steps() + 1; // testCase is not NULL
55 }
56
57 const char* TestStep::asText(const Type::_v type)
58 throw() {
59   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
60   return text [type];
61 }
62
63 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent) const
64 throw() {
65   anna::xml::Node* result = parent->createChild("TestStep");
66
67   result->createAttribute("Number", a_number);
68   result->createAttribute("Type", asText(a_type));
69   result->createAttribute("Completed", (a_completed ? "yes":"no"));
70
71   // Begin
72   std::string s_aux = a_beginTimestamp.asString();
73 //  int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
74 //  if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
75   result->createAttribute("BeginTimestamp", s_aux);
76
77   // End
78   s_aux = a_endTimestamp.asString();
79 //  deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
80 //  if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
81   result->createAttribute("EndTimestamp", s_aux);
82
83   return result;
84 }
85
86 std::string TestStep::asXMLString() const throw() {
87   anna::xml::Node root("root");
88   return anna::xml::Compiler().apply(asXML(&root));
89 }
90
91 bool TestStep::execute() throw() {
92   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));
93   setBeginTimestamp(anna::functions::millisecond());
94   return do_execute();
95 }
96
97 void TestStep::complete() throw() {
98   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));
99   a_completed = true;
100   setEndTimestamp(anna::functions::millisecond());
101   do_complete();
102 }
103
104 void TestStep::reset() throw() {
105   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));
106   // type and testCase kept
107   a_completed = false;
108   a_beginTimestamp = 0;
109   a_endTimestamp = 0;
110   do_reset();
111 }
112
113 void TestStep::next() throw() {
114   a_testCase->nextStep();
115   a_testCase->process();
116 }
117
118
119 ////////////////////////////////////////////////////////////////////////////////////////////////////////
120 // TestStepTimeout
121 ////////////////////////////////////////////////////////////////////////////////////////////////////////
122 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent) const
123 throw() {
124   anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
125   //parent->createChild("TestStepTimeout");
126   result->createAttribute("Timeout", a_timeout.asString());
127
128   return result;
129 }
130
131 bool TestStepTimeout::do_execute() throw() {
132   try {
133     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
134   }
135   catch (anna::RuntimeException &ex) {
136     ex.trace();
137     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
138     a_testCase->setState(TestCase::State::Failed);
139   }
140
141   return true; // go next
142 }
143
144 void TestStepTimeout::do_complete() throw() {
145   int stepNumber = getNumber();
146   if (stepNumber == a_testCase->steps()) {
147     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)
148     a_testCase->setState(TestCase::State::Success);
149   }
150   else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
151     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
152     a_testCase->setState(TestCase::State::Failed);
153   }
154
155   a_timer = NULL;
156 }
157
158 void TestStepTimeout::do_reset() throw() {
159   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));
160
161   try {
162     TestManager::instantiate().cancelTimer(a_timer);
163   }
164   catch (anna::RuntimeException &ex) {
165     ex.trace();
166   }
167   a_timer = NULL;
168   //a_timeout = 0; THIS IS CONFIGURATION INFO
169 }
170
171 ////////////////////////////////////////////////////////////////////////////////////////////////////////
172 // TestStepSendxml
173 ////////////////////////////////////////////////////////////////////////////////////////////////////////
174 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
175 throw() {
176   anna::xml::Node* result = TestStep::asXML(parent);
177   //parent->createChild("TestStepSendxml");
178   std::string msg = "", xmlmsg = "";
179
180   // Message
181   if (TestManager::instantiate().getDumpHex()) {
182     if (a_message.isEmpty()) {
183       msg = "<empty>";
184     }
185     else {
186       msg = "\n"; msg += a_message.asString(); msg += "\n";
187     }
188   }
189
190   if (!a_message.isEmpty()) {
191     try {
192       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
193       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
194       codecMsg.decode(a_message);
195       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
196     }
197     catch (anna::RuntimeException &ex) {
198       ex.trace();
199     }
200   }
201
202   if (msg != "") result->createAttribute("Message", msg);
203   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
204   result->createAttribute("Expired", (a_expired ? "yes":"no"));
205   if (a_waitForRequestStepNumber != -1)
206     result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
207
208   return result;
209 }
210
211 bool TestStepSendxml::do_execute() throw() {
212   anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
213   bool success = false;
214   std::string failReason, s_warn;
215
216   try {
217     // Update sequence for answers:
218     if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
219       // Request which was received:
220       const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
221       const anna::DataBlock &request = tsw->getMsgDataBlock();
222       anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
223       anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
224       // Update sequence:
225       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
226       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
227
228       // Check Session-Id for warning ...
229       std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
230       std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
231       if (sessionIdRequest != sessionIdAnswer) {
232         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());
233         LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
234         a_testCase->addDebugSummaryHint(s_warn);
235       }
236     }
237
238     if (getType() == Type::Sendxml2e) {
239       MyDiameterEntity *entity = a_realmNode->getEntity();
240       if (entity) {
241         //msg->clearBody();
242         msg->setBody(a_message);
243         /* response = NULL =*/entity->send(msg);
244         success = true;
245       }
246       else {
247         failReason = "There is no diameter entity currently configured. Unable to send the message";
248         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
249       }
250     }
251     else if (getType() == Type::Sendxml2c) {
252       MyLocalServer *localServer = a_realmNode->getDiameterServer();
253       if (localServer) {
254         //msg->clearBody();
255         msg->setBody(a_message);
256         /* response = NULL =*/localServer->send(msg);
257         success = true;
258       }
259       else {
260         failReason = "There is no diameter local server currently configured. Unable to send the message";
261         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
262       }
263     }
264   } catch(anna::RuntimeException &ex) {
265     failReason = ex.asString();
266   }
267
268   // release msg
269   a_realmNode->releaseCommMessage(msg);
270
271   if (!success) {
272     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
273     a_testCase->setState(TestCase::State::Failed);
274   }
275   else {
276     complete();
277   }
278
279   return success; // go next if sent was OK
280 }
281
282 void TestStepSendxml::do_reset() throw() {
283   a_expired = false;
284   //a_message.clear();
285 }
286
287 ////////////////////////////////////////////////////////////////////////////////////////////////////////
288 // TestStepDelay
289 ////////////////////////////////////////////////////////////////////////////////////////////////////////
290 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
291 throw() {
292   anna::xml::Node* result = TestStep::asXML(parent);
293   //parent->createChild("TestStepDelay");
294
295   result->createAttribute("Delay", a_delay.asString());
296
297   return result;
298 }
299
300 bool TestStepDelay::do_execute() throw() {
301   try {
302     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
303   }
304   catch (anna::RuntimeException &ex) {
305     ex.trace();
306     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
307     a_testCase->setState(TestCase::State::Failed);
308   }
309
310   return false; // don't go next (wait complete)
311 }
312
313 void TestStepDelay::do_complete() throw() {
314   a_timer = NULL;
315   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
316 }
317
318 void TestStepDelay::do_reset() throw() {
319   try {
320     TestManager::instantiate().cancelTimer(a_timer);
321   }
322   catch (anna::RuntimeException &ex) {
323     ex.trace();
324   }
325   a_timer = NULL;
326   //a_delay = 0; THIS IS CONFIGURATION INFO
327 }
328
329 ////////////////////////////////////////////////////////////////////////////////////////////////////////
330 // TestStepWait
331 ////////////////////////////////////////////////////////////////////////////////////////////////////////
332 void TestStepWait::setCondition(bool fromEntity,
333                                   const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
334                                   const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
335
336   a_condition.setReceivedFromEntity(fromEntity);
337   a_condition.setCode(code);
338   a_condition.setBitR(bitR);
339   a_condition.setResultCode(resultCode);
340   a_condition.setSessionId(sessionId);
341   a_condition.setHopByHop(hopByHop);
342   a_condition.setMsisdn(msisdn);
343   a_condition.setImsi(imsi);
344   a_condition.setServiceContextId(serviceContextId);
345 }
346
347 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
348
349   a_condition.setReceivedFromEntity(fromEntity);
350   a_condition.setRegexp(regexp);
351 }
352
353 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
354 throw() {
355   anna::xml::Node* result = TestStep::asXML(parent);
356   //parent->createChild("TestStepWait");
357   std::string msg = "", xmlmsg = "";
358
359   // Condition
360   a_condition.asXML(result);
361
362   // Message
363   if (TestManager::instantiate().getDumpHex()) {
364     if (a_message.isEmpty()) {
365       msg = "<empty>";
366     }
367     else {
368       msg = "\n"; msg += a_message.asString(); msg += "\n";
369     }
370   }
371
372   if (!a_message.isEmpty()) {
373     try {
374       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
375       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
376       codecMsg.decode(a_message);
377       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
378     }
379     catch (anna::RuntimeException &ex) {
380       ex.trace();
381     }
382   }
383
384   if (msg != "") result->createAttribute("MatchedMessage", msg);
385   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
386
387   return result;
388 }
389
390 bool TestStepWait::do_execute() throw() {
391   return a_completed;
392 }
393
394 void TestStepWait::do_complete() throw() {
395   a_testCase->process(); // next() not invoked; we only want to reactivate the test case
396 }
397
398 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
399   if (a_condition.comply(db/*, matchSessionId*/)) {
400     a_message = db; // store matched
401     complete();
402     return true;
403   }
404
405   return false;
406 }
407
408 void TestStepWait::do_reset() throw() {
409   a_message.clear();
410   a_clientSession = NULL;
411   a_serverSession = NULL;
412 }
413
414 ////////////////////////////////////////////////////////////////////////////////////////////////////////
415 // TestStepCmd
416 ////////////////////////////////////////////////////////////////////////////////////////////////////////
417 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent) const
418 throw() {
419   anna::xml::Node* result = TestStep::asXML(parent);
420   //parent->createChild("TestStepCmd");
421
422   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
423   result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
424   result->createAttribute("CommandInProgress", a_threadRunning ? "yes":"no");
425   if (!a_threadRunning && a_resultCode != -2) {
426     result->createAttribute("ResultCode", a_resultCode);
427     //if (a_output != "") result->createAttribute("Output", a_output);
428   }
429
430   return result;
431 }
432
433 bool TestStepCmd::do_execute() throw() {
434   if (!a_threadRunning) {
435     // Special tags to replace:
436     std::string cmd = getScript();
437     cmd += " ";
438     cmd += getParameters();
439     size_t index;
440     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
441       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
442     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
443       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
444     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
445       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
446
447     a_thread = std::thread(cmdRunOnThread, this, cmd);
448     a_thread.detach();
449   }
450
451   return false; // don't go next (wait complete)
452 }
453
454 void TestStepCmd::do_complete() throw() {
455
456   a_threadRunning = false;
457   if (a_threadDeprecated) {
458     a_threadDeprecated = false;
459     return; // ignore TODO: interrupt the thread to avoid execution of the script
460   }
461
462   if (getResultCode() != 0)
463     a_testCase->setState(TestCase::State::Failed);
464   else
465     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
466 }
467
468 void TestStepCmd::do_reset() throw() {
469
470   if (a_threadRunning) {
471     std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
472     LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
473     a_threadDeprecated = true;
474   }
475
476   a_resultCode = -2;
477   //a_output = "";
478 }
479