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 //
17 #include <anna/testing/TestCase.hpp>
18 #include <anna/testing/TestStep.hpp>
20 #include <anna/xml/Compiler.hpp>
21 #include <anna/diameter/defines.hpp>
22 #include <anna/diameter/helpers/dcca/defines.hpp>
23 #include <anna/diameter/codec/functions.hpp>
24 #include <anna/diameter.comm/OriginHost.hpp>
25 #include <anna/diameter/helpers/base/functions.hpp>
26 #include <anna/diameter/helpers/dcca/functions.hpp>
27 #include <anna/core/util/Millisecond.hpp>
28 #include <anna/core/tracing/Logger.hpp>
29 #include <anna/testing/TestManager.hpp>
32 using namespace anna::testing;
35 ///////////////////////////////////////////////////////////////////////////////////////////////////
36 void TestCase::DebugSummary::addHint(const std::string &hint) throw() {
38 event.Timestamp = anna::functions::millisecond();
40 a_events.push_back(event);
43 void TestCase::DebugSummary::clear() throw() {
47 anna::xml::Node* TestCase::DebugSummary::asXML(anna::xml::Node* parent) const throw() {
48 anna::xml::Node* result = parent->createChild("DebugSummary");
50 std::vector<event_t>::const_iterator it;
51 for (it = a_events.begin(); it != a_events.end(); it++) {
52 anna::xml::Node* event = result->createChild("Event");
53 event->createAttribute("Timestamp", (*it).Timestamp.asString());
54 event->createAttribute("Hint", (*it).Hint);
59 ///////////////////////////////////////////////////////////////////////////////////////////////////
62 TestCase::TestCase(unsigned int id) :
64 a_state(State::Initialized),
66 a_interactiveAmount(-1) {
68 /*a_stepsIt = a_steps.end()*/;
69 TestManager &testManager = TestManager::instantiate();
70 testManager.tcsStateStats(State::Initialized, State::Initialized);
73 TestCase::~TestCase() {
74 reset(true); // hard reset
75 std::vector<TestStep*>::const_iterator it;
76 for (it = a_steps.begin(); it != a_steps.end(); it++) delete (*it);
79 const char* TestCase::asText(const State::_v state)
81 static const char* text [] = { "Initialized", "InProgress", "Failed", "Success" };
85 anna::xml::Node* TestCase::asXML(anna::xml::Node* parent) const
87 anna::xml::Node* result = parent->createChild("TestCase");
89 result->createAttribute("Id", a_id);
90 result->createAttribute("State", asText(a_state));
91 result->createAttribute("StartTimestamp", a_startTime.asString());
92 int steps = a_steps.size();
94 result->createAttribute("NumberOfTestSteps", steps);
95 std::vector<TestStep*>::const_iterator it;
96 for (it = a_steps.begin(); it != a_steps.end(); it++) {
101 if (a_debugSummary.events()) {
102 a_debugSummary.asXML(result);
105 result->createAttribute("Interactive", (a_interactiveAmount != -1) ? "yes":"no");
110 std::string TestCase::asXMLString() const throw() {
111 anna::xml::Node root("root");
112 return anna::xml::Compiler().apply(asXML(&root));
115 bool TestCase::hasSameCondition(const TestCondition &condition) const throw() {
116 std::vector<TestStep*>::const_iterator it;
118 for (it = a_steps.begin(); it != a_steps.end(); it++) {
119 if ((*it)->getType() != TestStep::Type::Wait) continue;
120 step = (TestStepWait *)(*it);
121 if (step->getCondition() == condition) return true;
127 void TestCase::setState(const State::_v &state) throw() {
129 State::_v previousState = a_state;
130 if (state == previousState) return;
132 TestManager &testManager = TestManager::instantiate();
135 testManager.tcsStateStats(previousState, state);
139 if ((getState() == State::Failed) && (!testManager.getDumpFailedReports())) return;
140 if ((getState() == State::Success) && (!testManager.getDumpSuccessReports())) return;
141 // report file name: cycle-<cycle id>.testcase-<test case id>.xml
143 // FORMAT: We tabulate the cycle and test case in order to ease ordering of files by mean ls:
144 int cycles = testManager.getPoolRepeats();
145 int tests = testManager.tests();
146 int cyclesWidth = (cycles<=0) ? 3 /* 1000 cycles !! */: ((int) log10 ((double) cycles) + 1);
147 int testsWidth = (tests<=0) ? 9 /* subscribers */: ((int) log10 ((double) tests) + 1);
148 std::stringstream format;
149 format << "/cycle-%0" << cyclesWidth << "d.testcase-%0" << testsWidth << "llu.xml";
152 std::string file = testManager.getReportsDirectory() + anna::functions::asString(format.str().c_str(), testManager.getPoolCycle(), a_id);
154 out.open(file.c_str(), std::ofstream::out | std::ofstream::app);
155 if(out.is_open() == false) {
156 std::string msg("Error opening '");
158 msg += "' for writting";
159 anna::Logger::error(msg, ANNA_FILE_LOCATION);
162 out << asXMLString() << std::endl;
168 bool TestCase::done() throw() {
169 if (a_stepsIt == a_steps.end()) {
170 setState(State::Success);
177 bool TestCase::process() throw() {
179 LOGWARNING(anna::Logger::warning(anna::functions::asString("Test case %llu is empty, nothing to execute", a_id), ANNA_FILE_LOCATION));
183 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Test case %llu is finished, nothing done until soft-reset", a_id), ANNA_FILE_LOCATION));
187 if (a_state == State::Initialized) {
188 a_stepsIt = a_steps.begin();
189 setState(State::InProgress);
191 // For 'wait' steps (not really useful, but better than nothing: begin timestamp on test case start timestamp...):
192 a_startTime = anna::functions::millisecond();
195 // Check end of the test case:
196 if (done()) return false;
198 bool somethingDone = false;
199 while ((*a_stepsIt)->execute()) { // executes returns 'true' if the next step must be also executed (execute until can't stand no more)
201 // Check end of the test case:
202 if (done()) return false;
203 somethingDone = true;
206 return somethingDone;
209 bool TestCase::reset(bool hard) throw() {
211 // Soft reset if finished:
212 if (!hard /* is soft reset */ && !isFinished()) return false;
214 // Dump as failed if still in progress (hard reset):
215 if (getState() == State::InProgress) {
216 addDebugSummaryHint("Testcase hard reset while in progress");
217 setState(State::Failed);
220 // Clean stage ////////////////////////////
222 std::vector<TestStep*>::iterator it;
223 for (it = a_steps.begin(); it != a_steps.end(); it++)
226 a_debugSummary.clear();
228 a_interactiveAmount = -1;
230 setState(State::Initialized);
235 void TestCase::assertInitialized() const throw(anna::RuntimeException) {
237 throw anna::RuntimeException(anna::functions::asString("Cannot program anymore. The test case %llu has finished. You must reset it to append new steps (or do it during execution, which is also allowed).", a_id), ANNA_FILE_LOCATION);
240 void TestCase::assertMessage(const anna::DataBlock &db, bool toEntity) throw(anna::RuntimeException) {
242 bool isRequest = anna::diameter::codec::functions::isRequest(db);
243 bool registerKeys = ((isRequest && toEntity) || (!isRequest && !toEntity) /* (*) */);
244 // (*) we register answers Session-Id "assuming" that we will know the Session-Id values created by the client.
245 // This is another solution regarding diameter server testing. No sure about the final implementation.
246 // We will help registering also subscriber data, because certain messages (i.e. SLR) coming from clients could
247 // have specific Session-Id value (unknown at test programming), and normally are identified by subscriber.
251 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
252 if (a_hopByHops.find(hbh) != a_hopByHops.end())
253 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);
254 a_hopByHops[hbh] = NULL; // may be assigned to a wait condition
258 TestManager &testManager = TestManager::instantiate();
259 testManager.registerKey1(anna::diameter::helpers::base::functions::getSessionId(db), this);
262 std::string subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
263 if (subscriberId == "") // try with IMSI
264 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
266 if (subscriberId != "")
267 testManager.registerKey2(subscriberId, this);
271 void TestCase::addTimeout(const anna::Millisecond &timeout) throw(anna::RuntimeException) {
273 TestStepTimeout *step = new TestStepTimeout(this);
274 step->setTimeout(timeout);
278 void TestCase::addSendxml2e(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
280 assertMessage(db, true /* to entity */);
282 if (stepNumber != -1) {
283 const TestStep *stepReferred = getStep(stepNumber);
285 throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
287 if (stepReferred->getType() != TestStep::Type::Wait)
288 throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
290 const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
291 if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
292 throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait for request' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
296 TestStepSendxml2e *step = new TestStepSendxml2e(this);
297 step->setMsgDataBlock(db);
298 step->setOriginHost(host);
299 step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
303 void TestCase::addSendxml2c(const anna::DataBlock &db, anna::diameter::comm::OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
305 assertMessage(db, false /* to client */);
307 if (stepNumber != -1) {
308 const TestStep *stepReferred = getStep(stepNumber);
310 throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
312 if (stepReferred->getType() != TestStep::Type::Wait)
313 throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
315 const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
316 if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
317 throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait for request' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
321 TestStepSendxml2c *step = new TestStepSendxml2c(this);
322 step->setMsgDataBlock(db);
323 step->setOriginHost(host);
324 step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
328 void TestCase::addDelay(const anna::Millisecond &delay) throw(anna::RuntimeException) {
330 TestStepDelay *step = new TestStepDelay(this);
331 step->setDelay(delay);
335 void TestCase::addWait(bool fromEntity,
336 const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
337 const std::string &sessionId, const std::string &resultCode,
338 const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw(anna::RuntimeException) {
340 std::string usedHopByHop = hopByHop;
341 TestStepWait *step = NULL;
343 // Check basic conditions:
345 if (resultCode != "")
346 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);
348 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);
351 if (hopByHop != "") {
352 if (hopByHop[0] == '#') {
354 throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu)", a_id), ANNA_FILE_LOCATION);
356 int stepNumber = atoi(hopByHop.substr(1).c_str());
358 const TestStep *stepReferred = getStep(stepNumber);
360 throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
362 if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
363 throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu)", a_id), ANNA_FILE_LOCATION);
365 const anna::DataBlock &db = (static_cast<const TestStepSendxml*>(stepReferred))->getMsgDataBlock();
366 bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
368 throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu)", a_id), ANNA_FILE_LOCATION);
371 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
372 usedHopByHop = anna::functions::asString(hbh);
373 step = new TestStepWait(this);
374 a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
379 if (!step) step = new TestStepWait(this);
380 step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
383 if (hasSameCondition(step->getCondition()))
384 anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
390 void TestCase::addWaitRegexpHex(bool fromEntity, const std::string ®exp) throw(anna::RuntimeException) {
393 TestStepWait *step = new TestStepWait(this);
394 step->setConditionRegexpHex(fromEntity, regexp);
397 if (hasSameCondition(step->getCondition()))
398 anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
404 void TestCase::addWaitRegexpXml(bool fromEntity, const std::string ®exp) throw(anna::RuntimeException) {
407 TestStepWait *step = new TestStepWait(this);
408 step->setConditionRegexpXml(fromEntity, regexp);
411 if (hasSameCondition(step->getCondition()))
412 anna::Logger::information(anna::functions::asString("The same wait condition has already been programmed in this test case (%llu). Are you sure ?", a_id), ANNA_FILE_LOCATION);
418 void TestCase::addCommand(const std::string &cmd) throw(anna::RuntimeException) {
421 TestStepCmd *step = new TestStepCmd(this);
422 step->setScript(cmd);
427 TestStepWait *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) throw() {
429 TestStepWait *result;
430 for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
431 if ((*it)->getType() != TestStep::Type::Wait) continue;
432 if ((*it)->isCompleted()) continue;
433 result = (TestStepWait*)(*it);
434 if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
441 const TestStep *TestCase::getStep(int stepNumber) const throw() {
442 if (stepNumber < 1 || stepNumber > steps()) return NULL;
443 // return a_steps.at(stepNumber-1); // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
444 return a_steps[stepNumber-1];