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/xml/Compiler.hpp>
18 #include <anna/diameter/defines.hpp>
19 #include <anna/diameter/helpers/dcca/defines.hpp>
20 #include <anna/diameter/codec/functions.hpp>
21 #include <anna/diameter/helpers/base/functions.hpp>
22 #include <anna/diameter/helpers/dcca/functions.hpp>
23 #include <anna/core/util/Millisecond.hpp>
24 #include <anna/core/tracing/Logger.hpp>
27 #include <TestCase.hpp>
28 #include <TestManager.hpp>
31 ///////////////////////////////////////////////////////////////////////////////////////////////////
32 void TestCase::DebugSummary::addHint(const std::string &hint) throw() {
34 event.Timestamp = anna::functions::millisecond();
36 a_events.push_back(event);
39 void TestCase::DebugSummary::clear() throw() {
43 anna::xml::Node* TestCase::DebugSummary::asXML(anna::xml::Node* parent) const throw() {
44 anna::xml::Node* result = parent->createChild("DebugSummary");
46 std::vector<event_t>::const_iterator it;
47 for (it = a_events.begin(); it != a_events.end(); it++) {
48 anna::xml::Node* event = result->createChild("Event");
49 event->createAttribute("Timestamp", (*it).Timestamp.asString());
50 event->createAttribute("Hint", (*it).Hint);
55 ///////////////////////////////////////////////////////////////////////////////////////////////////
58 TestCase::TestCase(unsigned int id) :
60 a_state(State::Initialized),
62 a_interactiveAmount(-1) {
64 /*a_stepsIt = a_steps.end()*/;
65 TestManager &testManager = TestManager::instantiate();
66 testManager.tcsStateStats(State::Initialized, State::Initialized);
69 TestCase::~TestCase() {
70 reset(true); // hard reset
71 std::vector<TestStep*>::const_iterator it;
72 for (it = a_steps.begin(); it != a_steps.end(); it++) delete (*it);
75 const char* TestCase::asText(const State::_v state)
77 static const char* text [] = { "Initialized", "InProgress", "Failed", "Success" };
81 anna::xml::Node* TestCase::asXML(anna::xml::Node* parent) const
83 anna::xml::Node* result = parent->createChild("TestCase");
85 result->createAttribute("Id", a_id);
86 result->createAttribute("State", asText(a_state));
87 result->createAttribute("StartTimestamp", a_startTime.asString());
88 int steps = a_steps.size();
90 result->createAttribute("NumberOfTestSteps", steps);
91 std::vector<TestStep*>::const_iterator it;
92 for (it = a_steps.begin(); it != a_steps.end(); it++) {
97 if (a_debugSummary.events()) {
98 a_debugSummary.asXML(result);
101 result->createAttribute("Interactive", (a_interactiveAmount != -1) ? "yes":"no");
106 std::string TestCase::asXMLString() const throw() {
107 anna::xml::Node root("root");
108 return anna::xml::Compiler().apply(asXML(&root));
111 bool TestCase::hasSameCondition(const TestCondition &condition) const throw() {
112 std::vector<TestStep*>::const_iterator it;
114 for (it = a_steps.begin(); it != a_steps.end(); it++) {
115 if ((*it)->getType() != TestStep::Type::Wait) continue;
116 step = (TestStepWait *)(*it);
117 if (step->getCondition() == condition) return true;
123 void TestCase::setState(const State::_v &state) throw() {
125 State::_v previousState = a_state;
126 if (state == previousState) return;
128 TestManager &testManager = TestManager::instantiate();
131 testManager.tcsStateStats(previousState, state);
135 if ((getState() == State::Failed) && (!testManager.getDumpFailedReports())) return;
136 if ((getState() == State::Success) && (!testManager.getDumpSuccessReports())) return;
137 // report file name: cycle-<cycle id>.testcase-<test case id>.xml
139 // FORMAT: We tabulate the cycle and test case in order to ease ordering of files by mean ls:
140 int cycles = testManager.getPoolRepeats();
141 int tests = testManager.tests();
142 int cyclesWidth = (cycles<=0) ? 3 /* 1000 cycles !! */: ((int) log10 ((double) cycles) + 1);
143 int testsWidth = (tests<=0) ? 9 /* subscribers */: ((int) log10 ((double) tests) + 1);
144 std::stringstream format;
145 format << "/cycle-%0" << cyclesWidth << "d.testcase-%0" << testsWidth << "llu.xml";
148 std::string file = testManager.getReportsDirectory() + anna::functions::asString(format.str().c_str(), testManager.getPoolCycle(), a_id);
150 out.open(file.c_str(), std::ofstream::out | std::ofstream::app);
151 if(out.is_open() == false) {
152 std::string msg("Error opening '");
154 msg += "' for writting";
155 anna::Logger::error(msg, ANNA_FILE_LOCATION);
158 out << asXMLString() << std::endl;
164 bool TestCase::done() throw() {
165 if (a_stepsIt == a_steps.end()) {
166 setState(State::Success);
173 bool TestCase::process() throw() {
175 LOGWARNING(anna::Logger::warning(anna::functions::asString("Test case %llu is empty, nothing to execute", a_id), ANNA_FILE_LOCATION));
179 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Test case %llu is finished, nothing done until soft-reset", a_id), ANNA_FILE_LOCATION));
183 if (a_state == State::Initialized) {
184 a_stepsIt = a_steps.begin();
185 setState(State::InProgress);
187 // For 'wait' steps (not really useful, but better than nothing: begin timestamp on test case start timestamp...):
188 a_startTime = anna::functions::millisecond();
191 // Check end of the test case:
192 if (done()) return false;
194 bool somethingDone = false;
195 while ((*a_stepsIt)->execute()) { // executes returns 'true' if the next step must be also executed (execute until can't stand no more)
197 // Check end of the test case:
198 if (done()) return false;
199 somethingDone = true;
202 return somethingDone;
205 bool TestCase::reset(bool hard) throw() {
207 // Soft reset if finished:
208 if (!hard /* is soft reset */ && !isFinished()) return false;
210 // Clean stage ////////////////////////////
212 std::vector<TestStep*>::iterator it;
213 for (it = a_steps.begin(); it != a_steps.end(); it++)
216 a_debugSummary.clear();
218 a_interactiveAmount = -1;
220 setState(State::Initialized);
225 void TestCase::assertInitialized() const throw(anna::RuntimeException) {
227 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);
230 void TestCase::assertMessage(const anna::DataBlock &db, bool toEntity) throw(anna::RuntimeException) {
232 bool isRequest = anna::diameter::codec::functions::isRequest(db);
233 bool registerKeys = ((isRequest && toEntity) || (!isRequest && !toEntity) /* (*) */);
234 // (*) we register answers Session-Id "assuming" that we will know the Session-Id values created by the client.
235 // This is another solution regarding diameter server testing. No sure about the final implementation.
236 // We will help registering also subscriber data, because certain messages (i.e. SLR) coming from clients could
237 // have specific Session-Id value (unknown at test programming), and normally are identified by subscriber.
241 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
242 if (a_hopByHops.find(hbh) != a_hopByHops.end())
243 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);
244 a_hopByHops[hbh] = NULL; // may be assigned to a wait condition
248 TestManager &testManager = TestManager::instantiate();
249 testManager.registerSessionId(anna::diameter::helpers::base::functions::getSessionId(db), this);
252 std::string subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
253 if (subscriberId == "") // try with IMSI
254 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(db, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
256 if (subscriberId != "")
257 testManager.registerSubscriberId(subscriberId, this);
261 void TestCase::addTimeout(const anna::Millisecond &timeout) throw(anna::RuntimeException) {
263 TestStepTimeout *step = new TestStepTimeout(this);
264 step->setTimeout(timeout);
268 void TestCase::addSendxml2e(const anna::DataBlock &db, OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
270 assertMessage(db, true /* to entity */);
272 if (stepNumber != -1) {
273 const TestStep *stepReferred = getStep(stepNumber);
275 throw anna::RuntimeException(anna::functions::asString("Step number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
277 if (stepReferred->getType() != TestStep::Type::Wait)
278 throw anna::RuntimeException(anna::functions::asString("Step number (%d) must refer to a 'wait' step (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
280 const TestCondition &tc = (static_cast<const TestStepWait*>(stepReferred))->getCondition();
281 if (tc.getCode() == "0") { // if regexp used, is not possible to detect this kind of errors
282 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);
286 TestStepSendxml2e *step = new TestStepSendxml2e(this);
287 step->setMsgDataBlock(db);
288 step->setOriginHost(host);
289 step->setWaitForRequestStepNumber(stepNumber); // -1 means, no reference
293 void TestCase::addSendxml2c(const anna::DataBlock &db, OriginHost *host, int stepNumber) throw(anna::RuntimeException) {
295 assertMessage(db, false /* to client */);
297 TestStepSendxml2c *step = new TestStepSendxml2c(this);
298 step->setMsgDataBlock(db);
299 step->setOriginHost(host);
303 void TestCase::addDelay(const anna::Millisecond &delay) throw(anna::RuntimeException) {
305 TestStepDelay *step = new TestStepDelay(this);
306 step->setDelay(delay);
310 void TestCase::addWait(bool fromEntity,
311 const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
312 const std::string &sessionId, const std::string &resultCode,
313 const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw(anna::RuntimeException) {
315 std::string usedHopByHop = hopByHop;
316 TestStepWait *step = NULL;
318 // Check basic conditions:
320 if (resultCode != "")
321 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);
323 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);
326 if (hopByHop != "") {
327 if (hopByHop[0] == '#') {
329 throw anna::RuntimeException(anna::functions::asString("No steps has been programmed, step reference is nonsense (test case %llu)", a_id), ANNA_FILE_LOCATION);
331 int stepNumber = atoi(hopByHop.substr(1).c_str());
333 const TestStep *stepReferred = getStep(stepNumber);
335 throw anna::RuntimeException(anna::functions::asString("Step reference number (%d) do not exists (test case %llu)", stepNumber, a_id), ANNA_FILE_LOCATION);
337 if (stepReferred->getType() != TestStep::Type::Sendxml2e && stepReferred->getType() != TestStep::Type::Sendxml2c)
338 throw anna::RuntimeException(anna::functions::asString("Step number must refer to a 'sendxml2e' or 'sendxml2c' step (test case %llu)", a_id), ANNA_FILE_LOCATION);
340 const anna::DataBlock &db = (static_cast<const TestStepSendxml*>(stepReferred))->getMsgDataBlock();
341 bool isAnswer = anna::diameter::codec::functions::isAnswer(db);
343 throw anna::RuntimeException(anna::functions::asString("Step number must refer to a request message (test case %llu)", a_id), ANNA_FILE_LOCATION);
346 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(db);
347 usedHopByHop = anna::functions::asString(hbh);
348 step = new TestStepWait(this);
349 a_hopByHops[hbh /* always exists: is the info we calculated above */] = step;
354 if (!step) step = new TestStepWait(this);
355 step->setCondition(fromEntity, code, bitR, usedHopByHop, applicationId, sessionId, resultCode, msisdn, imsi, serviceContextId);
358 if (hasSameCondition(step->getCondition()))
359 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);
365 void TestCase::addWaitRegexp(bool fromEntity, const std::string ®exp) throw(anna::RuntimeException) {
368 TestStepWait *step = new TestStepWait(this);
369 step->setCondition(fromEntity, regexp);
372 if (hasSameCondition(step->getCondition()))
373 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);
379 void TestCase::addCommand(const std::string &cmd) throw(anna::RuntimeException) {
382 TestStepCmd *step = new TestStepCmd(this);
383 step->setScript(cmd);
388 TestStepWait *TestCase::searchNextWaitConditionFulfilled(const anna::DataBlock &message, bool waitFromEntity) throw() {
390 TestStepWait *result;
391 for (std::vector<TestStep*>::const_iterator it = a_stepsIt /* current */; it != a_steps.end(); it++) {
392 if ((*it)->getType() != TestStep::Type::Wait) continue;
393 if ((*it)->isCompleted()) continue;
394 result = (TestStepWait*)(*it);
395 if ((result->getCondition().receivedFromEntity() == waitFromEntity) && (result->fulfilled(message)))
402 const TestStep *TestCase::getStep(int stepNumber) const throw() {
403 if (stepNumber < 1 || stepNumber > steps()) return NULL;
404 // return a_steps.at(stepNumber-1); // http://stackoverflow.com/questions/3269809/stdvectorat-vs-operator-surprising-results-5-to-10-times-slower-f
405 return a_steps[stepNumber-1];