ScriptTestAmdaCommandLine.cpp 25.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
#include <stdlib.h>
#include <stdio.h> /* defines FILENAME_MAX */
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <memory>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>

#include <iterator>
#include <boost/regex.hpp>
#include <boost/algorithm/string/find_format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>

#include "CSlim/SlimUtil.h"
#include "CSlim/SlimList.h"
#include "CSlim/Fixtures.h"

#include "CSlimTools.hh"
//#include "PlotTools.hh"

#include "TimeTable.hh"
#include "AsciiReader.hh"
#include "TimeTableCatalogFactory.hh"
#include "TimeTableCatalogUtil.hh"

#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
struct TestAmdaCommandLine;

struct TestAmdaCommandLine {

	static TestAmdaCommandLine* getInstance() {
		if (!_currentInstance) {
			_currentInstance = new TestAmdaCommandLine;
		}
		return _currentInstance;
	}

	static void releaseInstance() {
		delete _currentInstance;
		_currentInstance = NULL;
	}

	static TestAmdaCommandLine* From(void *fixtureStorage) {
		return reinterpret_cast<TestAmdaCommandLine*>(fixtureStorage);
	}

	char _currentPath[FILENAME_MAX];
	int _result;
	char* _stdOutFile;
	char* _stdErrFile;
	std::string _currentNameTest;
	int _indexTest;
	std::string _path;
	std::string _buildType;
	std::string _execPath;
	std::string _workingDirectory;

private:
	TestAmdaCommandLine() :
			_result(0),
			_currentNameTest(""),
			_indexTest(0),
			_path(""),
			_buildType("Debug"),
			_execPath("../build/Debug/bin/"),
			_workingDirectory("app-debug") {

		const char* lBuildType = getenv("BUILD_TYPE");
		if (lBuildType && (strcmp(lBuildType, "Release") == 0)) {
			_buildType = lBuildType;
			_execPath = "../build/Release/bin/";
			_workingDirectory = "app-release";
		}
		chdir(_workingDirectory.c_str());
		GetCurrentDir(_currentPath, sizeof(_currentPath));
		_stdOutFile = tmpnam(NULL);
		_stdErrFile = tmpnam(NULL);
	}

	~TestAmdaCommandLine() {
		remove(_stdOutFile);
		remove(_stdErrFile);
	}

	static TestAmdaCommandLine* _currentInstance;

};

TestAmdaCommandLine* TestAmdaCommandLine::_currentInstance = NULL;

extern "C" {

void* TestAmdaCommandLine_Create(StatementExecutor* /*errorHandler*/,
		SlimList* /*args*/) {
	return TestAmdaCommandLine::getInstance();
}

void TestAmdaCommandLine_Destroy(void */*fixture*/) {
	// delete TestAmdaCommandLine::From(fixture);
	TestAmdaCommandLine::releaseInstance();
}

static char* returnValueArgument(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	bool valgrind = !access("valgrindMemCheck", R_OK);
	std::string commandExec = std::string(context->_currentPath) + "/"
			+ context->_execPath + "/EXE_AMDA_Kernel ";
	if (valgrind) {
		mkdir("../build/report", S_IRWXU | S_IRGRP | S_IXGRP);
		std::string preCommande =
				std::string(
						"valgrind --xml=yes  --xml-file=../build/report/reportValgrind_")
						+ context->_currentNameTest + "_"
						+ CSlimTools::intToString(context->_indexTest)
						+ ".xml ";
		++context->_indexTest;
		commandExec = preCommande + " " + std::string(context->_currentPath)
				+ "/" + context->_execPath + "/EXE_AMDA_Kernel ";
	}

	// Set environment variable used to HIDE AMDA header
	// on produced files
	setenv ("HIDE_HEADER_FILE", "true", 1);

	std::string command = commandExec + SlimList_GetStringAt(args, 0);
	std::cout << "execute " << command << std::endl;
	int ret = system(command.c_str());
	return CSlimTools::traitReturnSystem(ret);
}

static char* setPath(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	context->_path = std::string(SlimList_GetStringAt(args, 0));
	return CSlimTools::traitReturnSystem(0);
}

static char* commonExecute (void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	std::stringstream ss;

	// Set environment variable used to HIDE AMDA version number
	// on produced files
	setenv ("HIDE_VERSION", "true", 1);

	std::cerr << "Path: " << getenv("PATH") << std::endl;

	if (!access("valgrindMemCheck", R_OK)) {
		std::string cmd = std::string(SlimList_GetStringAt(args, 0));
		boost::algorithm::trim(cmd);
		//Use valgrind only for AMDA executables
		std::vector<std::string> allowedCmds{"amdaXMLRequestorTool", "amdaParameterGenerator", "amdaParameterInfo",
			"EXE_AMDA_Kernel", "ttConversion", "ttOperations"};
		if (std::find(std::begin(allowedCmds), std::end(allowedCmds), cmd) != std::end(allowedCmds)) {
			mkdir("../build/report", S_IRWXU | S_IRGRP | S_IXGRP);
			ss << "valgrind --xml=yes --xml-file=../build/report/reportValgrind_"
					<< context->_currentNameTest << "_"
					<< CSlimTools::intToString(context->_indexTest) << ".xml ";
			++context->_indexTest;
		}
	}
	ss << std::string(SlimList_GetStringAt(args, 0)) << " "
			<< SlimList_GetStringAt(args, 1) << " > " << context->_stdOutFile
			<< " 2> " << context->_stdErrFile;

	std::string newCommand = boost::replace_all_copy(ss.str(), "${OUTPUT}",
			context->_stdOutFile);
	std::cout << newCommand << std::endl;
	context->_result = system(newCommand.c_str()); //ss.str().c_str());
	std::string command = std::string("cat ") + context->_stdErrFile;
	std::cerr << "display: " << system(command.c_str()) << std::endl;
	return CSlimTools::traitReturnSystem(context->_result);
}

static char* executeWithInfoCommandArgs(void *fixture, SlimList *args) {
	unsetenv ("HIDE_AMDA_DATE");

	unsetenv ("HIDE_HEADER_FILE");

	return commonExecute (fixture, args);
}

static char* executeCommandArgs(void *fixture, SlimList *args) {
	// Set environment variable used to HIDE AMDA creation date
	// on produced images
	setenv ("HIDE_AMDA_DATE", "true", 1);

	// Set environment variable used to HIDE AMDA header
	// on produced files
	setenv ("HIDE_HEADER_FILE", "true", 1);

	return commonExecute (fixture, args);
}

static char* result(void *fixture, SlimList */*args*/) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	return CSlimTools::traitReturnSystem(context->_result);
}

static char* logFilePattern(void */*fixture*/, SlimList *args) {
	std::string command = std::string("egrep '") + SlimList_GetStringAt(args, 0)
			+ "' example.log";
	int ret = system(command.c_str());

	return CSlimTools::traitReturnSystem(ret);
}

static char* logFileBeforPattern(void */*fixture*/, SlimList *args) {
	std::string command = std::string("grep -m1 -B1000 \"")
			+ SlimList_GetStringAt(args, 0) + "\" example.log";
	command += std::string(" | egrep \"") + SlimList_GetStringAt(args, 1)
			+ "\"";
	int ret = system(command.c_str());

	return CSlimTools::traitReturnSystem(ret);
}

static char* errFilePattern(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	std::string command = std::string("egrep '") + SlimList_GetStringAt(args, 0)
			+ "' " + context->_stdErrFile;
	int ret = system(command.c_str());
	return CSlimTools::traitReturnSystem(ret);
}

static char* checkTimeTableFileType(void */*fixture*/, SlimList *args) {
	int result = 0;

	// Check the result TimeTable file name
	std::string file(SlimList_GetStringAt(args, 0));

	// Check the result TimeTable file name
	std::string fileType(SlimList_GetStringAt(args, 1));

	// Check file existence
	if (access(file.c_str(), F_OK) != 0) {
		 result = -3;
	}

	// Read Time Table reference
	std::string readerType = TimeTableCatalog::TimeTableCatalogFactory::getInstance().getReaderType(file);

	if(fileType != readerType) {
		result = -1;
	}

	static char returnStr[128];
        sprintf (returnStr, "%d", result);
        return const_cast<char *>(returnStr);
}

static char* diffOutputFileRef(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	std::string command = std::string("diff ") + context->_stdOutFile + " "
			+ context->_path + SlimList_GetStringAt(args, 0);
	int ret = system(command.c_str());

	return CSlimTools::traitReturnSystem(ret);
}

static char* diffOutputFileFile1File2(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	std::string command = std::string("diff ") + context->_path
			+ SlimList_GetStringAt(args, 0) + " "
			+ SlimList_GetStringAt(args, 1);
	int ret = system(command.c_str());

	return CSlimTools::traitReturnSystem(ret);
//	return CSlimTools::compareFile(SlimList_GetStringAt(args, 0), SlimList_GetStringAt(args, 1));

}

static char *dodiffTimeTable(const char *tt1, const char *tt2) {
	std::stringstream str;
	std::ifstream fileLeft(tt1);
	std::ifstream fileRight(tt2);
	bool ret = true;
	if (fileLeft.good() && fileRight.good()) {
		int lineNumber = 0;
		double maxEpsilon = 0;
		while (fileLeft.good() && fileRight.good()) {
			std::string lineLeft;
			std::string lineRight;
			++lineNumber;
			getline(fileLeft, lineLeft);
			getline(fileRight, lineRight);
			if (lineLeft.find("# Creation Date:") != std::string::npos
					&& lineRight.find("# Creation Date:") != std::string::npos) {
				// ignore difference between creation date
				continue;
			}
			char *tmp = CSlimTools::compareLine(lineLeft, lineRight, 0,
					lineNumber, maxEpsilon);
			if ((tmp[0] != '0' || tmp[1] != '\0')) {
				str << "line " << lineNumber << ": " << tmp;
				ret = false;
			}
		}
		if (!(fileLeft.eof()) || !(fileRight.eof())) {
			std::cout << "line " << lineNumber << " nb lines different"
					<< std::endl;
			str << "nb lines different";
			ret = false;
		}
	} else {
		if (fileRight.good()) {
			std::cout << "file '" << tt1 << "' not found" << std::endl;
			str << std::string("file '") + tt1 + "' not found";
			ret = false;
		} else {
			std::cout << "file '" << tt2 << "' not found" << std::endl;
			str << std::string("file '") + tt2 + "' not found";
			ret = false;
		}
	}
	if (ret) {
		return const_cast<char *>("0");
	} else {
		std::string error = str.str();
                static char returnStr[1024];
                sprintf (returnStr, "%1023s", error.c_str());
                return const_cast<char *>(returnStr);
		//std::vector<char> data(error.size() + 1);
		//std::copy(error.begin(), error.end(), data.begin());
		//return &data[0];
	}
}

/**
 * @brief Check if for a reference interval, there is a corresponding interval in the given result.
 * When checking two intervals, we take into account that it could be a delta (no more than sampling time)
 * between the two start time and/or stop time.
 * It's also possible that the two intervals are not at the same indices and so we have a window on which a search is done.
 */
static char* diffTimeTableInterTT1TT2(void */*fixture*/, SlimList *args) {
	//TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);

	// This must be the reference file.
	std::string file1(SlimList_GetStringAt(args, 0));
	// This must be the result file.
	std::string file2(SlimList_GetStringAt(args, 1));

	// Check file existence
	if (access(file1.c_str(), F_OK) != 0) {
		return const_cast<char *>("-3");
	}
	if(access(file2.c_str(), F_OK) != 0) {
		return const_cast<char *>("-3");
	}

	// Read Time Table reference
	std::string readerType = TimeTableCatalog::TimeTableCatalogFactory::getInstance().getReaderType(file1);
	TimeTableCatalog::TimeTable tt1;
	tt1.read(file1, readerType);

	// Read Time Table result
	readerType = TimeTableCatalog::TimeTableCatalogFactory::getInstance().getReaderType(file2);
	TimeTableCatalog::TimeTable tt2;
	tt2.read(file2, readerType);

	// Get sampling time and check it
	int samplingTime_1 = 1, samplingTime_2 = 2;
	size_t pos1;

	// Constant is taken from ParamOutputDataMining class.
	const std::string search_1 = "Sampling: ";

	if ( (pos1 = tt1._history.find(search_1)) != std::string::npos) {
		pos1 += search_1.length();

		std::string sSamplingTime = tt1._history.substr(pos1, tt1._history.length() - 1);
		samplingTime_1 = atoi(sSamplingTime.c_str());
	}

	if ( (pos1 = tt2._history.find(search_1)) != std::string::npos) {
		pos1 += search_1.length();

		std::string sSamplingTime = tt2._history.substr(pos1, tt1._history.length() - 1);
		samplingTime_2 = atoi(sSamplingTime.c_str());
	}

	if (samplingTime_1 != samplingTime_2) {
		std::cout<<tt1._history<<std::endl;
		std::cout<<tt2._history<<std::endl;
		return const_cast<char *>("-2");
	}

	// Get intervals
	std::vector<TimeTableCatalog::TimeInterval>tt1Intervals = tt1.getIntervals();
	std::vector<TimeTableCatalog::TimeInterval>tt2Intervals = tt2.getIntervals();

	// Get intervals size
	int tt1IntNumber = tt1Intervals.size();
	int tt2IntNumber = tt2Intervals.size();
	// Default window is set to 10
	int windowInterval = 10;

	// If intervals size are not the same we take difference length.
	if(tt1IntNumber != tt2IntNumber) {
		windowInterval = abs(tt1IntNumber - tt2IntNumber);
	}

	// Store index of result interval for which an interval is matching with reference interval.
	std::vector<unsigned int> resultIndexUsed;

	int error = 0;

	// Try to find a similarity for each interval in the two file.
	for(int index = 0; index < tt1IntNumber; index++) {
		std::stringstream startTime1, startTime2, stopTime1, stopTime2;
		TimeTableCatalog::TimeInterval ttInterval_1 = tt1Intervals[index];
		TimeTableCatalog::writeISOTime(ttInterval_1._startTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, startTime1);
		TimeTableCatalog::writeISOTime(ttInterval_1._stopTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, stopTime1);


		if (index >= tt2IntNumber)
		{
			error = -1;
			std::cout<<"No similarity found for this result interval: ["<<startTime1.str()<<", "<<stopTime1.str()<<"]"<<std::endl;
			continue;
		}

		TimeTableCatalog::TimeInterval ttInterval_2 = tt2Intervals[index];

		TimeTableCatalog::writeISOTime(ttInterval_2._startTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, startTime2);
		TimeTableCatalog::writeISOTime(ttInterval_2._stopTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, stopTime2);

		// For the same index, check if there is a similarity between the two intervals (take into account delta that must be less than sampling time)
		if( (abs(ttInterval_1._startTime - ttInterval_2._startTime) < samplingTime_1) && (abs(ttInterval_1._stopTime - ttInterval_2._stopTime) < samplingTime_1) ) {
			resultIndexUsed.push_back(index);
		} else {
			// Define window start and end.
			int parssingIndex = windowInterval * (-1);
			int endParssing = windowInterval;

			if (index < windowInterval) {
				parssingIndex = index * (-1);
			} else if (index > tt1IntNumber - windowInterval) {
				endParssing = tt1IntNumber - index;
			}

			bool notFound = true;
			// Parse window index
			while ((parssingIndex <= endParssing) && notFound) {
				ttInterval_2 = tt2Intervals[index + parssingIndex];
				if( (abs(ttInterval_1._startTime - ttInterval_2._startTime) < samplingTime_1) && (abs(ttInterval_1._stopTime - ttInterval_2._stopTime) < samplingTime_1) ) {
					notFound = false;
					resultIndexUsed.push_back(index + parssingIndex);
				} else {
					parssingIndex++;
				}
			}

			if(notFound) {
				error = -1;
				std::cout<<"No similarity found for this reference interval: ["<<startTime1.str()<<", "<<stopTime1.str()<<"]"<<std::endl;
			}
		}
	}

	std::cout<<std::endl;

	// Print result interval that have not been used
	std::sort(resultIndexUsed.begin(), resultIndexUsed.end());
	int size = resultIndexUsed.size();
	unsigned int indexUsed;
	unsigned int count = 0;
	bool notUsed = true;
	for (int index = 0; index < size; index++) {
		indexUsed = resultIndexUsed[index];
		notUsed = true;

		// For each index not used print interval
		while (notUsed) {
			if(count < indexUsed) {
				TimeTableCatalog::TimeInterval ttInterval_2 = tt2Intervals[count];
				std::stringstream startTime2, stopTime2;
				TimeTableCatalog::writeISOTime(ttInterval_2._startTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, startTime2);
				TimeTableCatalog::writeISOTime(ttInterval_2._stopTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, stopTime2);
				std::cout<<"No similarity found for this result interval: ["<<startTime2.str()<<", "<<stopTime2.str()<<"]"<<std::endl;
				count++;

				error = -1;
			} else {
				notUsed = false;
				count++;
			}
		}
	}

	// Parse end of intervals
	if (count < tt2Intervals.size()) {
		while (count < tt2Intervals.size()) {
			TimeTableCatalog::TimeInterval ttInterval_2 = tt2Intervals[count];
			std::stringstream startTime2, stopTime2;
			TimeTableCatalog::writeISOTime(ttInterval_2._startTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, startTime2);
			TimeTableCatalog::writeISOTime(ttInterval_2._stopTime, TimeTableCatalog::TimeTable::TIME_FORMAT::YYYYMMDDThhmmss, stopTime2);
			std::cout<<"No similarity found for this result interval: ["<<startTime2.str()<<", "<<stopTime2.str()<<"]"<<std::endl;
			count++;
		}
		error = -1;
	}

	static char returnStr[128];
	sprintf (returnStr, "%d", error);
	return const_cast<char *>(returnStr);
}

static char* diffTimeTableTT1TT2(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	std::string file1(SlimList_GetStringAt(args, 0));
	std::string file2(SlimList_GetStringAt(args, 1));

	// If there is no path "/" in the file name, so add path
	if(file1.find("/") == std::string::npos) {
		file1 = context->_path + file1;
	}

	if(file2.find("/") == std::string::npos) {
			file2 = context->_path + file2;
	}

	return dodiffTimeTable(file1.c_str(), file2.c_str());
}

static char *diffOutputFiles(const char *file1, const char *file2,
		double epsilon) {
	std::cout << "Compare " << file1 << " to " << file2 << " with epsilon = "
			<< epsilon << std::endl;
	return CSlimTools::compareFile(file1, file2, epsilon);
}

static char* diffOutputFileFile1File2Epsilon(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	return diffOutputFiles(
			std::string(context->_path + SlimList_GetStringAt(args, 0)).c_str(),
			std::string(SlimList_GetStringAt(args, 1)).c_str(),
			SlimList_GetDoubleAt(args, 2));
}

static char* diffOutputFileSameDirFile1File2Epsilon(void */*fixture*/,
		SlimList *args) {
	return diffOutputFiles(std::string(SlimList_GetStringAt(args, 0)).c_str(),
			std::string(SlimList_GetStringAt(args, 1)).c_str(),
			SlimList_GetDoubleAt(args, 2));
}

static char* changeDirPath(void *fixture, SlimList *args) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	context->_result = chdir(
			std::string(SlimList_GetStringAt(args, 0)).c_str());
	return CSlimTools::traitReturnSystem(context->_result);
}

static char* changeDirRestore(void *fixture, SlimList */*args*/) {
	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	context->_result = chdir(context->_currentPath);
	return CSlimTools::traitReturnSystem(context->_result);
}

/** function used to log */
static char* referenceIdTest(void *fixture, SlimList *args) {
	std::cout << std::endl
			<< "***************************************************************************"
			<< std::endl;
	std::cout << "Test " << SlimList_GetStringAt(args, 0) << std::endl;
	std::cerr << "Test " << SlimList_GetStringAt(args, 0) << std::endl;

	TestAmdaCommandLine* context = TestAmdaCommandLine::From(fixture);
	const char *chaine = SlimList_GetStringAt(args, 0);
	std::stringstream ss;
	for (unsigned int it = 0; it < strlen(chaine); it++) {
		if (isalnum(chaine[it])) {
			ss << chaine[it];
		} else {
			ss << "_";
		}
	}
	context->_currentNameTest = ss.str();
	return const_cast<char *>("");
}

clock_t getExecutionTime(const std::string& name,
		std::vector<std::string> args) {
	clock_t executionTime;
	if (name == "intersect") {

		std::vector<TimeTableCatalog::TimeTable> tts;
		TimeTableCatalog::TimeTable tt1;
		tt1.read(args[0], TimeTableCatalog::AsciiReader::FORMAT);
		tts.push_back(tt1);
		std::cout << "   " << tt1.getIntervalNumber() <<" intervals read" << std::endl;
		TimeTableCatalog::TimeTable tt2;
		tt2.read(args[1], TimeTableCatalog::AsciiReader::FORMAT);
		std::cout << "   " << tt2.getIntervalNumber() <<" intervals read" << std::endl;
		tts.push_back(tt2);
		TimeTableCatalog::TimeTable tt;
		executionTime = clock();
		std::unique_ptr<TimeTableCatalog::TimeTable> intersectedTT = TimeTableCatalog::TimeTable::intersect(tts);
		executionTime = clock() - executionTime;
		std::cout << "   " << intersectedTT->getIntervalNumber() <<" intervals generated" << std::endl;
	}
	printf("Execution time is %f seconds",
			((float) executionTime) / CLOCKS_PER_SEC);
	return executionTime;
}

static char* calculateExecutionTime(void */*fixture*/, SlimList *args) {
	std::vector<std::string> paths;
	std::istringstream iss(std::string(SlimList_GetStringAt(args, 1)));
	do {
		std::string ttpath;
		iss >> ttpath;
		paths.push_back(ttpath);
	} while (iss);

	std::string fname(SlimList_GetStringAt(args, 0));
	std::string fargs(iss.str());
	boost::algorithm::replace_all(fargs, " ", ",");
	printf("Executing %s (%s)...\n", fname.c_str(), fargs.c_str());
	clock_t execTime = getExecutionTime(fname, paths);
	static char buf[256];
	sprintf(buf, "%f", ((float) execTime) / CLOCKS_PER_SEC);
	return buf;
}

/**
 * @brief Check if calculated error rate is less than given error rate (maximum authorized error rate).
 */
//static char* calculateErrorRate(void */*fixture*/, SlimList *args) {
/*	std::string lReferenceFile(SlimList_GetStringAt(args, 0));
	std::string lResultFile(SlimList_GetStringAt(args, 1));
	double maxErrorRate = atof(SlimList_GetStringAt(args, 2));

	// Check if file need to be converted in png format.
	if (lReferenceFile.find(".png") == std::string::npos) {
		lReferenceFile = PlotTools::convert2Png(lReferenceFile);
	}

	// Check if file need to be converted in png format.
	if (lResultFile.find(".png") == std::string::npos) {
		lResultFile = PlotTools::convert2Png(lResultFile);
	}

	std::cout<<"Reference file: "<<lReferenceFile<<std::endl;
	std::cout<<"Result file: "<<lResultFile<<std::endl;

	double errorRate = PlotTools::calculateErrorRate(lReferenceFile, lResultFile);

	if (errorRate < maxErrorRate) {
		return const_cast<char *>("0");
	} else {
		printf("Maximum error rate exceed (%f%%), current error rate is %f%%", maxErrorRate, errorRate);
		return const_cast<char *>("1");
	}
}*/

// Comparaison de deux images par production d'une image delta (ImgDiff

static char* compareImg1Img2ImgDiff(void */*fixture*/, SlimList *args) {
	static char returnStr[128];

	bool skip = !access("skipPlotCompare", R_OK);
	if (skip) {
		std::cout << "Skip plot compare" << std::endl;
		strcpy (returnStr, "0");
		return (returnStr);
	}

	char command [2048];
	sprintf (command, "compare %s %s %s",
				SlimList_GetStringAt(args, 0),
				SlimList_GetStringAt(args, 1),
				SlimList_GetStringAt(args, 2));

	// Execute command
	int ret =system (command);
	if (ret == 0)
		strcpy (returnStr, "0");
	else
		sprintf (returnStr, "Erreur systeme %d", ret);

   return (returnStr);
}

// Comparaison stricte de deux parties d'images

static char* compareImg1Img2Extract(void */*fixture*/, SlimList *args) {
	static char returnStr[128];

	bool skip = !access("skipPlotCompare", R_OK);
	if (skip) {
		std::cout << "Skip plot compare" << std::endl;
		strcpy (returnStr, "0");
		return (returnStr);
	}

	char imgDiffFile[] = "/tmp/amdaImgDiff.XXXXXX";
	close (mkstemp(imgDiffFile));

	char imgDiffResultFile[] = "/tmp/amdaImgDiffResult.XXXXXX";
	close (mkstemp(imgDiffResultFile));

	char command [2048];
	if (strcasecmp (SlimList_GetStringAt(args, 2), "all") != 0) {
		sprintf (command, "compare -extract %s -metric PSNR %s %s %s 2> %s",
				SlimList_GetStringAt(args, 2),
				SlimList_GetStringAt(args, 0),
				SlimList_GetStringAt(args, 1),
				imgDiffFile,
				imgDiffResultFile);
	}
	else {
		sprintf (command, "compare -metric PSNR %s %s %s 2> %s",
				SlimList_GetStringAt(args, 0),
				SlimList_GetStringAt(args, 1),
				imgDiffFile,
				imgDiffResultFile);
	}


	// Execute command and create imgDiffResultFile file
	int ret = system (command);
	if (ret == 0) {
		// Extract metric
		char metric [128];
		memset (metric, 0, sizeof (metric));

		FILE * fMetric = fopen (imgDiffResultFile, "r");
		if (fMetric != NULL) {
			fgets (metric, sizeof(metric), fMetric);
			fclose (fMetric);
			if (strstr (metric, "inf") != NULL)
				strcpy (returnStr, "0");
			else
				strcpy (returnStr, "Les images diffèrent");
		}
		else {
		   strcpy (returnStr, "Fichier metric non trouvé");
		}
	}
	else {
		sprintf (returnStr, "Erreur systeme %d", ret);
	}

	// Remove temporary files
	unlink (imgDiffFile);
	unlink (imgDiffResultFile);

    return (returnStr);
}

SLIM_CREATE_FIXTURE(TestAmdaCommandLine)
	SLIM_FUNCTION(returnValueArgument)
	SLIM_FUNCTION(logFilePattern)
	SLIM_FUNCTION(logFileBeforPattern)
	SLIM_FUNCTION(changeDirPath)
	SLIM_FUNCTION(changeDirRestore)
	SLIM_FUNCTION(checkTimeTableFileType)
	SLIM_FUNCTION(diffTimeTableTT1TT2)
	SLIM_FUNCTION(diffTimeTableInterTT1TT2)
	SLIM_FUNCTION(diffOutputFileFile1File2)
	SLIM_FUNCTION(diffOutputFileFile1File2Epsilon)
	SLIM_FUNCTION(diffOutputFileSameDirFile1File2Epsilon)
	SLIM_FUNCTION(result)
	SLIM_FUNCTION(executeCommandArgs)
	SLIM_FUNCTION(executeWithInfoCommandArgs)
	SLIM_FUNCTION(errFilePattern)
	SLIM_FUNCTION(referenceIdTest)
	SLIM_FUNCTION(setPath)
	SLIM_FUNCTION(calculateExecutionTime)
	SLIM_FUNCTION(diffOutputFileRef)
	//SLIM_FUNCTION(calculateErrorRate)
	SLIM_FUNCTION(compareImg1Img2ImgDiff)
	SLIM_FUNCTION(compareImg1Img2Extract)
	SLIM_END
}