1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
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 //
13 #include <anna/testing/TestManager.hpp>
15 #include <anna/xml/Compiler.hpp>
16 #include <anna/xml/Node.hpp>
17 #include <anna/core/tracing/Logger.hpp>
18 #include <anna/app/functions.hpp>
19 #include <anna/timex/Engine.hpp>
20 #include <anna/diameter/helpers/base/functions.hpp>
21 #include <anna/diameter/helpers/dcca/functions.hpp>
22 #include <anna/comm/functions.hpp>
23 #include <anna/diameter.comm/ClientSession.hpp>
24 #include <anna/diameter.comm/ServerSession.hpp>
25 #include <anna/testing/TestStep.hpp>
26 #include <anna/testing/TestClock.hpp>
27 #include <anna/diameter/codec/Message.hpp>
33 using namespace anna::testing;
36 ///////////////////////////////////////////////////////////////////////////////////////////////////
37 void TestManager::StatSummary::newTCState(const TestCase::State::_v beginState, const TestCase::State::_v endState) throw() {
39 if ((beginState == TestCase::State::Initialized)&&(endState == TestCase::State::Initialized)) { // special case (new test case provisioning)
45 case TestCase::State::Initialized: a_initializedTcs--; break;
46 case TestCase::State::InProgress: a_inprogressTcs--; break;
47 case TestCase::State::Failed: a_failedTcs--; break;
48 case TestCase::State::Success: a_sucessTcs--; break;
52 case TestCase::State::Initialized: a_initializedTcs++; break;
53 case TestCase::State::InProgress: a_inprogressTcs++; break;
54 case TestCase::State::Failed: a_failedTcs++; break;
55 case TestCase::State::Success: a_sucessTcs++; break;
60 void TestManager::StatSummary::clear() throw() {
67 anna::xml::Node *TestManager::StatSummary::asXML(anna::xml::Node* parent) const throw() {
68 anna::xml::Node* result = parent->createChild("StatSummary");
70 anna::xml::Node* tcs = result->createChild("TestCasesCounts");
71 tcs->createAttribute("Total", a_initializedTcs + a_inprogressTcs + a_failedTcs + a_sucessTcs);
72 tcs->createAttribute("Initialized", a_initializedTcs);
73 tcs->createAttribute("InProgress", a_inprogressTcs);
74 tcs->createAttribute("Failed", a_failedTcs);
75 tcs->createAttribute("Success", a_sucessTcs);
79 ///////////////////////////////////////////////////////////////////////////////////////////////////
83 TestManager::TestManager() :
84 anna::timex::TimeEventObserver("TestManager") {
85 a_timeController = NULL;
86 a_reportsDirectory = "./";
88 a_dumpInProgressReports = false;
89 a_dumpInitializedReports = false;
90 a_dumpFailedReports = false;
91 a_dumpSuccessReports = false;
93 a_dumpHexMessages = false;
94 a_synchronousAmount = 1;
95 a_poolRepeats = 0; // repeat disabled by default
97 a_inProgressLimit = UINT_MAX; // no limit
100 //a_statSummary.clear();
101 a_currentTestIt = a_testPool.end();
104 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
106 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
107 if (it != a_sessionIdTestCaseMap.end()) { // found
108 unsigned int id = it->second->getId();
109 if (id != testCase->getId()) {
110 throw anna::RuntimeException(anna::functions::asString("There is another test case (id = %llu) which registered such sessionId: %s", id, sessionId.c_str()), ANNA_FILE_LOCATION);
114 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
115 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager::registerSessionId for test case (id = %llu): %s)", testCase->getId(), sessionId.c_str()), ANNA_FILE_LOCATION));
119 void TestManager::registerSubscriberId(const std::string &subscriberId, const TestCase *testCase) throw(anna::RuntimeException) {
121 std::map<std::string /* subscriber id's */, TestCase*>::const_iterator it = a_subscriberIdTestCaseMap.find(subscriberId);
122 if (it != a_subscriberIdTestCaseMap.end()) { // found
123 unsigned int id = it->second->getId();
124 if (id != testCase->getId()) {
125 throw anna::RuntimeException(anna::functions::asString("There is another test case (id = %llu) which registered such subscriberId: %s", id, subscriberId.c_str()), ANNA_FILE_LOCATION);
129 a_subscriberIdTestCaseMap[subscriberId] = const_cast<TestCase*>(testCase);
130 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager::registerSubscriberId for test case (id = %llu): %s)", testCase->getId(), subscriberId.c_str()), ANNA_FILE_LOCATION));
134 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
135 throw(anna::RuntimeException) {
136 TestTimer* result(NULL);
138 if(a_timeController == NULL)
139 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
141 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
142 result = a_timers.create();
143 result->setType(type);
144 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
145 result->setObserver(this);
146 result->setContext(testCaseStep);
147 result->setTimeout(timeout);
150 std::string msg("TestManager::createTimer | ");
151 msg += result->asString();
152 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
155 a_timeController->activate(result);
159 void TestManager::cancelTimer(TestTimer* timer)
165 std::string msg("TestManager::cancel | ");
166 msg += timer->asString();
167 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
171 if(a_timeController == NULL)
172 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
174 a_timeController->cancel(timer);
175 } catch(anna::RuntimeException& ex) {
180 //------------------------------------------------------------------------------------------
181 // Se invoca automaticamente desde anna::timex::Engine
182 //------------------------------------------------------------------------------------------
183 void TestManager::release(anna::timex::TimeEvent* timeEvent)
185 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
186 timer->setContext(NULL);
187 a_timers.release(timer);
190 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
192 if (testTicksPerSecond == 0) {
194 a_timeController->cancel(a_clock);
195 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
198 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
202 else if (testTicksPerSecond < 0) {
203 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
207 anna::Millisecond applicationTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
208 a_synchronousAmount = 1;
210 if (applicationTimeInterval < anna::Millisecond(1)) {
211 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
215 if (applicationTimeInterval < a_timeController->getResolution()) {
216 int maximumObtained = 1000 / (int)(a_timeController->getResolution());
217 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
219 applicationTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
222 if (a_synchronousAmount > 1) {
224 std::string msg = anna::functions::asString("Desired testing time trigger rate (%d events per second) requires more than one sending per event (%d every %lld milliseconds). Consider launch more instances with lower rate (for example %d ADML processes with %d ttps), or configure %d or more sockets to the remote endpoints to avoid burst sendings",
227 applicationTimeInterval.getValue(),
229 1000/applicationTimeInterval,
230 a_synchronousAmount);
232 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
237 a_clock->setTimeout(applicationTimeInterval);
240 a_clock = new TestClock("Testing clock", applicationTimeInterval, this); // clock
243 if (!a_clock->isActive()) a_timeController->activate(a_clock);
248 bool TestManager::gotoTestCase(unsigned int id) throw() {
249 test_pool_it it = a_testPool.find(id);
250 if (it != a_testPool.end()) {
251 a_currentTestIt = it;
258 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
260 if (!tests()) return NULL;
261 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
262 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
266 TestCase *TestManager::getTestCase(unsigned int id) throw() {
268 test_pool_nc_it it = a_testPool.find(id);
269 if (it != a_testPool.end()) return it->second;
271 TestCase *result = new TestCase(id);
272 a_testPool[id] = result;
276 bool TestManager::clearPool() throw() {
277 if (!tests()) return false;
278 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
279 // TODO: stop the possible command threads or there will be a core dump
282 a_sessionIdTestCaseMap.clear();
283 a_subscriberIdTestCaseMap.clear();
284 a_currentTestIt = a_testPool.end();
286 configureTTPS(0); // stop
287 a_statSummary.clear();
291 bool TestManager::resetPool(bool hard) throw() {
292 bool result = false; // any reset
294 if (!tests()) return result;
295 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
296 if (it->second->reset(hard))
299 //a_sessionIdTestCaseMap.clear();
300 //a_subscriberIdTestCaseMap.clear();
304 bool TestManager::tick() throw() {
305 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
306 return execTestCases(a_synchronousAmount);
309 bool TestManager::execTestCases(int sync_amount) throw() {
312 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming", ANNA_FILE_LOCATION));
316 // Synchronous sendings per tick:
317 int count = sync_amount;
319 if (!nextTestCase()) return false; // stop the clock
326 bool TestManager::nextTestCase() throw() {
330 // Limit for in-progress test cases:
331 if (getInProgressCount() >= a_inProgressLimit) {
332 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
333 return true; // wait next tick to release OTA test cases
337 if (a_currentTestIt == a_testPool.end())
338 a_currentTestIt = a_testPool.begin();
343 if (a_currentTestIt == a_testPool.end()) {
344 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
345 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
351 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
352 anna::Logger::warning(anna::functions::asString("Testing pool cycle %d completed (repeats configured: %d%s). Restarting for the %s cycle", a_poolCycle, a_poolRepeats, nolimit.c_str(), (a_poolRepeats == a_poolCycle) ? "last":"next"), ANNA_FILE_LOCATION);
355 //a_currentTestIt = a_testPool.begin();
356 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
357 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
361 // Soft reset to initialize already finished (in previous cycle) test cases:
362 a_currentTestIt->second->reset(false);
364 // Process test case:
365 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Processing test case id = %llu, currently '%s' state", a_currentTestIt->first, TestCase::asText(a_currentTestIt->second->getState())), ANNA_FILE_LOCATION));
366 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
367 a_currentTestIt->second->process();
368 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
369 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
370 // forget to programm a test case timeout with a reasonable value
375 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
377 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
379 catch (anna::RuntimeException &ex) {
381 LOGDEBUG(anna::Logger::debug("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
384 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
385 if (sessionIdIt != a_sessionIdTestCaseMap.end())
386 return sessionIdIt->second;
388 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
392 TestCase *TestManager::getTestCaseFromSubscriberId(const anna::DataBlock &message, std::string &subscriberId) throw() {
394 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(message, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
395 if (subscriberId == "") // try with IMSI
396 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(message, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
398 catch (anna::RuntimeException &ex) {
400 LOGDEBUG(anna::Logger::debug("Cannot get the Subscriber-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
403 std::map<std::string /* subscriber id's */, TestCase*>::const_iterator subscriberIdIt = a_subscriberIdTestCaseMap.find(subscriberId);
404 if (subscriberIdIt != a_subscriberIdTestCaseMap.end())
405 return subscriberIdIt->second;
407 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Cannot identify the Test Case for received Subscriber-Id: %s", subscriberId.c_str()), ANNA_FILE_LOCATION));
411 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
414 if (!tests()) return;
416 // Identify the test case:
417 std::string sessionId, subscriberId;
419 tc = getTestCaseFromSessionId(message, sessionId);
421 tc = getTestCaseFromSubscriberId(message, subscriberId);
423 LOGWARNING(anna::Logger::warning(anna::comm::functions::asText("Cannot identify the Test Case for the message received from server: ", message), ANNA_FILE_LOCATION)); // this should not appear
427 // Work with Test case:
428 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
429 if (!tsw) { // store as 'uncovered'
430 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "'; ";
433 static anna::diameter::codec::Message codecMsg;
434 codecMsg.decode(message);
435 hint += "HEX Message: '"; hint += anna::functions::asHexString(message);
436 hint += "'; XML Message:\n"; hint += codecMsg.asXMLString();
438 catch (anna::RuntimeException &ex) {
440 hint += ex.asString();
442 hint += "\nClient Session: "; hint += clientSession->asString();
444 tc->addDebugSummaryHint(hint);
447 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
452 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
455 if (!tests()) return;
457 // Identify the test case:
458 std::string sessionId, subscriberId;
460 tc = getTestCaseFromSessionId(message, sessionId);
462 tc = getTestCaseFromSubscriberId(message, subscriberId);
464 LOGWARNING(anna::Logger::warning(anna::comm::functions::asText("Cannot identify the Test Case for the message received from client: ", message), ANNA_FILE_LOCATION)); // this should not appear
468 // Work with Test case:
469 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
470 if (!tsw) { // store as 'uncovered'
471 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "'; ";
474 static anna::diameter::codec::Message codecMsg;
475 codecMsg.decode(message);
476 hint += "HEX Message: '"; hint += anna::functions::asHexString(message);
477 hint += "'; XML Message:\n"; hint += codecMsg.asXMLString();
479 catch (anna::RuntimeException &ex) {
481 hint += ex.asString();
483 hint += "\nServer Session: "; hint += serverSession->asString();
485 tc->addDebugSummaryHint(hint);
488 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
493 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
495 anna::xml::Node* result = parent->createChild("TestManager");
497 int poolSize = a_testPool.size();
498 result->createAttribute("NumberOfTestCases", poolSize);
499 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
500 else result->createAttribute("PoolRepeats", "disabled");
501 result->createAttribute("PoolCycle", a_poolCycle);
502 a_statSummary.asXML(result);
503 if (a_inProgressLimit == UINT_MAX)
504 result->createAttribute("InProgressLimit", "<no limit>");
506 result->createAttribute("InProgressLimit", a_inProgressLimit);
507 result->createAttribute("DumpInitializedReports", (a_dumpInitializedReports ? "yes":"no"));
508 result->createAttribute("DumpInProgressReports", (a_dumpInProgressReports ? "yes":"no"));
509 result->createAttribute("DumpFailedReports", (a_dumpFailedReports ? "yes":"no"));
510 result->createAttribute("DumpSuccessReports", (a_dumpSuccessReports ? "yes":"no"));
511 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
512 result->createAttribute("ReportsDirectory", a_reportsDirectory);
514 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
515 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
516 result->createAttribute("TicksPerSecond", ticksPerSecond);
518 if (a_currentTestIt != a_testPool.end()) {
519 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
522 anna::xml::Node* testCases = result->createChild("TestCases");
523 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
524 if (((*it).second->getState() == TestCase::State::Initialized) && (!getDumpInitializedReports())) continue;
525 if (((*it).second->getState() == TestCase::State::InProgress) && (!getDumpInProgressReports())) continue;
526 if (((*it).second->getState() == TestCase::State::Failed) && (!getDumpFailedReports())) continue;
527 if (((*it).second->getState() == TestCase::State::Success) && (!getDumpSuccessReports())) continue;
528 (*it).second->asXML(testCases);
535 std::string TestManager::asXMLString() const throw() {
536 anna::xml::Node root("root");
537 return anna::xml::Compiler().apply(asXML(&root));