Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • cberge/dynamic-graph
  • ostasse/dynamic-graph
  • gsaurel/dynamic-graph
  • stack-of-tasks/dynamic-graph
4 results
Show changes
Showing
with 1930 additions and 1414 deletions
// -*- c++-mode -*-
// Copyright 2010 François Bleibel Thomas Moulard, Olivier Stasse
//
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/dynamic-graph-api.h>
#include <exception>
#include <boost/lambda/bind.hpp>
#include <string>
#include <sstream>
#include <algorithm>
#include <dynamic-graph/exception-signal.h>
#include <dynamic-graph/linear-algebra.h>
namespace dynamicgraph
{
SignalCaster::SignalCaster ()
{}
SignalCaster::~SignalCaster ()
{}
void SignalCaster::destroy()
{
delete instance_;
instance_ = 0;
}
void
SignalCaster::registerCast (const std::type_info& type,
SignalCaster::displayer_type displayer,
SignalCaster::caster_type caster,
SignalCaster::tracer_type tracer)
{
if (existsCast (type))
{
// If type name has already been registered for same type, do not throw.
if (type_info_[type.name()] != &type)
{
std::string typeName(type.name());
std::ostringstream os;
os << "cast already registered for typename " << typeName << "\n"
<< "and types differ: " << &type << " != "
<< type_info_[type.name()]
<< ".\n"
<< "A possible reason is that the dynamic"
<< " library defining this type\n"
<< "has been loaded several times, defining different symbols"
<< " for the same type.";
throw ExceptionSignal(ExceptionSignal::GENERIC,
os.str());
}
}
functions_[type.name()] = cast_functions_type(displayer,caster, tracer);
type_info_[type.name()] = &type;
}
void
SignalCaster::unregisterCast (const std::type_info& type)
{
size_t n = functions_.erase(type.name ());
if (0 == n) // erase did not find element
// TODO: throw Cast not registered exception
throw ExceptionSignal(ExceptionSignal::GENERIC);
}
bool
SignalCaster::existsCast (const std::type_info& type) const
{
return functions_.find (type.name ()) != functions_.end ();
}
SignalCaster::cast_functions_type&
SignalCaster::getCast (const std::string& type_name)
{
std::map<std::string, cast_functions_type>::iterator it =
functions_.find(type_name);
if (it == functions_.end ())
//TODO: throw "cast not registered" exception
throw ExceptionSignal(ExceptionSignal::BAD_CAST, "Cast not registered");
return it->second;
}
void SignalCaster::disp (const boost::any& object, std::ostream& os)
{
getCast(object.type ().name ()).get<0> () (object, os);
}
void
SignalCaster::trace(const boost::any& object, std::ostream& os)
{
getCast(object.type ().name ()).get<2> () (object, os);
}
std::vector<std::string>
SignalCaster::listTypenames() const
{
std::vector<std::string> typeList;
for (std::map<std::string, cast_functions_type>::const_iterator iter =
functions_.begin(); iter != functions_.end(); iter++)
typeList.push_back(iter->first);
return typeList;
}
boost::any
SignalCaster::cast (const std::type_info& type, std::istringstream& iss)
{
return getCast(type.name ()).get<1> () (iss);
}
/// Singleton on the library-wide instance of SignalCaster
SignalCaster* SignalCaster::getInstance(void)
{
if (instance_ == 0) {
instance_ = new SignalCaster;
}
return instance_;
}
SignalCaster* SignalCaster::instance_ = 0;
} // namespace dynamicgraph
......@@ -12,116 +12,98 @@
/* --------------------------------------------------------------------- */
/* DG */
#include <iomanip>
#include <boost/bind.hpp>
#include <dynamic-graph/tracer-real-time.h>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/tracer-real-time.h>
#include <boost/bind.hpp>
#include <iomanip>
using namespace std;
using namespace dynamicgraph;
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TracerRealTime,"TracerRealTime");
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TracerRealTime, "TracerRealTime");
/* --------------------------------------------------------------------- */
/* --- DGOUTSTRINGSTREAM ---------------------------------------------- */
/* --------------------------------------------------------------------- */
OutStringStream::
OutStringStream ()
: std::ostringstream ()
,buffer( 0 ),index(0),bufferSize(0),full(false)
{
OutStringStream::OutStringStream()
: std::ostringstream(), buffer(0), index(0), bufferSize(0), full(false) {
dgDEBUGINOUT(15);
}
OutStringStream::
~OutStringStream ()
{
OutStringStream::~OutStringStream() {
dgDEBUGIN(15);
delete[] buffer;
dgDEBUGOUT(15);
}
void OutStringStream::
resize (const std::streamsize& size)
{
void OutStringStream::resize(const std::streamsize &size) {
dgDEBUGIN(15);
index=0;
index = 0;
bufferSize = size;
full=false;
full = false;
delete[] buffer;
buffer = new char[static_cast<size_t> (size)];
buffer = new char[static_cast<size_t>(size)];
dgDEBUGOUT(15);
}
bool OutStringStream::
addData (const char * data, const std::streamoff& size)
{
bool OutStringStream::addData(const char *data, const std::streamoff &size) {
dgDEBUGIN(15);
std::streamsize towrite = static_cast<std::streamsize> (size);
if (index + towrite > bufferSize)
{
dgDEBUGOUT(15);
full = true;
return false;
}
memcpy (buffer + index, data, static_cast<size_t> (towrite));
std::streamsize towrite = static_cast<std::streamsize>(size);
if (index + towrite > bufferSize) {
dgDEBUGOUT(15);
full = true;
return false;
}
memcpy(buffer + index, data, static_cast<size_t>(towrite));
index += towrite;
dgDEBUGOUT(15);
return true;
}
void OutStringStream::
dump( std::ostream& os )
{
void OutStringStream::dump(std::ostream &os) {
dgDEBUGIN(15);
os.write( buffer,index );
os.write(buffer, index);
dgDEBUGOUT(15);
}
void OutStringStream::
empty ()
{
void OutStringStream::empty() {
dgDEBUGIN(15);
index=0; full=false;
index = 0;
full = false;
dgDEBUGOUT(15);
}
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
TracerRealTime::TracerRealTime( const std::string & n )
:Tracer(n)
,bufferSize( BUFFER_SIZE_DEFAULT )
{
TracerRealTime::TracerRealTime(const std::string &n)
: Tracer(n), bufferSize(BUFFER_SIZE_DEFAULT) {
dgDEBUGINOUT(15);
/* --- Commands --- */
{
using namespace dynamicgraph::command;
std::string doc
= docCommandVoid0("Trash the current content of the buffers, without saving it.");
std::string doc = docCommandVoid0(
"Trash the current content of the buffers, without saving it.");
addCommand("empty",
makeCommandVoid0(*this,&TracerRealTime::emptyBuffers,doc ));
makeCommandVoid0(*this, &TracerRealTime::emptyBuffers, doc));
addCommand("getBufferSize",
makeDirectGetter(*this,&bufferSize,
docDirectGetter("bufferSize","int")));
makeDirectGetter(*this, &bufferSize,
docDirectGetter("bufferSize", "int")));
addCommand("setBufferSize",
makeDirectSetter(*this,&bufferSize,
docDirectSetter("bufferSize","int")));
} // using namespace command
makeDirectSetter(*this, &bufferSize,
docDirectSetter("bufferSize", "int")));
} // using namespace command
dgDEBUGOUT(15);
}
......@@ -130,227 +112,194 @@ TracerRealTime::TracerRealTime( const std::string & n )
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void TracerRealTime::
openFile( const SignalBase<int> & sig,
const std::string& givenname )
{
void TracerRealTime::openFile(const SignalBase<int> &sig,
const std::string &givenname) {
dgDEBUGIN(15);
string signame;
if( givenname.length () )
{ signame = givenname; } else { signame = sig.shortName (); }
if (givenname.length()) {
signame = givenname;
} else {
signame = sig.shortName();
}
string filename = rootdir + basename + signame + suffix;
dgDEBUG(5) << "Sig <"<<sig.getName ()
<< ">: new file "<< filename << endl;
std::ofstream * newfile = new std::ofstream( filename.c_str () );
dgDEBUG(5) << "Newfile:" << (void*) newfile << endl;
hardFiles.push_back( newfile );
dgDEBUG(5) << "Sig <" << sig.getName() << ">: new file " << filename << endl;
std::ofstream *newfile = new std::ofstream(filename.c_str());
if (!newfile->good()) {
delete newfile;
DG_THROW ExceptionTraces(
ExceptionTraces::NOT_OPEN,
"Could not open file " + filename + " for signal " + signame, "");
}
dgDEBUG(5) << "Newfile:" << (void *)newfile << endl;
hardFiles.push_back(newfile);
dgDEBUG(5) << "Creating Outstringstream" << endl;
//std::stringstream * newbuffer = new std::stringstream ();
OutStringStream * newbuffer = new OutStringStream (); // std::stringstream ();
newbuffer->resize( bufferSize );
// std::stringstream * newbuffer = new std::stringstream ();
OutStringStream *newbuffer = new OutStringStream(); // std::stringstream ();
newbuffer->resize(bufferSize);
newbuffer->givenname = givenname;
files.push_back( newbuffer );
files.push_back(newbuffer);
dgDEBUGOUT(15);
}
void TracerRealTime::
closeFiles ()
{
void TracerRealTime::closeFiles() {
dgDEBUGIN(15);
std::lock_guard<std::mutex> files_lock(files_mtx);
FileList::iterator iter = files.begin ();
HardFileList::iterator hardIter = hardFiles.begin ();
FileList::iterator iter = files.begin();
HardFileList::iterator hardIter = hardFiles.begin();
while( files.end ()!=iter )
{
dgDEBUG(25) << "Close the files." << endl;
while (files.end() != iter) {
dgDEBUG(25) << "Close the files." << endl;
std::stringstream * file = dynamic_cast< stringstream* >(*iter);
std::ofstream * hardFile = *hardIter;
std::stringstream *file = dynamic_cast<stringstream *>(*iter);
std::ofstream *hardFile = *hardIter;
(*hardFile) <<flush; hardFile->close ();
delete file;
delete hardFile;
(*hardFile) << flush;
hardFile->close();
delete file;
delete hardFile;
++iter; ++hardIter;
}
++iter;
++hardIter;
}
dgDEBUG(25) << "Clear the lists." << endl;
files.clear ();
hardFiles.clear ();
files.clear();
hardFiles.clear();
dgDEBUGOUT(15);
}
void TracerRealTime::
trace ()
{
void TracerRealTime::trace() {
dgDEBUGIN(15);
FileList::iterator iter = files.begin ();
HardFileList::iterator hardIter = hardFiles.begin ();
while( files.end ()!=iter )
{
dgDEBUG(35) << "Next" << endl;
std::ostream * os = *iter;
if( NULL==os )
{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"The buffer is null",""); }
//std::stringstream & file = * dynamic_cast< stringstream* >(os);
OutStringStream * file = dynamic_cast< OutStringStream* >(os); // segfault
if( NULL==file )
{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"The buffer is not open",""); }
std::ofstream & hardFile = **hardIter;
if(! hardFile.good () )
{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"The file is not open",""); }
if( (hardFile.good ())&&(NULL!=file) )
{
// const unsigned int SIZE = 1024*8;
// char buffer[SIZE];
// streambuf * pbuf = file.rdbuf ();
// pbuf->pubseekpos(0);
// const unsigned int NB_BYTE = pbuf->in_avail ();
// dgDEBUG(35) << "Bytes in buffer: " << NB_BYTE << endl;
// //dgDEBUG(35) << "Copie" <<endl<<file.str ()<< endl;
// for( unsigned int index=0;index<NB_BYTE;index+=SIZE )
// {
// pbuf->pubseekpos( index );
// int nget = pbuf->sgetn( buffer,SIZE );
// dgDEBUG(35) << "Copie ["<<nget<<"] " <<buffer<<endl;
// hardFile.write( buffer,nget );
// }
//hardFile << file.str () << flush;
//file.seekp(0);
file->dump( hardFile );
file->empty ();
hardFile.flush ();
//file.str("");
}
++iter; ++hardIter;
FileList::iterator iter = files.begin();
HardFileList::iterator hardIter = hardFiles.begin();
while (files.end() != iter) {
dgDEBUG(35) << "Next" << endl;
std::ostream *os = *iter;
if (NULL == os) {
DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is null",
"");
}
// std::stringstream & file = * dynamic_cast< stringstream* >(os);
OutStringStream *file = dynamic_cast<OutStringStream *>(os); // segfault
if (NULL == file) {
DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN,
"The buffer is not open", "");
}
std::ofstream &hardFile = **hardIter;
if (!hardFile.good()) {
DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN,
"The file is not open", "");
}
if ((hardFile.good()) && (NULL != file)) {
file->dump(hardFile);
file->empty();
hardFile.flush();
}
++iter;
++hardIter;
}
dgDEBUGOUT(15);
}
void TracerRealTime::
emptyBuffers ()
{
void TracerRealTime::emptyBuffers() {
dgDEBUGIN(15);
for( FileList::iterator iter = files.begin ();files.end ()!=iter;++iter )
{
//std::stringstream & file = * dynamic_cast< stringstream* >(*iter);
try {
OutStringStream & file = * dynamic_cast< OutStringStream* >(*iter);
file.empty ();
//file.str("");
}
catch( ... ) { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"The buffer is not open",""); }
for (FileList::iterator iter = files.begin(); files.end() != iter; ++iter) {
// std::stringstream & file = * dynamic_cast< stringstream* >(*iter);
try {
OutStringStream &file = *dynamic_cast<OutStringStream *>(*iter);
file.empty();
// file.str("");
} catch (...) {
DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN,
"The buffer is not open", "");
}
}
dgDEBUGOUT(15);
}
// void TracerRealTime::
// emptyBuffer( std::stringstream & file )
// {
// streambuf * pbuf = file.rdbuf ();
// pbuf->file.rdbuf () ->pubsetbuf( fileBuffer,10 );
// }
void TracerRealTime::
recordSignal( std::ostream& os,
const SignalBase<int>& sig )
{
void TracerRealTime::recordSignal(std::ostream &os,
const SignalBase<int> &sig) {
dgDEBUGIN(15);
try {
OutStringStream & file = dynamic_cast< OutStringStream& >(os);
OutStringStream &file = dynamic_cast<OutStringStream &>(os);
file.str("");
dgDEBUG(45) << "Empty file [" << file.tellp ()
<< "] <" << file.str ().c_str () <<"> " <<endl;
Tracer::recordSignal( file,sig );
file.addData( file.str ().c_str (),file.tellp () );
dgDEBUG(35) << "Write data [" << file.tellp ()
<< "] <" << file.str ().c_str () <<"> " <<endl;
} catch( ExceptionAbstract & exc ) { throw exc; }
catch( ... ) {
DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"The buffer is not open","");
dgDEBUG(45) << "Empty file [" << file.tellp() << "] <" << file.str().c_str()
<< "> " << endl;
Tracer::recordSignal(file, sig);
file.addData(file.str().c_str(), file.tellp());
dgDEBUG(35) << "Write data [" << file.tellp() << "] <" << file.str().c_str()
<< "> " << endl;
} catch (ExceptionAbstract &exc) {
throw;
} catch (...) {
DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN,
"The buffer is not open", "");
}
dgDEBUGOUT(15);
return ;
return;
}
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void TracerRealTime::
display( std::ostream& os ) const
{
os << CLASS_NAME << " " << name << " [mode=" << (play?"play":"pause")
<< "] : "<< endl
<< " - Dep list: "<<endl;
FileList::const_iterator iterFile = files.begin ();
for( SignalList::const_iterator iter = toTraceSignals.begin ();
toTraceSignals.end ()!=iter;++iter )
{
dgDEBUG(35) << "Next" << endl;
const OutStringStream * file = dynamic_cast< OutStringStream* >(*iterFile);
os << " -> "<<(*iter)->getName ();
if( file->givenname.length () ) os << " (in " << file->givenname << ")" ;
os << "\t";
if( file )
{
const std::streamsize PRECISION = os.precision ();
const std::streamsize SIZE = file->index;
const std::streamsize MSIZE = file->bufferSize;
unsigned int dec=0; std::string unit ="";
if( (SIZE>>30)||(MSIZE>>30) ) { dec = 30; unit="Go"; }
else if( (SIZE>>20)||(MSIZE>>20) ) { dec = 20; unit="Mo"; }
else if( (SIZE>>10)||(MSIZE>>10) ) { dec = 10; unit="Ko"; }
os << "[" << std::setw(1)<<std::setprecision(1)
<< (((double)SIZE+0.0)/(1<<dec)) << unit << "/"
<< std::setprecision(2)<<(((double)MSIZE+0.0)/(1<<dec))
<< unit << "]\t";
if( file->full ) os << "(FULL)";
os.precision(PRECISION);
}
os<<endl;
iterFile++;
void TracerRealTime::display(std::ostream &os) const {
os << CLASS_NAME << " " << name << " [mode=" << (play ? "play" : "pause")
<< "] : " << endl
<< " - Dep list: " << endl;
FileList::const_iterator iterFile = files.begin();
for (SignalList::const_iterator iter = toTraceSignals.begin();
toTraceSignals.end() != iter; ++iter) {
dgDEBUG(35) << "Next" << endl;
const OutStringStream *file = dynamic_cast<OutStringStream *>(*iterFile);
os << " -> " << (*iter)->getName();
if (file->givenname.length()) os << " (in " << file->givenname << ")";
os << "\t";
if (file) {
const std::streamsize PRECISION = os.precision();
const std::streamsize SIZE = file->index;
const std::streamsize MSIZE = file->bufferSize;
unsigned int dec = 0;
std::string unit = "";
if ((SIZE >> 30) || (MSIZE >> 30)) {
dec = 30;
unit = "Go";
} else if ((SIZE >> 20) || (MSIZE >> 20)) {
dec = 20;
unit = "Mo";
} else if ((SIZE >> 10) || (MSIZE >> 10)) {
dec = 10;
unit = "Ko";
}
os << "[" << std::setw(1) << std::setprecision(1)
<< (((double)SIZE + 0.0) / (1 << dec)) << unit << "/"
<< std::setprecision(2) << (((double)MSIZE + 0.0) / (1 << dec)) << unit
<< "]\t";
if (file->full) os << "(FULL)";
os.precision(PRECISION);
}
os << endl;
++iterFile;
}
}
std::ostream& operator<< ( std::ostream& os,const TracerRealTime& t )
{
std::ostream &operator<<(std::ostream &os, const TracerRealTime &t) {
t.display(os);
return os;
}
......@@ -12,115 +12,108 @@
/* --------------------------------------------------------------------- */
/* DG */
#include <dynamic-graph/tracer.h>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/value.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/tracer.h>
#include <dynamic-graph/value.h>
#include <boost/bind.hpp>
using namespace std;
using namespace dynamicgraph;
using namespace dynamicgraph::command;
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Tracer,"Tracer");
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Tracer, "Tracer");
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
Tracer::Tracer( const std::string n )
:Entity(n)
,toTraceSignals ()
,traceStyle(TRACE_STYLE_DEFAULT)
,frequency(1)
,basename ()
,suffix(".dat")
,rootdir ()
,namesSet( false )
,files ()
,names ()
,play(false)
,timeStart(0)
,triger( boost::bind(&Tracer::recordTrigger,this,_1,_2),
sotNOSIGNAL,
"Tracer("+n+")::triger" )
{
signalRegistration( triger );
Tracer::Tracer(const std::string n)
: Entity(n),
toTraceSignals(),
traceStyle(TRACE_STYLE_DEFAULT),
frequency(1),
basename(),
suffix(".dat"),
rootdir(),
namesSet(false),
files(),
names(),
play(false),
timeStart(0),
triger(boost::bind(&Tracer::recordTrigger, this, _1, _2), sotNOSIGNAL,
"Tracer(" + n + ")::triger") {
signalRegistration(triger);
/* --- Commands --- */
{
using namespace dynamicgraph::command;
std::string doc;
doc = docCommandVoid2("Add a new signal to trace.",
"string (signal name)","string (filename, empty for default");
doc = docCommandVoid2("Add a new signal to trace.", "string (signal name)",
"string (filename, empty for default");
addCommand("add",
makeCommandVoid2(*this,&Tracer::addSignalToTraceByName,doc ));
makeCommandVoid2(*this, &Tracer::addSignalToTraceByName, doc));
doc = docCommandVoid0("Remove all signals. If necessary, close open files.");
doc =
docCommandVoid0("Remove all signals. If necessary, close open files.");
addCommand("clear",
makeCommandVoid0(*this,&Tracer::clearSignalToTrace,doc ));
makeCommandVoid0(*this, &Tracer::clearSignalToTrace, doc));
doc = docCommandVoid3("Gives the args for file opening, and "
"if signals have been set, open the corresponding files.",
"string (dirname)","string (prefix)","string (suffix)");
addCommand("open",
makeCommandVoid3(*this,&Tracer::openFiles,doc ));
doc = docCommandVoid3(
"Gives the args for file opening, and "
"if signals have been set, open the corresponding files.",
"string (dirname)", "string (prefix)", "string (suffix)");
addCommand("open", makeCommandVoid3(*this, &Tracer::openFiles, doc));
doc = docCommandVoid0("Close all the open files.");
addCommand("close",
makeCommandVoid0(*this,&Tracer::closeFiles,doc ));
addCommand("close", makeCommandVoid0(*this, &Tracer::closeFiles, doc));
doc = docCommandVoid0("If necessary, dump "
"(can be done automatically for some traces type).");
addCommand("dump",
makeCommandVoid0(*this,&Tracer::trace,doc ));
doc = docCommandVoid0(
"If necessary, dump "
"(can be done automatically for some traces type).");
addCommand("dump", makeCommandVoid0(*this, &Tracer::trace, doc));
doc = docCommandVoid0("Start the tracing process.");
addCommand("start",
makeCommandVoid0(*this,&Tracer::start,doc ));
addCommand("start", makeCommandVoid0(*this, &Tracer::start, doc));
doc = docCommandVoid0("Stop temporarily the tracing process.");
addCommand("stop",
makeCommandVoid0(*this,&Tracer::stop,doc ));
addCommand("stop", makeCommandVoid0(*this, &Tracer::stop, doc));
addCommand("getTimeStart",
makeDirectGetter(*this,&timeStart,
docDirectGetter("timeStart","int")));
makeDirectGetter(*this, &timeStart,
docDirectGetter("timeStart", "int")));
addCommand("setTimeStart",
makeDirectSetter(*this,&timeStart,
docDirectSetter("timeStart","int")));
} // using namespace command
makeDirectSetter(*this, &timeStart,
docDirectSetter("timeStart", "int")));
} // using namespace command
}
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void Tracer::
addSignalToTrace( const SignalBase<int>& sig,
const string& filename )
{
void Tracer::addSignalToTrace(const SignalBase<int> &sig,
const string &filename) {
dgDEBUGIN(15);
toTraceSignals.push_back( &sig ); dgDEBUGF(15,"%p",&sig);
names.push_back( filename );
if( namesSet ) openFile( sig,filename );
triger.addDependency( sig );
// openFile may throw so it should be called first.
if (namesSet) openFile(sig, filename);
toTraceSignals.push_back(&sig);
dgDEBUGF(15, "%p", &sig);
names.push_back(filename);
triger.addDependency(sig);
dgDEBUGOUT(15);
}
void Tracer::
addSignalToTraceByName( const string& signame,
const string& filename )
{
void Tracer::addSignalToTraceByName(const string &signame,
const string &filename) {
dgDEBUGIN(15);
istringstream iss( signame );
istringstream iss(signame);
SignalBase<int> &sig = PoolStorage::getInstance()->getSignal(iss);
addSignalToTrace(sig,filename);
addSignalToTrace(sig, filename);
dgDEBUGOUT(15);
}
......@@ -128,12 +121,10 @@ addSignalToTraceByName( const string& signame,
* does not modify the file list (it does not close
* the files in particular.
*/
void Tracer::
clearSignalToTrace ()
{
closeFiles ();
toTraceSignals.clear ();
triger.clearDependencies ();
void Tracer::clearSignalToTrace() {
closeFiles();
toTraceSignals.clear();
triger.clearDependencies();
}
// void Tracer::
......@@ -142,63 +133,59 @@ clearSignalToTrace ()
// triger.parasite(sig);
// }
void Tracer::
openFiles( const std::string& rootdir_, const std::string& basename_,
const std::string& suffix_ )
{
void Tracer::openFiles(const std::string &rootdir_,
const std::string &basename_,
const std::string &suffix_) {
dgDEBUGIN(15);
std::basic_string<char>::size_type n = rootdir_.length ();
std::basic_string<char>::size_type n = rootdir_.length();
rootdir = rootdir_;
if( (0<n)&('/'!=rootdir[n-1]) ) rootdir+='/';
if ((0 < n) & ('/' != rootdir[n - 1])) rootdir += '/';
basename=basename_;
suffix=suffix_;
basename = basename_;
suffix = suffix_;
if( files.size () ) closeFiles ();
if (files.size()) closeFiles();
SignalList::const_iterator iter = toTraceSignals.begin ();
NameList::const_iterator iterName = names.begin ();
while( toTraceSignals.end ()!=iter )
{
dgDEBUG(15) << "Open <" << (*iter)->getName ()
<< "> in <" << *iterName << ">." << std::endl;
openFile( **iter,*iterName );
++iter; ++iterName;
}
SignalList::const_iterator iter = toTraceSignals.begin();
NameList::const_iterator iterName = names.begin();
while (toTraceSignals.end() != iter) {
dgDEBUG(15) << "Open <" << (*iter)->getName() << "> in <" << *iterName
<< ">." << std::endl;
openFile(**iter, *iterName);
++iter;
++iterName;
}
namesSet = true;
dgDEBUGOUT(15);
}
void Tracer::
openFile( const SignalBase<int> & sig,
const string& givenname )
{
void Tracer::openFile(const SignalBase<int> &sig, const string &givenname) {
dgDEBUGIN(15);
string signame;
if( givenname.length () )
{ signame = givenname; } else { signame = sig.shortName (); }
if (givenname.length()) {
signame = givenname;
} else {
signame = sig.shortName();
}
string filename = rootdir + basename + signame + suffix;
dgDEBUG(5) << "Sig <"<< sig.getName () << ">: new file "<< filename << endl;
std::ofstream * newfile = new std::ofstream( filename.c_str () );
files.push_back( newfile );
dgDEBUG(5) << "Sig <" << sig.getName() << ">: new file " << filename << endl;
std::ofstream *newfile = new std::ofstream(filename.c_str());
files.push_back(newfile);
dgDEBUGOUT(15);
}
void Tracer::
closeFiles ()
{
void Tracer::closeFiles() {
dgDEBUGIN(15);
std::lock_guard<std::mutex> files_lock(files_mtx);
for( FileList::iterator iter = files.begin ();files.end ()!=iter;++iter )
{
std::ostream * filePtr = *iter;
delete filePtr;
}
files.clear ();
for (FileList::iterator iter = files.begin(); files.end() != iter; ++iter) {
std::ostream *filePtr = *iter;
delete filePtr;
}
files.clear();
dgDEBUGOUT(15);
}
......@@ -207,85 +194,83 @@ closeFiles ()
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void Tracer::
record ()
{
if(! play) { dgDEBUGINOUT(15); return;}
void Tracer::record() {
if (!play) {
dgDEBUGINOUT(15);
return;
}
dgDEBUGIN(15);
if( files.size ()!=toTraceSignals.size () )
{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
"No files open for tracing"," (file=%d != %d=sig).",
files.size (),toTraceSignals.size ()); }
// Ensure record() never hangs. If the attempt to acquire the lock fails,
// then closeFiles() is active and we shouldn't write to files anyways.
std::unique_lock<std::mutex> files_lock(files_mtx, std::try_to_lock);
if (!files_lock.owns_lock()) {
dgDEBUGOUT(15);
return;
}
if (files.size() != toTraceSignals.size()) {
DG_THROW
ExceptionTraces(ExceptionTraces::NOT_OPEN, "No files open for tracing",
" (file=%d != %d=sig).", files.size(),
toTraceSignals.size());
}
FileList::iterator iterFile = files.begin ();
SignalList::iterator iterSig = toTraceSignals.begin ();
FileList::iterator iterFile = files.begin();
SignalList::iterator iterSig = toTraceSignals.begin();
while( toTraceSignals.end ()!=iterSig )
{
dgDEBUG(45) << "Try..." <<endl;
recordSignal( **iterFile,**iterSig );
++iterSig; ++iterFile;
}
while (toTraceSignals.end() != iterSig) {
dgDEBUG(45) << "Try..." << endl;
recordSignal(**iterFile, **iterSig);
++iterSig;
++iterFile;
}
dgDEBUGOUT(15);
}
void Tracer::
recordSignal( std::ostream& os,
const SignalBase<int>& sig )
{
void Tracer::recordSignal(std::ostream &os, const SignalBase<int> &sig) {
dgDEBUGIN(15);
try {
if( sig.getTime ()>timeStart )
{
os<< sig.getTime () << "\t";
sig.trace(os); os<<endl;
}
if (sig.getTime() > timeStart) {
os << sig.getTime() << "\t";
sig.trace(os);
os << endl;
}
} catch (ExceptionAbstract &exc) {
os << exc << std::endl;
} catch (...) {
os << "Unknown error occurred while reading signal." << std::endl;
}
catch( ExceptionAbstract& exc ) { os << exc << std::endl; }
catch( ... ) { os << "Unknown error occurred while reading signal." << std::endl; }
dgDEBUGOUT(15);
dgDEBUGOUT(15);
}
int& Tracer::
recordTrigger( int& dummy, const int& time )
{
dgDEBUGIN(15) << " time="<<time <<endl;
record ();
int &Tracer::recordTrigger(int &dummy, const int &time) {
dgDEBUGIN(15) << " time=" << time << endl;
record();
dgDEBUGOUT(15);
return dummy;
}
void Tracer::
trace ()
{
}
void Tracer::trace() {}
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
void Tracer::
display( std::ostream& os ) const
{
os << CLASS_NAME << " " << name << " [mode=" << (play?"play":"pause")
<< "] : "<< endl
<< " - Dep list: "<<endl;
for( SignalList::const_iterator iter = toTraceSignals.begin ();
toTraceSignals.end ()!=iter;++iter )
{ os << " -> "<<(*iter)->getName ()<<endl; }
void Tracer::display(std::ostream &os) const {
os << CLASS_NAME << " " << name << " [mode=" << (play ? "play" : "pause")
<< "] : " << endl
<< " - Dep list: " << endl;
for (SignalList::const_iterator iter = toTraceSignals.begin();
toTraceSignals.end() != iter; ++iter) {
os << " -> " << (*iter)->getName() << endl;
}
}
std::ostream& operator<< ( std::ostream& os,const Tracer& t )
{
std::ostream &operator<<(std::ostream &os, const Tracer &t) {
t.display(os);
return os;
}
# Copyright 2010, Olivier Stasse, JRL, CNRS/AIST
#
# Copyright 2010-2020, Olivier Stasse, Guilhem Saurel, JRL, CNRS/AIST, LAAS-CNRS
ADD_DEFINITIONS(-DDEBUG=2)
add_definitions(-DBOOST_TEST_DYN_LINK -DBOOST_TEST_MAIN)
# Add Boost path to include directories.
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
# Make Boost.Test generates the main function in test cases.
ADD_DEFINITIONS(-DBOOST_TEST_DYN_LINK -DBOOST_TEST_MAIN)
ADD_DEFINITIONS(-DTESTS_DATADIR="${CMAKE_CURRENT_SOURCE_DIR}/data")
ADD_DEFINITIONS(-DTESTS_PLUGINDIR="${LIBRARY_OUTPUT_PATH}")
ADD_DEFINITIONS(-DTESTS_DYNLIBSUFFIX="${CMAKE_SHARED_LIBRARY_SUFFIX}")
# DYNAMIC_GRAPH_TEST(NAME)
# ------------------------
#
# Define a test named `NAME'.
#
# This macro will create a binary from `NAME.cpp', link it against
# Boost and add it to the test suite.
#
MACRO(DYNAMIC_GRAPH_TEST NAME)
ADD_EXECUTABLE(${NAME} ${NAME}.cpp)
ADD_TEST(${NAME} ${RUNTIME_OUTPUT_DIRECTORY}/${NAME})
TARGET_LINK_LIBRARIES(${NAME} ${PROJECT_NAME})
ADD_DEPENDENCIES(${NAME} ${PROJECT_NAME})
# Link against Boost.
TARGET_LINK_LIBRARIES(${NAME} ${Boost_LIBRARIES})
ENDMACRO(DYNAMIC_GRAPH_TEST)
add_definitions(-DTESTS_DATADIR="${CMAKE_CURRENT_SOURCE_DIR}/data")
add_definitions(-DTESTS_PLUGINDIR="${LIBRARY_OUTPUT_PATH}")
add_definitions(-DTESTS_DYNLIBSUFFIX="${CMAKE_SHARED_LIBRARY_SUFFIX}")
macro(DYNAMIC_GRAPH_TEST NAME)
add_unit_test(${NAME} "${NAME}.cpp")
target_link_libraries(${NAME} PRIVATE ${PROJECT_NAME}
Boost::unit_test_framework)
endmacro(DYNAMIC_GRAPH_TEST)
# Signal cast test.
SET(signalcast_libs signal-cast-registerer-libA signal-cast-registerer-libB)
set(signalcast_libs signal-cast-registerer-libA signal-cast-registerer-libB)
FOREACH(lib ${signalcast_libs})
ADD_LIBRARY(${lib} SHARED ${lib}.cpp)
foreach(lib ${signalcast_libs})
add_library(${lib} SHARED "${lib}.cpp")
target_link_libraries(${lib} PRIVATE ${PROJECT_NAME})
endforeach()
TARGET_LINK_LIBRARIES(${lib} ${PROJECT_NAME})
ADD_DEPENDENCIES(${lib} ${PROJECT_NAME})
ENDFOREACH()
DYNAMIC_GRAPH_TEST(signal-cast-registerer)
dynamic_graph_test(signal-cast-registerer)
# Unit testing.
IF(NOT APPLE)
DYNAMIC_GRAPH_TEST(entity)
ENDIF(NOT APPLE)
DYNAMIC_GRAPH_TEST(custom-entity)
DYNAMIC_GRAPH_TEST(factory)
DYNAMIC_GRAPH_TEST(pool)
DYNAMIC_GRAPH_TEST(signal-time-dependent)
DYNAMIC_GRAPH_TEST(value)
DYNAMIC_GRAPH_TEST(signal-ptr)
DYNAMIC_GRAPH_TEST(real-time-logger)
DYNAMIC_GRAPH_TEST(debug-trace)
DYNAMIC_GRAPH_TEST(debug-tracer)
TARGET_LINK_LIBRARIES(debug-tracer tracer)
DYNAMIC_GRAPH_TEST(debug-logger)
DYNAMIC_GRAPH_TEST(debug-logger-winit)
if(NOT APPLE)
dynamic_graph_test(entity)
endif(NOT APPLE)
dynamic_graph_test(custom-entity)
dynamic_graph_test(factory)
dynamic_graph_test(pool)
dynamic_graph_test(signal-time-dependent)
dynamic_graph_test(value)
dynamic_graph_test(signal-ptr)
dynamic_graph_test(real-time-logger)
dynamic_graph_test(debug-trace)
dynamic_graph_test(debug-tracer)
target_link_libraries(debug-tracer PRIVATE tracer)
dynamic_graph_test(debug-real-time-tracer)
target_link_libraries(debug-real-time-tracer PRIVATE tracer-real-time tracer)
dynamic_graph_test(debug-logger)
dynamic_graph_test(debug-logger-winit)
dynamic_graph_test(signal-all)
dynamic_graph_test(command-test)
dynamic_graph_test(test-mt)
target_link_libraries(test-mt PRIVATE tracer)
dynamic_graph_test(exceptions)
/* Copyright 2019, LAAS-CNRS
*
* Olivier Stasse
*
* See LICENSE file
*
*/
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <iostream>
#include <sstream>
#include "dynamic-graph/command-bind.h"
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
#define ENABLE_RT_LOG
#include <dynamic-graph/logger.h>
#include <dynamic-graph/real-time-logger.h>
#define BOOST_TEST_MODULE debug - logger
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
using namespace dynamicgraph::command;
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
static const std::string CLASS_NAME;
bool test_zero_arg_;
bool test_one_arg_;
bool test_two_args_;
bool test_three_args_;
bool test_four_args_;
bool test_one_arg_ret_;
bool test_two_args_ret_;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n) : Entity(n) {
test_zero_arg_ = false;
test_one_arg_ = false;
test_two_args_ = false;
test_three_args_ = false;
test_four_args_ = false;
test_one_arg_ret_ = false;
test_two_args_ret_ = false;
addCommand("0_arg", makeCommandVoid0(*this, &CustomEntity::zero_arg,
docCommandVoid0("zero arg")));
addCommand("1_arg", makeCommandVoid1(*this, &CustomEntity::one_arg,
docCommandVoid1("one arg", "int")));
addCommand("2_args",
makeCommandVoid2(*this, &CustomEntity::two_args,
docCommandVoid2("two args", "int", "int")));
addCommand("3_args", makeCommandVoid3(*this, &CustomEntity::three_args,
docCommandVoid3("three args", "int",
"int", "int")));
addCommand("4_args",
makeCommandVoid4(
*this, &CustomEntity::four_args,
docCommandVoid4("four args", "int", "int", "int", "int")));
addCommand("1_arg_r",
makeCommandReturnType1(*this, &CustomEntity::one_arg_ret,
docCommandVoid1("one arg", "int")));
addCommand("2_args_r", makeCommandReturnType2(
*this, &CustomEntity::two_args_ret,
docCommandVoid2("two args", "int", "int")));
addCommand(
"cmd_verbose",
makeCommandVerbose(*this, &CustomEntity::cmd_verbose,
docCommandVerbose("Display some information")));
/// Generating an exception by adding a command which already exist
bool res = false;
std::string e_1_arg("1_arg");
try {
addCommand(e_1_arg, getNewStyleCommand(e_1_arg));
} catch (dynamicgraph::ExceptionFactory &aef) {
res = (aef.getCode() == dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
BOOST_CHECK(res);
}
~CustomEntity() {}
void zero_arg() { test_zero_arg_ = true; }
void one_arg(const int &) { test_one_arg_ = true; }
void two_args(const int &, const int &) { test_two_args_ = true; }
void three_args(const int &, const int &, const int &) {
test_three_args_ = true;
}
void four_args(const int &, const int &, const int &, const int &) {
test_four_args_ = true;
}
int one_arg_ret(const int &) {
test_one_arg_ret_ = true;
return 2;
}
std::string two_args_ret(const int &, const int &) {
test_two_args_ret_ = true;
return std::string("return");
}
void cmd_verbose(std::ostream &oss) {
std::string as("print verbose");
oss << as;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(command_test) {
dynamicgraph::CustomEntity *ptr_entity =
(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity")));
dynamicgraph::CustomEntity &entity = *ptr_entity;
std::map<const std::string, Command *> aCommandMap =
entity.getNewStyleCommandMap();
std::map<const std::string, Command *>::iterator it_map;
it_map = aCommandMap.find("0_arg");
if (it_map == aCommandMap.end()) BOOST_CHECK(false);
it_map->second->execute();
BOOST_CHECK(entity.test_zero_arg_);
int first_arg = 1;
Value aValue(first_arg);
std::vector<std::string> vec_fname(4);
vec_fname[0] = "1_arg";
vec_fname[1] = "2_args";
vec_fname[2] = "3_args";
vec_fname[3] = "4_args";
std::vector<Value> values;
for (unsigned int i = 0; i < 4; i++) {
it_map = aCommandMap.find(vec_fname[i]);
if (it_map == aCommandMap.end()) BOOST_CHECK(false);
values.push_back(aValue);
it_map->second->setParameterValues(values);
it_map->second->execute();
it_map->second->owner();
it_map->second->getDocstring();
}
BOOST_CHECK(entity.test_one_arg_);
BOOST_CHECK(entity.test_two_args_);
BOOST_CHECK(entity.test_three_args_);
BOOST_CHECK(entity.test_four_args_);
// With return type.
vec_fname.clear();
vec_fname.push_back(std::string("1_arg_r"));
vec_fname.push_back(std::string("2_args_r"));
values.clear();
for (unsigned int i = 0; i < 2; i++) {
it_map = aCommandMap.find(vec_fname[i]);
if (it_map == aCommandMap.end()) {
BOOST_CHECK(false);
exit(-1);
}
values.push_back(aValue);
it_map->second->setParameterValues(values);
Value aValue = it_map->second->execute();
it_map->second->owner();
it_map->second->getDocstring();
}
BOOST_CHECK(entity.test_one_arg_ret_);
BOOST_CHECK(entity.test_two_args_ret_);
std::vector<Value> values_two;
values_two.push_back(aValue);
/// Wrong number of arguments
bool res = false;
it_map = aCommandMap.find(std::string("2_args"));
try {
it_map->second->setParameterValues(values_two);
} catch (const dynamicgraph::ExceptionAbstract &aea) {
res = (aea.getCode() == dynamicgraph::ExceptionAbstract::ABSTRACT);
}
BOOST_CHECK(res);
double snd_arg_db = 10.0;
Value aValue2(snd_arg_db);
values_two.push_back(aValue2);
/// Wrong types of arguments
res = false;
it_map = aCommandMap.find(std::string("2_args"));
try {
it_map->second->setParameterValues(values_two);
} catch (const dynamicgraph::ExceptionAbstract &aea) {
res = (aea.getCode() == dynamicgraph::ExceptionAbstract::TOOLS);
}
BOOST_CHECK(res);
/// Try to find the command 1_arg
res = false;
entity.getNewStyleCommand(vec_fname[0]);
BOOST_CHECK(true);
/// Generate an exception by searching a command with an empty name.w
std::string empty("");
try {
entity.getNewStyleCommand(empty);
} catch (dynamicgraph::ExceptionFactory &aef) {
res = (aef.getCode() == dynamicgraph::ExceptionFactory::UNREFERED_FUNCTION);
}
BOOST_CHECK(res);
/// delete the entity.
delete ptr_entity;
}
// Copyright 2010 Thomas Moulard.
//
#include <sstream>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <sstream>
#define BOOST_TEST_MODULE customEntity
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
struct CustomEntity : public dynamicgraph::Entity
{
struct CustomEntity : public dynamicgraph::Entity {
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
virtual const std::string &getClassName() const { return CLASS_NAME; }
CustomEntity (const std::string n)
: Entity (n)
{
}
explicit CustomEntity(const std::string &n) : Entity(n) {}
virtual ~CustomEntity()
{
}
void display (std::ostream& os) const
{
os << "custom entity";
}
virtual ~CustomEntity() {}
void display(std::ostream &os) const { os << "custom entity"; }
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
BOOST_AUTO_TEST_CASE (constructor)
{
BOOST_CHECK_EQUAL (CustomEntity::CLASS_NAME, "CustomEntity");
BOOST_AUTO_TEST_CASE(constructor) {
BOOST_CHECK_EQUAL(CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::Entity* entity =
dynamicgraph::FactoryStorage::getInstance()->
newEntity("CustomEntity", "my-entity");
BOOST_CHECK_EQUAL (entity->getName (), "my-entity");
BOOST_CHECK_EQUAL (entity->getClassName (), CustomEntity::CLASS_NAME);
dynamicgraph::Entity *entity =
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity");
BOOST_CHECK_EQUAL(entity->getName(), "my-entity");
BOOST_CHECK_EQUAL(entity->Entity::getClassName(), "Entity");
BOOST_CHECK_EQUAL(entity->getClassName(), CustomEntity::CLASS_NAME);
//CustomEntity entity2 ("");
// CustomEntity entity2 ("");
// Deregister entities before destroying them
dynamicgraph::PoolStorage::destroy();
}
BOOST_AUTO_TEST_CASE (display)
{
dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()->
newEntity("CustomEntity", "my-entity");
BOOST_AUTO_TEST_CASE(display) {
dynamicgraph::Entity *entity =
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity");
output_test_stream output;
entity->display(output);
BOOST_CHECK (output.is_equal ("custom entity"));
BOOST_CHECK(output.is_equal("custom entity"));
// Deregister entities before destroying them
dynamicgraph::PoolStorage::destroy();
}
......@@ -5,83 +5,78 @@
* See LICENSE file
*
*/
#include <sstream>
#include <iostream>
#include <sstream>
#define ENABLE_RT_LOG
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/logger.h>
#include <dynamic-graph/real-time-logger.h>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
#define ENABLE_RT_LOG
#include <dynamic-graph/real-time-logger.h>
#include <dynamic-graph/logger.h>
#define BOOST_TEST_MODULE debug-logger
#define BOOST_TEST_MODULE debug - logger
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread/thread.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n) : Entity(n) {
logger_.setTimeSample(0.001);
logger_.setStreamPrintPeriod(0.005);
logger_.setVerbosity(VERBOSITY_ALL);
LoggerVerbosity alv = logger_.getVerbosity();
BOOST_CHECK(alv == VERBOSITY_ALL);
}
namespace dynamicgraph
{
class CustomEntity : public Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
CustomEntity (const std::string n)
: Entity (n)
{
logger_.setTimeSample(0.001);
logger_.setStreamPrintPeriod(0.005);
logger_.setVerbosity(VERBOSITY_ALL);
LoggerVerbosity alv = logger_.getVerbosity();
BOOST_CHECK(alv==VERBOSITY_ALL);
}
~CustomEntity()
{
}
void testDebugTrace()
{
sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG);
sendMsg("This is a message of level MSG_TYPE_INFO",MSG_TYPE_INFO);
sendMsg("This is a message of level MSG_TYPE_WARNING",MSG_TYPE_WARNING);
sendMsg("This is a message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR);
sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM);
sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM);
sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM);
sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM);
~CustomEntity() {}
void testDebugTrace() {
sendMsg("This is a message of level MSG_TYPE_DEBUG", MSG_TYPE_DEBUG);
sendMsg("This is a message of level MSG_TYPE_INFO", MSG_TYPE_INFO);
sendMsg("This is a message of level MSG_TYPE_WARNING", MSG_TYPE_WARNING);
sendMsg("This is a message of level MSG_TYPE_ERROR", MSG_TYPE_ERROR);
sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",
MSG_TYPE_DEBUG_STREAM);
sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",
MSG_TYPE_INFO_STREAM);
sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",
MSG_TYPE_WARNING_STREAM);
sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",
MSG_TYPE_ERROR_STREAM);
logger_.countdown();
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
}
logger_.countdown();
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization)
{
std::ofstream of;
BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization) {
dynamicgraph::RealTimeLogger::instance();
//of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app);
// dgADD_OSTREAM_TO_RTLOG (of);
BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity-2")));
dynamicgraph::CustomEntity &entity =
*(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity(
"CustomEntity", "my-entity-2")));
for(unsigned int i=0;i<10000;i++)
{
entity.testDebugTrace();
}
for (unsigned int i = 0; i < 1000; i++) {
entity.testDebugTrace();
}
dynamicgraph::RealTimeLogger::destroy();
}
......@@ -5,83 +5,148 @@
* See LICENSE file
*
*/
#include <sstream>
#include <iostream>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <iostream>
#include <sstream>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
#define ENABLE_RT_LOG
#include <dynamic-graph/real-time-logger.h>
#include <dynamic-graph/logger.h>
#include <dynamic-graph/real-time-logger.h>
#define BOOST_TEST_MODULE debug-logger
#define BOOST_TEST_MODULE debug - logger
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n) : Entity(n) {
logger_.setTimeSample(0.001);
logger_.setStreamPrintPeriod(0.005);
namespace dynamicgraph
{
class CustomEntity : public Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
CustomEntity (const std::string n)
: Entity (n)
{
logger_.setTimeSample(0.001);
logger_.setStreamPrintPeriod(0.005);
logger_.setVerbosity(VERBOSITY_ALL);
LoggerVerbosity alv = logger_.getVerbosity();
BOOST_CHECK(alv==VERBOSITY_ALL);
}
~CustomEntity()
{
}
void testDebugTrace()
{
sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG);
sendMsg("This is a message of level MSG_TYPE_INFO",MSG_TYPE_INFO);
sendMsg("This is a message of level MSG_TYPE_WARNING",MSG_TYPE_WARNING);
sendMsg("This is a message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR);
sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM);
sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM);
sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM);
sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM);
logger_.countdown();
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
}
logger_.setVerbosity(VERBOSITY_NONE);
BOOST_CHECK_EQUAL(logger_.getVerbosity(), VERBOSITY_NONE);
BOOST_CHECK(logger_.stream(MSG_TYPE_DEBUG).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_INFO).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_WARNING).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_ERROR).isNull());
logger_.setVerbosity(VERBOSITY_ERROR);
BOOST_CHECK_EQUAL(logger_.getVerbosity(), VERBOSITY_ERROR);
BOOST_CHECK(logger_.stream(MSG_TYPE_DEBUG).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_INFO).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_WARNING).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_ERROR).isNull());
logger_.setVerbosity(VERBOSITY_WARNING_ERROR);
BOOST_CHECK_EQUAL(logger_.getVerbosity(), VERBOSITY_WARNING_ERROR);
BOOST_CHECK(logger_.stream(MSG_TYPE_DEBUG).isNull());
BOOST_CHECK(logger_.stream(MSG_TYPE_INFO).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_WARNING).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_ERROR).isNull());
BOOST_AUTO_TEST_CASE(debug_logger)
{
logger_.setVerbosity(VERBOSITY_INFO_WARNING_ERROR);
BOOST_CHECK_EQUAL(logger_.getVerbosity(), VERBOSITY_INFO_WARNING_ERROR);
BOOST_CHECK(logger_.stream(MSG_TYPE_DEBUG).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_INFO).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_WARNING).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_ERROR).isNull());
logger_.setVerbosity(VERBOSITY_ALL);
BOOST_CHECK_EQUAL(logger_.getVerbosity(), VERBOSITY_ALL);
BOOST_CHECK(!logger_.stream(MSG_TYPE_DEBUG).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_INFO).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_WARNING).isNull());
BOOST_CHECK(!logger_.stream(MSG_TYPE_ERROR).isNull());
}
~CustomEntity() {}
void testDebugTrace() {
logger_.stream(MSG_TYPE_DEBUG)
<< "This is a message of level MSG_TYPE_DEBUG\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_INFO)
<< "This is a message of level MSG_TYPE_INFO\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_WARNING)
<< "This is a message of level MSG_TYPE_WARNING\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_ERROR)
<< "This is a message of level MSG_TYPE_ERROR\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_DEBUG_STREAM)
<< "This is a message of level MSG_TYPE_DEBUG_STREAM\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_INFO_STREAM)
<< "This is a message of level MSG_TYPE_INFO_STREAM\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_WARNING_STREAM)
<< "This is a message of level MSG_TYPE_WARNING_STREAM\n";
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_ERROR_STREAM)
<< "This is a message of level MSG_TYPE_ERROR_STREAM\n";
/* Add test toString */
dynamicgraph::RealTimeLogger::instance().spinOnce();
double q = 1.0;
logger_.stream() << "Value to display: " + toString(q) << '\n';
dynamicgraph::RealTimeLogger::instance().spinOnce();
std::vector<double> vq;
vq.resize(3);
vq[0] = 1.0;
vq[1] = 2.0;
vq[2] = 3.0;
logger_.stream(MSG_TYPE_INFO)
<< "Value to display: " << toString(vq) << '\n';
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.stream(MSG_TYPE_INFO)
<< "Value to display: " << toString(vq, 3, 10) << '\n';
dynamicgraph::RealTimeLogger::instance().spinOnce();
Eigen::Matrix<double, 3, 3> an_eig_m;
an_eig_m.setOnes();
logger_.stream(MSG_TYPE_INFO)
<< "Value to display: " << toString(an_eig_m) << '\n';
dynamicgraph::RealTimeLogger::instance().spinOnce();
logger_.countdown();
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(debug_logger) {
std::ofstream of;
dynamicgraph::RealTimeLogger::instance();
of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app);
dgADD_OSTREAM_TO_RTLOG (of);
of.open("/tmp/dg-LOGS.txt", std::ofstream::out | std::ofstream::app);
dgADD_OSTREAM_TO_RTLOG(of);
BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::CustomEntity &entity =
*(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity")));
dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity")));
entity.setTimeSample(0.002);
BOOST_CHECK_EQUAL(entity.getTimeSample(), 0.002);
entity.setStreamPrintPeriod(0.002);
BOOST_CHECK_EQUAL(entity.getStreamPrintPeriod(), 0.002);
for(unsigned int i=0;i<10000;i++)
{
entity.testDebugTrace();
}
for (unsigned int i = 0; i < 10000; i++) {
entity.testDebugTrace();
}
dynamicgraph::RealTimeLogger::destroy();
}
/* Copyright 2019, LAAS-CNRS
*
* Olivier Stasse
*
*/
#include <dynamic-graph/command.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <dynamic-graph/tracer-real-time.h>
#include <iostream>
#define BOOST_TEST_MODULE debug - tracer
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph {
struct MyEntity : public dynamicgraph::Entity {
static const std::string CLASS_NAME;
dynamicgraph::Signal<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTwoTimeDepSOUT;
explicit MyEntity(const std::string &name)
: Entity(name),
m_sigdSIN("MyEntity(" + name + ")::input(double)::in_double"),
m_sigdTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2),
m_sigdSIN,
"MyEntity(" + name + ")::input(double)::out_double"),
m_sigdTwoTimeDepSOUT(
boost::bind(&MyEntity::update, this, _1, _2), m_sigdSIN,
"MyEntity(" + name + ")::input(double)::out2double")
{
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT << m_sigdTwoTimeDepSOUT);
}
double &update(double &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(test_tracer) {
using namespace dynamicgraph;
// Creates a tracer.
TracerRealTime &atracer = *dynamic_cast<TracerRealTime *>(
FactoryStorage::getInstance()->newEntity("TracerRealTime", "my-tracer"));
MyEntity &entity = *dynamic_cast<MyEntity *>(
FactoryStorage::getInstance()->newEntity("MyEntity", "my-entity"));
std::string rootdir("/tmp");
std::string basename("my-tracer");
std::string suffix(".dat");
atracer.setBufferSize(1 << 14);
// Check that an exception is thrown if the filename is invalid.
atracer.openFiles(rootdir, "invalid/filename", suffix);
BOOST_CHECK_THROW(
atracer.addSignalToTraceByName("my-entity.out_double", "output"),
ExceptionTraces);
// Test openfiles
atracer.openFiles(rootdir, basename, suffix);
// Add trace by name
atracer.addSignalToTraceByName("my-entity.out_double", "output");
/// Add trace by name
SignalBase<int> &out_double = entity.getSignal("out_double");
SignalBase<int> &out_double_2 = entity.getSignal("out2double");
Signal<double, int> &in_double =
*(dynamic_cast<Signal<double, int> *>(&entity.getSignal("in_double")));
in_double.setConstant(1.5);
atracer.start();
std::string emptybuf_cmd_str("empty");
command::Command *acmd = atracer.getNewStyleCommand(emptybuf_cmd_str);
acmd->execute();
for (int i = 0; i < 1000; i++) {
in_double.setTime(i);
out_double.recompute(i);
out_double_2.recompute(i);
atracer.recordTrigger(i, i);
}
output_test_stream output;
atracer.display(output);
atracer.stop();
atracer.trace();
atracer.clearSignalToTrace();
atracer.closeFiles();
acmd->execute();
atracer.record();
BOOST_CHECK(output.is_equal(
"TracerRealTime my-tracer [mode=play] : \n"
" - Dep list: \n"
" -> MyEntity(my-entity)::input(double)::out_double (in output)"
" [8Ko/16Ko] \n"));
}
......@@ -3,10 +3,12 @@
* Olivier Stasse
*
*/
#include <sstream>
#include <iostream>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <iostream>
#include <sstream>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
......@@ -14,89 +16,83 @@
#define VP_DEBUG_MODE 50
#define VP_TEMPLATE_DEBUG_MODE 50
#include <dynamic-graph/debug.h>
#define BOOST_TEST_MODULE debug-trace
#define BOOST_TEST_MODULE debug - trace
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph
{
class CustomEntity : public Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
CustomEntity (const std::string n)
: Entity (n)
{
dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt");
}
~CustomEntity()
{
dynamicgraph::dgDEBUGFLOW.closeFile("/tmp/dynamic-graph-traces.txt");
}
void testDebugTrace()
{
/// Test debugging information when entering the code.
dgDEBUGIN(5);
/// Intermediate test.
dgDEBUGINOUT(5);
dgDEBUG(5) << "Here is a test" << std::endl;
/// Test debugging information when going out of the code.
dgDEBUGOUT(5);
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
}
BOOST_AUTO_TEST_CASE(testDebugTrace)
{
BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity")));
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n) : Entity(n) {
dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt");
}
~CustomEntity() {
dynamicgraph::dgDEBUGFLOW.closeFile("/tmp/dynamic-graph-traces.txt");
}
void testDebugTrace() {
/// Test debugging information when entering the code.
dgDEBUGIN(5);
/// Intermediate test.
dgDEBUGINOUT(5);
dgDEBUG(5) << "Here is a test" << std::endl;
/// Test debugging information when going out of the code.
dgDEBUGOUT(5);
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(testDebugTrace) {
BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::CustomEntity *ptr_entity =
(dynamic_cast<dynamicgraph::CustomEntity *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity")));
dynamicgraph::CustomEntity &entity = *ptr_entity;
entity.testDebugTrace();
/// Copy the debug file into the oss_debug_file
output_test_stream output;
std::fstream the_debug_file;
the_debug_file.open(dynamicgraph::DebugTrace::DEBUG_FILENAME_DEFAULT,
std::ios::in );
std::ios::in);
// Extract the filename and this source file from the output
std::string astr;
std::ostringstream oss_debug_file;
while(std::getline(the_debug_file,astr))
{
std::size_t found=astr.find(":");
std::string asubstr = astr.substr(found+1,astr.length());
found = asubstr.find(":");
std::string asubstr2 = asubstr.substr(found+1,astr.length());
oss_debug_file << asubstr2;
}
while (std::getline(the_debug_file, astr)) {
std::size_t found = astr.find(":");
std::string asubstr = astr.substr(found + 1, astr.length());
found = asubstr.find(":");
std::string asubstr2 = asubstr.substr(found + 1, astr.length());
oss_debug_file << asubstr2;
}
the_debug_file.close();
// Compare with the strings put inside this source file
std::string str_to_test = "# In {"
"# In/Out { }"
"Here is a test"
"# Out }";
std::string str_to_test =
"# In {"
"# In/Out { }"
"Here is a test"
"# Out }";
bool two_sub_string_identical;
// Make comparisons.
......@@ -104,4 +100,5 @@ BOOST_AUTO_TEST_CASE(testDebugTrace)
BOOST_CHECK(two_sub_string_identical);
delete ptr_entity;
}
......@@ -4,8 +4,6 @@
*
*/
#include <iostream>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
......@@ -14,104 +12,119 @@
#include <dynamic-graph/signal-time-dependent.h>
#include <dynamic-graph/tracer.h>
#define BOOST_TEST_MODULE debug-tracer
#include <iostream>
#define BOOST_TEST_MODULE debug - tracer
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
namespace dynamicgraph
{
struct MyEntity : public dynamicgraph::Entity
{
static const std::string CLASS_NAME;
dynamicgraph::Signal<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTwoTimeDepSOUT;
MyEntity (const std::string& name)
: Entity (name)
,m_sigdSIN("MyEntity("+name+")::input(double)::in_double")
,m_sigdTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2),
m_sigdSIN,
"MyEntity("+name+")::input(double)::out_double")
,m_sigdTwoTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2),
m_sigdSIN,
"MyEntity("+name+")::input(double)::out2double")
{
signalRegistration(m_sigdSIN
<< m_sigdTimeDepSOUT
<< m_sigdTwoTimeDepSOUT);
}
virtual void display (std::ostream& os) const
{
os << "Hello! My name is " << getName () << " !" << std::endl;
}
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
double & update(double &res, const int &inTime)
{
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (MyEntity,"MyEntity");
}
namespace dynamicgraph {
struct MyEntity : public dynamicgraph::Entity {
static const std::string CLASS_NAME;
dynamicgraph::Signal<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
dynamicgraph::SignalTimeDependent<Vector, int> m_sigVTimeDepSOUT;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTwoTimeDepSOUT;
explicit MyEntity(const std::string &name)
: Entity(name),
m_sigdSIN("MyEntity(" + name + ")::input(double)::in_double"),
m_sigdTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2),
m_sigdSIN,
"MyEntity(" + name + ")::input(double)::out_double"),
m_sigVTimeDepSOUT(boost::bind(&MyEntity::updateVector, this, _1, _2),
m_sigdSIN,
"MyEntity(" + name + ")::input(vector)::out_vector"),
m_sigdTwoTimeDepSOUT(
boost::bind(&MyEntity::update, this, _1, _2), m_sigdSIN,
"MyEntity(" + name + ")::input(double)::out2double")
BOOST_AUTO_TEST_CASE(test_tracer)
{
{
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT << m_sigVTimeDepSOUT
<< m_sigdTwoTimeDepSOUT);
}
virtual void display(std::ostream &os) const {
os << "Hello! My name is " << getName() << " !" << std::endl;
}
virtual const std::string &getClassName() const { return CLASS_NAME; }
double &update(double &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
Vector &updateVector(Vector &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res.resize(2);
res << aDouble, 2 * aDouble;
return res;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(test_tracer) {
using dynamicgraph::Vector;
// Creates a tracer.
dynamicgraph::Tracer & atracer =
*dynamic_cast<dynamicgraph::Tracer *>
(dynamicgraph::FactoryStorage::getInstance()->newEntity("Tracer",
"my-tracer"));
dynamicgraph::Tracer &atracer = *dynamic_cast<dynamicgraph::Tracer *>(
dynamicgraph::FactoryStorage::getInstance()->newEntity("Tracer",
"my-tracer"));
dynamicgraph::Entity &entity =
*dynamicgraph::FactoryStorage::getInstance()->newEntity("MyEntity",
"my-entity");
std::string rootdir("/tmp");
std::string basename("my-tracer");
std::string suffix(".dat");
dynamicgraph::Entity & entity =
*dynamicgraph::FactoryStorage::getInstance()->newEntity("MyEntity",
"my-entity");
/// Test openfiles
atracer.openFiles(rootdir, basename, suffix);
/// Add trace by name
atracer.addSignalToTraceByName("my-entity.out_double","output");
atracer.addSignalToTraceByName("my-entity.out_double", "output");
/// Add trace by name
atracer.addSignalToTraceByName("my-entity.out_vector", "output-vector");
dynamicgraph::SignalBase<int> &aSignal = entity.getSignal("out2double");
dynamicgraph::SignalBase<int> & aSignal =
entity.getSignal("out2double");
dynamicgraph::Signal<double, int> &aSignalInt =
*(dynamic_cast<dynamicgraph::Signal<double, int> *>(
&entity.getSignal("in_double")));
dynamicgraph::Signal<double,int> & aSignalInt =
*(dynamic_cast<dynamicgraph::Signal<double,int> *>
(& entity.getSignal("in_double")));
dynamicgraph::Signal<Vector, int> &aSignalVector =
*(dynamic_cast<dynamicgraph::Signal<Vector, int> *>(
&entity.getSignal("out_vector")));
/// Add trace by signal object
atracer.addSignalToTrace(aSignal,"output2");
atracer.addSignalToTrace(aSignal, "output2");
aSignalInt.setConstant(1.5);
std::string rootdir("/tmp");
std::string basename("my-tracer");
std::string suffix(".dat");
/// Test openfiles
atracer.openFiles(rootdir,basename,suffix);
atracer.start();
for(int i=0;i<1000;i++)
{
aSignal.setTime(i);
aSignalInt.setTime(i);
atracer.recordTrigger(i,i);
}
for (int i = 0; i < 1000; i++) {
aSignal.setTime(i);
aSignalInt.access(i);
aSignalInt.setTime(i);
aSignalVector.recompute(i);
aSignalVector.setTime(i);
atracer.recordTrigger(i, i);
}
atracer.stop();
atracer.clearSignalToTrace();
atracer.closeFiles();
atracer.record();
}
......@@ -5,229 +5,251 @@
#define ENABLE_RT_LOG
#include <sstream>
#include <dynamic-graph/command-direct-getter.h>
#include <dynamic-graph/command-direct-setter.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
#include <dynamic-graph/real-time-logger.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <sstream>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"
#define BOOST_TEST_MODULE entity
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph
{
class CustomEntity : public Entity
{
public:
dynamicgraph::SignalPtr<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
CustomEntity (const std::string n)
: Entity (n)
,m_sigdSIN(NULL,"CustomEntity("+name+")::input(double)::in_double")
,m_sigdTimeDepSOUT(boost::bind(&CustomEntity::update,this,_1,_2),
m_sigdSIN,
"CustomEntity("+name+")::input(double)::out_double")
{
}
void addSignal()
{
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT);
}
void rmValidSignal()
{
signalDeregistration("in_double");
signalDeregistration("out_double");
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
dynamicgraph::SignalPtr<double, int> m_sigdSIN, m_sigdSIN2;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
static const std::string CLASS_NAME;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n)
: Entity(n),
m_sigdSIN(NULL, "CustomEntity(" + name + ")::input(double)::in_double"),
m_sigdSIN2(NULL,
"CustomEntity(" + name + ")::input(double)::in_double"),
m_sigdTimeDepSOUT(
boost::bind(&CustomEntity::update, this, _1, _2), m_sigdSIN,
"CustomEntity(" + name + ")::input(double)::out_double"),
m_value(0.0) {}
~CustomEntity() { entityDeregistration(); }
void addSignal() {
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT);
/// Try a second time to generate an exception
try {
signalRegistration(m_sigdSIN2 << m_sigdTimeDepSOUT);
} catch (ExceptionFactory &aef) {
BOOST_CHECK_EQUAL(aef.getCode(),
dynamicgraph::ExceptionFactory::SIGNAL_CONFLICT);
}
}
void rmValidSignal() {
signalDeregistration("in_double");
signalDeregistration("out_double");
}
double &update(double &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
public:
double m_value;
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
BOOST_AUTO_TEST_CASE(constructor) {
namespace dg = dynamicgraph;
namespace dgc = dynamicgraph::command;
BOOST_CHECK_EQUAL(dg::CustomEntity::CLASS_NAME, "CustomEntity");
dg::Entity &entity = *dg::FactoryStorage::getInstance()->newEntity(
"CustomEntity", "my-entity");
BOOST_CHECK_EQUAL(entity.getName(), "my-entity");
BOOST_CHECK_EQUAL(entity.getClassName(), dg::CustomEntity::CLASS_NAME);
dg::CustomEntity entity2("");
// Test Commands
dgc::DirectGetter<dg::CustomEntity, double> a_direct_getter(
entity2, &entity2.m_value,
dgc::docDirectGetter("Get value m_value", "double"));
dgc::DirectSetter<dg::CustomEntity, double> a_direct_setter(
entity2, &entity2.m_value,
dgc::docDirectSetter("Set value m_value", "double"));
dgc::Value aValue(2.0);
std::vector<dgc::Value> values;
values.push_back(aValue);
a_direct_setter.setParameterValues(values);
a_direct_setter.execute();
a_direct_getter.execute();
double & update(double &res, const int &inTime)
{
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
}
BOOST_AUTO_TEST_CASE (constructor)
{
BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");
dynamicgraph::Entity& entity =
*dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
"my-entity");
BOOST_CHECK_EQUAL (entity.getName (), "my-entity");
BOOST_CHECK_EQUAL (entity.getClassName (),
dynamicgraph::CustomEntity::CLASS_NAME);
output_test_stream output;
output << entity2.m_value;
output << entity2;
dynamicgraph::CustomEntity entity2 ("");
entity.getDocString();
}
BOOST_AUTO_TEST_CASE (signal)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(signal) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
// Non const getter.
try
{
entity.getSignal ("I do not exist");
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
try {
entity.getSignal("I do not exist");
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
// Const getter.
try
{
const dynamicgraph::Entity& entityConst = entity;
entityConst.getSignal ("I do not exist");
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
try {
const dynamicgraph::Entity &entityConst = entity;
entityConst.getSignal("I do not exist");
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
// deregistration
try
{
dynamicgraph::CustomEntity * customEntity =
dynamic_cast<dynamicgraph::CustomEntity *>(&entity);
customEntity->addSignal();
// Removing signals is working the first time
customEntity->rmValidSignal();
// Removing signals generates an exception the second time.
customEntity->rmValidSignal();
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
try {
dynamicgraph::CustomEntity *customEntity =
dynamic_cast<dynamicgraph::CustomEntity *>(&entity);
customEntity->addSignal();
std::string signame("CustomEntity(my-entity)::input(double)::in_double");
customEntity->Entity::hasSignal(signame);
output_test_stream output;
customEntity->Entity::displaySignalList(output);
dynamicgraph::Entity::SignalMap asigmap = customEntity->getSignalMap();
output << customEntity;
// Removing signals is working the first time
customEntity->rmValidSignal();
// Removing signals generates an exception the second time.
customEntity->rmValidSignal();
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL);
}
}
BOOST_AUTO_TEST_CASE (displaySignalList)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(displaySignalList) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
output_test_stream output;
entity.displaySignalList(output);
BOOST_CHECK (output.is_equal ("--- <my-entity> signal list: \n"));
BOOST_CHECK(output.is_equal("--- <my-entity> signal list: \n"));
}
BOOST_AUTO_TEST_CASE (display)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(display) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
output_test_stream output;
entity.display(output);
BOOST_CHECK (output.is_equal ("CustomEntity: my-entity"));
BOOST_CHECK(output.is_equal("CustomEntity: my-entity"));
}
BOOST_AUTO_TEST_CASE (getCommandList)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(getCommandList) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_CHECK_EQUAL (entity.getCommandList (), "print\nsignals\nsignalDep");
BOOST_CHECK_EQUAL(entity.getCommandList(), "print\nsignals\nsignalDep");
}
BOOST_AUTO_TEST_CASE (writeGraph)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(writeGraph) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
output_test_stream output;
entity.writeGraph (output);
entity.writeGraph(output);
BOOST_CHECK (output.is_equal (""));
BOOST_CHECK(output.is_equal(""));
}
BOOST_AUTO_TEST_CASE (writeCompletionList)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(writeCompletionList) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
output_test_stream output;
entity.writeCompletionList (output);
entity.writeCompletionList(output);
BOOST_CHECK (output.is_equal ("print\nsignals\nsignalDep\n"));
BOOST_CHECK(output.is_equal("print\nsignals\nsignalDep\n"));
}
BOOST_AUTO_TEST_CASE (sendMsg)
{
BOOST_AUTO_TEST_CASE(sendMsg) {
std::ofstream of;
of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app);
of.open("/tmp/dg-LOGS.txt", std::ofstream::out | std::ofstream::app);
dgADD_OSTREAM_TO_RTLOG(of);
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
output_test_stream output;
for(unsigned int i=0;
i<4;
i++)
{
for(unsigned int j=0;j<2000;j++)
{
dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel=
(dynamicgraph::LoggerVerbosity) i;
entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel);
if (entity.getLoggerVerbosityLevel()!=aLoggerVerbosityLevel)
output << "Mismatch output";
std::string aBaseMsg="Auto Test Case";
std::string aMsg=aBaseMsg+" DEBUG";
entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_DEBUG, __FILE__, __LINE__);
aMsg=aBaseMsg+" INFO";
entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_INFO, __FILE__, __LINE__);
aMsg=aBaseMsg+" WARNING";
entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_WARNING, __FILE__, __LINE__);
aMsg=aBaseMsg+" DEBUG";
entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_ERROR, __FILE__, __LINE__);
};
for (unsigned int i = 0; i < 4; i++) {
for (unsigned int j = 0; j < 2000; j++) {
dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel =
(dynamicgraph::LoggerVerbosity)i;
entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel);
if (entity.getLoggerVerbosityLevel() != aLoggerVerbosityLevel)
output << "Mismatch output";
#define __FILELINE__ __FILE__ BOOST_PP_STRINGIZE(__LINE__)
entity.logger().stream(dynamicgraph::MSG_TYPE_DEBUG, __FILELINE__)
<< "Auto Test Case"
<< " DEBUG" << '\n';
entity.logger().stream(dynamicgraph::MSG_TYPE_INFO, __FILELINE__)
<< "Auto Test Case"
<< " INFO" << '\n';
entity.logger().stream(dynamicgraph::MSG_TYPE_WARNING, __FILELINE__)
<< "Auto Test Case"
<< " WARNING" << '\n';
entity.logger().stream(dynamicgraph::MSG_TYPE_ERROR, __FILELINE__)
<< "Auto Test Case"
<< " ERROR" << '\n';
#undef __FILELINE__
};
};
BOOST_CHECK (output.is_equal (""));
BOOST_CHECK(output.is_equal(""));
dynamicgraph::RealTimeLogger::destroy();
}
// WTF?
BOOST_AUTO_TEST_CASE (wtf)
{
dynamicgraph::Entity& entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_AUTO_TEST_CASE(wtf) {
dynamicgraph::Entity &entity =
dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity");
BOOST_CHECK_EQUAL (entity.test (),
static_cast<dynamicgraph::SignalBase<int>*> (0));
BOOST_CHECK_EQUAL(entity.test(),
static_cast<dynamicgraph::SignalBase<int> *>(0));
entity.test2 (static_cast<dynamicgraph::SignalBase<int>*> (0));
entity.test2(static_cast<dynamicgraph::SignalBase<int> *>(0));
}
// Copyright 2020 Olivier Stasse
// LAAS, CNRS
#include <dynamic-graph/exception-abstract.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/exception-signal.h>
#include <dynamic-graph/exception-traces.h>
#include <boost/version.hpp>
#include <sstream>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
using boost::test_tools::output_test_stream;
using namespace dynamicgraph;
BOOST_AUTO_TEST_CASE(exception_abstract_param) {
/// Test param from Exception
/// Default constructor
ExceptionAbstract::Param aParamSimple;
/// Advanced constructor
ExceptionAbstract::Param aParam(60, "function_test", "my_file");
aParamSimple.initCopy(aParam);
}
BOOST_AUTO_TEST_CASE(exception_abstract) {
/// Test exception abstract with a simple message
std::string msg_aea("Test exception abstract");
ExceptionAbstract aEA(10, msg_aea);
const char *aC = aEA.getMessage();
output_test_stream output;
output << aC;
BOOST_CHECK(output.is_equal("Test exception abstract"));
output << aEA;
BOOST_CHECK(
output.is_equal("AbstractError [#10]: Test exception abstract\n"));
}
BOOST_AUTO_TEST_CASE(exception_traces) {
std::string msg_aet("Test exception traces simple");
ExceptionTraces aET(ExceptionTraces::GENERIC, msg_aet);
output_test_stream output;
output << aET;
BOOST_CHECK(
output.is_equal("TracesError [#300]: Test exception traces simple\n"));
/// Test exception traces with a format.
int a = 2, b = 3;
std::string msg_aet2("Test exception traces ");
ExceptionTraces aET2(ExceptionTraces::GENERIC, msg_aet2, "(%d,%d)", a, b);
output << aET2;
BOOST_CHECK(
output.is_equal("TracesError [#300]: Test exception traces (2,3)\n"));
}
// Copyright 2010 Thomas Moulard.
//
#include <sstream>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
#include <sstream>
#define BOOST_TEST_MODULE factory
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
namespace dynamicgraph
{
class CustomEntity : public Entity
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
CustomEntity (const std::string n)
: Entity (n)
{
}
};
const std::string CustomEntity::CLASS_NAME = "CustomEntity";
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName() const { return CLASS_NAME; }
explicit CustomEntity(const std::string &n) : Entity(n) {}
};
const std::string CustomEntity::CLASS_NAME = "CustomEntity";
} // namespace dynamicgraph
dynamicgraph::Entity *makeEntity(const std::string &objectName) {
return new dynamicgraph::CustomEntity(objectName);
}
dynamicgraph::Entity* makeEntity(const std::string& objectName)
{
return new dynamicgraph::CustomEntity (objectName);
BOOST_AUTO_TEST_CASE(constructor) {
dynamicgraph::FactoryStorage::getInstance();
}
BOOST_AUTO_TEST_CASE(registerEntity) {
dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity",
&makeEntity);
try {
dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity",
&makeEntity);
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
BOOST_AUTO_TEST_CASE (constructor)
{
dynamicgraph::FactoryStorage::getInstance();
try {
dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", 0);
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
}
BOOST_AUTO_TEST_CASE (registerEntity)
{
dynamicgraph::FactoryStorage::getInstance()->registerEntity
("myEntity", &makeEntity);
try
{
dynamicgraph::FactoryStorage::getInstance()->registerEntity
("myEntity", &makeEntity);
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
try
{
dynamicgraph::FactoryStorage::getInstance()->registerEntity
("myEntity", 0);
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
}
BOOST_AUTO_TEST_CASE(unregisterEntity) {
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity");
BOOST_AUTO_TEST_CASE (unregisterEntity)
{
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity ("myEntity");
try
{
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity");
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
try
{
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity
("I do not exist.");
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
try {
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity");
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
try {
dynamicgraph::FactoryStorage::getInstance()->deregisterEntity(
"I do not exist.");
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::OBJECT_CONFLICT);
}
}
BOOST_AUTO_TEST_CASE (newEntity)
{
dynamicgraph::FactoryStorage::getInstance()->registerEntity
("myEntity", &makeEntity);
BOOST_AUTO_TEST_CASE(newEntity) {
dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity",
&makeEntity);
{
boost::shared_ptr<dynamicgraph::Entity> entity
(dynamicgraph::FactoryStorage::getInstance()->newEntity
("myEntity", "foo"));
boost::shared_ptr<dynamicgraph::Entity> entity(
dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity",
"foo"));
boost::shared_ptr<dynamicgraph::Entity> entity2
(dynamicgraph::FactoryStorage::getInstance()->newEntity
("myEntity", "foo2"));
boost::shared_ptr<dynamicgraph::Entity> entity2(
dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity",
"foo2"));
boost::shared_ptr<dynamicgraph::Entity> entity3
(dynamicgraph::FactoryStorage::getInstance()->newEntity
("myEntity", ""));
boost::shared_ptr<dynamicgraph::Entity> entity3(
dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", ""));
}
try
{
dynamicgraph::FactoryStorage::getInstance()->newEntity
("I do not exist.", "");
BOOST_ERROR ("Should never happen.");
}
catch (const dynamicgraph::ExceptionFactory& exception)
{
BOOST_CHECK_EQUAL (exception.getCode (),
dynamicgraph::ExceptionFactory::UNREFERED_OBJECT);
}
try {
dynamicgraph::FactoryStorage::getInstance()->newEntity("I do not exist.",
"");
BOOST_ERROR("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::UNREFERED_OBJECT);
}
try {
dynamicgraph::FactoryStorage::getInstance()->destroy();
dynamicgraph::FactoryStorage::getInstance()->existEntity("myEntity");
// BOOST_ERROR ("Should never happen.");
} catch (const dynamicgraph::ExceptionFactory &exception) {
BOOST_CHECK_EQUAL(exception.getCode(),
dynamicgraph::ExceptionFactory::UNREFERED_OBJECT);
}
}
BOOST_AUTO_TEST_CASE (existEntity)
{
BOOST_CHECK (dynamicgraph::FactoryStorage::getInstance()->existEntity
("myEntity"));
BOOST_CHECK (!dynamicgraph::FactoryStorage::getInstance()->existEntity
("myEntity2"));
BOOST_CHECK (!dynamicgraph::FactoryStorage::getInstance()->existEntity (""));
BOOST_AUTO_TEST_CASE(existEntity) {
// BOOST_CHECK (dynamicgraph::FactoryStorage::getInstance()->existEntity
// ("myEntity"));
BOOST_CHECK(
!dynamicgraph::FactoryStorage::getInstance()->existEntity("myEntity2"));
BOOST_CHECK(!dynamicgraph::FactoryStorage::getInstance()->existEntity(""));
}
// Copyright 2010 Thomas Moulard.
//
#include <sstream>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/interpreter.h>
#include <dynamic-graph/plugin-loader.h>
#define BOOST_TEST_MODULE tracer
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>
#include "interpreter.h"
using boost::test_tools::output_test_stream;
// Check that plug-in loading/unloading is working.
BOOST_AUTO_TEST_CASE (cmd_tracer)
{
dynamicgraph::PluginLoader pl;
// Push paths.
{
RUN_COMMAND ("pushImportPaths", TESTS_DATADIR);
BOOST_CHECK (output.is_empty ());
}
{
RUN_COMMAND ("pushImportPaths", TESTS_PLUGINDIR);
BOOST_CHECK (output.is_empty ());
}
// Import tracer.dg
{
RUN_COMMAND ("import", "interpreter-tracer.dg");
BOOST_CHECK (output.is_empty ());
}
}
// Copyright 2010 Thomas Moulard.
//
#include <sstream>
#include <iostream>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <iostream>
#include <sstream>
#define BOOST_TEST_MODULE pool
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
using boost::test_tools::output_test_stream;
struct MyEntity : public dynamicgraph::Entity
{
struct MyEntity : public dynamicgraph::Entity {
static const std::string CLASS_NAME;
dynamicgraph::SignalPtr<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
MyEntity (const std::string& name)
: Entity (name)
,m_sigdSIN(NULL,"MyEntity("+name+")::input(double)::in_double")
,m_sigdTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2),
m_sigdSIN,
"MyEntity("+name+")::input(double)::out_double")
{
explicit MyEntity(const std::string &name)
: Entity(name),
m_sigdSIN(NULL, "MyEntity(" + name + ")::input(double)::in_double"),
m_sigdTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2),
m_sigdSIN,
"MyEntity(" + name + ")::input(double)::out_double") {
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT);
}
virtual void display (std::ostream& os) const
{
os << "Hello! My name is " << getName () << " !" << std::endl;
virtual void display(std::ostream &os) const {
os << "Hello! My name is " << getName() << " !" << std::endl;
}
virtual const std::string& getClassName () const
{
return CLASS_NAME;
}
virtual const std::string &getClassName() const { return CLASS_NAME; }
double & update(double &res, const int &inTime)
{
double &update(double &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
return res;
}
};
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (MyEntity, "MyEntity");
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity");
namespace dg = dynamicgraph;
BOOST_AUTO_TEST_CASE (pool_display)
{
BOOST_AUTO_TEST_CASE(pool_display) {
/// Create Entity
dg::Entity* entity =
dg::FactoryStorage::getInstance()->
newEntity("MyEntity", "MyEntityInst");
dg::Entity *entity =
dg::FactoryStorage::getInstance()->newEntity("MyEntity", "MyEntityInst");
/// Test exception catching when registering Entity
bool res=false;
bool res = false;
try {
dg::Entity* entity2 =
dg::FactoryStorage::getInstance()->
newEntity("MyEntity", "MyEntityInst");
dg::Entity *entity2 = dg::FactoryStorage::getInstance()->newEntity(
"MyEntity", "MyEntityInst");
bool res2 = (entity2==entity);
bool res2 = (entity2 == entity);
BOOST_CHECK(res2);
} catch (const dg::ExceptionFactory &aef) {
res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT);
}
catch (const dg::ExceptionFactory &aef)
{
res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT);
}
BOOST_CHECK(res);
/// Test exception catching when deregistering Entity
res=false;
res = false;
try {
dg::FactoryStorage::getInstance()->
deregisterEntity("MyEntityInstFailure");
dg::FactoryStorage::getInstance()->deregisterEntity("MyEntityInstFailure");
} catch (const dg::ExceptionFactory &aef) {
res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT);
}
catch (const dg::ExceptionFactory &aef)
{
res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT);
}
BOOST_CHECK(res);
/// Search for an entity inside the map
output_test_stream output;
dg::Entity& e = dg::PoolStorage::getInstance()->getEntity
("MyEntityInst");
dg::Entity &e = dg::PoolStorage::getInstance()->getEntity("MyEntityInst");
e.display(output);
BOOST_CHECK (output.is_equal ("Hello! My name is MyEntityInst !\n"));
BOOST_CHECK(output.is_equal("Hello! My name is MyEntityInst !\n"));
/// Search for an entity inside the map
res=false;
try
{
dg::PoolStorage::getInstance()->getEntity
("MyEntityInstFailure");
}
catch (const dg::ExceptionFactory &aef)
{
res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_OBJECT);
}
BOOST_CHECK (res);
res = false;
try {
dg::PoolStorage::getInstance()->getEntity("MyEntityInstFailure");
} catch (const dg::ExceptionFactory &aef) {
res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_OBJECT);
}
BOOST_CHECK(res);
/// Testing entityMap
const dg::PoolStorage::Entities& anEntityMap =
dg::PoolStorage::getInstance()->getEntityMap();
const dg::PoolStorage::Entities &anEntityMap =
dg::PoolStorage::getInstance()->getEntityMap();
bool testExistence = anEntityMap.find("MyEntityInst")==anEntityMap.end();
bool testExistence = anEntityMap.find("MyEntityInst") == anEntityMap.end();
BOOST_CHECK(!testExistence);
/// Testing the existence of an entity
testExistence = dg::PoolStorage::getInstance()->existEntity
("MyEntityInst",entity);
testExistence =
dg::PoolStorage::getInstance()->existEntity("MyEntityInst", entity);
BOOST_CHECK(testExistence);
/// Testing the completion list of pool storage
dg::PoolStorage::getInstance()->writeCompletionList
(output);
BOOST_CHECK (output.is_equal ("MyEntityInst.in_double\nMyEntityInst.out_double\nprint\nsignals\nsignalDep\n"));
dg::PoolStorage::getInstance()->writeCompletionList(output);
BOOST_CHECK(
output.is_equal("MyEntityInst.in_double\nMyEntityInst.out_double\n"
"print\nsignals\nsignalDep\n"));
/// Checking the graph generated by the pool
dg::PoolStorage::getInstance()->writeGraph("output.dot");
......@@ -138,38 +123,47 @@ BOOST_AUTO_TEST_CASE (pool_display)
the_debug_file.close();
/// Use a predefined output
std::string str_to_test="/* This graph has been automatically generated.\n"
" 2019 Month: 2 Day: 28 Time: 11:28 */\n"
"digraph \"output\" { graph [ label=\"output\" bgcolor = white rankdir=LR ]\n"
"\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; \n"
"\tsubgraph cluster_Entities { \n"
"\t} \n"
"\"MyEntityInst\" [ label = \"MyEntityInst\" ,\n"
" fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]\n"
"}\n";
std::string str_to_test =
"/* This graph has been automatically generated.\n"
" 2019 Month: 2 Day: 28 Time: 11:28 */\n"
"digraph \"output\" { \t graph [ label=\"output\" "
"bgcolor = white rankdir=LR ]\n"
"\t node [ fontcolor = black, color = black,fillcolor = gold1,"
" style=filled, shape=box ] ; \n"
"\tsubgraph cluster_Entities { \n"
"\t} \n"
"\"MyEntityInst\" [ label = \"MyEntityInst\" ,\n"
" fontcolor = black, color = black, fillcolor=cyan, style=filled,"
" shape=box ]\n"
"}\n";
/// Check the two substring (remove the date) -
std::string s_output_wgph = oss_output_wgph.str();
std::string s_crmk="*/";
std::string s_crmk = "*/";
std::size_t find_s_output_wgph = s_output_wgph.find(s_crmk);
std::string sub_s_output_wgph =s_output_wgph.substr(find_s_output_wgph, s_output_wgph.length());
std::string sub_s_output_wgph =
s_output_wgph.substr(find_s_output_wgph, s_output_wgph.length());
std::size_t find_str_to_test = str_to_test.find(s_crmk);
std::string sub_str_to_test =str_to_test.substr(find_str_to_test, str_to_test.length());
std::string sub_str_to_test =
str_to_test.substr(find_str_to_test, str_to_test.length());
bool two_sub_string_identical;
two_sub_string_identical=sub_str_to_test==sub_s_output_wgph;
two_sub_string_identical = sub_str_to_test == sub_s_output_wgph;
std::cout << sub_str_to_test << std::endl;
std::cout << sub_s_output_wgph << std::endl;
std::cout << sub_str_to_test.compare(sub_s_output_wgph) << std::endl;
BOOST_CHECK(two_sub_string_identical);
/// Test name of a valid signal.
std::istringstream an_iss("MyEntityInst.in_double");
dg::SignalBase<int> &aSignal=
dg::PoolStorage::getInstance()->getSignal(an_iss);
dg::SignalBase<int> &aSignal =
dg::PoolStorage::getInstance()->getSignal(an_iss);
std::string aSignalName=aSignal.getName();
testExistence = aSignalName=="MyEntity(MyEntityInst)::input(double)::in_double";
std::string aSignalName = aSignal.getName();
testExistence =
aSignalName == "MyEntity(MyEntityInst)::input(double)::in_double";
BOOST_CHECK(testExistence);
/// Test name of an unvalid signal.
......@@ -177,28 +171,23 @@ BOOST_AUTO_TEST_CASE (pool_display)
try {
dg::PoolStorage::getInstance()->getSignal(an_iss);
} catch (const dg::ExceptionFactory &aef) {
res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_SIGNAL);
}
catch(const dg::ExceptionFactory &aef)
{
res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_SIGNAL);
}
BOOST_CHECK(res);
/// Deregister the entity.
dg::PoolStorage::getInstance()->deregisterEntity
(entity->getName());
dg::PoolStorage::getInstance()->deregisterEntity(entity->getName());
/// Testing the existance of an entity
testExistence = dg::PoolStorage::getInstance()->existEntity
("MyEntityInst",entity);
testExistence =
dg::PoolStorage::getInstance()->existEntity("MyEntityInst", entity);
BOOST_CHECK(!testExistence);
/// Create Entity
std::string name_entity("MyEntityInst2");
dg::PoolStorage::getInstance()->
clearPlugin(name_entity);
dg::PoolStorage::getInstance()->clearPlugin(name_entity);
dg::PoolStorage::destroy();
}
......@@ -13,45 +13,61 @@
#define BOOST_TEST_MODULE real_time_logger
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#include <boost/thread/thread.hpp>
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread/thread.hpp>
using namespace dynamicgraph;
BOOST_AUTO_TEST_CASE (monothread)
{
RealTimeLogger rtl (10);
rtl.addOutputStream (LoggerStreamPtr_t (new LoggerIOStream(std::cout)));
BOOST_AUTO_TEST_CASE(monothread) {
RealTimeLogger rtl(10);
rtl.addOutputStream(LoggerStreamPtr_t(new LoggerIOStream(std::cout)));
for (int i = 0; i < 9; ++i) rtl.front() << "Call number " << i << '\n';
BOOST_CHECK (rtl.full());
BOOST_CHECK(rtl.full());
rtl.front() << "This call should not appear in the output" << '\n';
rtl.spinOnce();
BOOST_CHECK (!rtl.full());
BOOST_CHECK(!rtl.full());
rtl.front() << "This call should appear in the output" << '\n';
int spinNb = 0;
while (rtl.spinOnce()) { spinNb++; }
while (rtl.spinOnce()) {
spinNb++;
}
BOOST_CHECK_EQUAL(spinNb, 9);
rtl.front() << "This msg should be short." << '\n';
rtl.spinOnce();
}
BOOST_AUTO_TEST_CASE (multithread)
{
RealTimeLogger& rtl = RealTimeLogger::instance();
dgADD_OSTREAM_TO_RTLOG (std::cout);
BOOST_AUTO_TEST_CASE(multithread) {
// The part of the code changing priority will only be effective
// if this test is run as root. Otherwise it behaves like a classical thread.
// Test confirms that in this case, it runs with a priority -51
// and that the thread for logging is running on SCHED_OTHER
// with a nice priority (20).
int threadPolicy;
struct sched_param threadParam;
if (pthread_getschedparam(pthread_self(), &threadPolicy, &threadParam) == 0) {
threadPolicy = SCHED_RR;
threadParam.sched_priority = 50;
pthread_setschedparam(pthread_self(), threadPolicy, &threadParam);
}
RealTimeLogger &rtl = RealTimeLogger::instance();
dgADD_OSTREAM_TO_RTLOG(std::cout);
for (std::size_t i = 0; i < rtl.getBufferSize()-1; ++i)
for (std::size_t i = 0; i < rtl.getBufferSize() - 1; ++i)
dgRTLOG() << "Call number " << i << '\n';
for (std::size_t i = 0; i < 12; ++i) {
boost::this_thread::sleep(boost::posix_time::milliseconds(20));
dgRTLOG() << "Call number " << i << std::endl;
BOOST_CHECK (!rtl.full());
BOOST_CHECK(!rtl.full());
}
dgRTLOG() << "This call should appear in the output" << '\n';
......
//
// Created by corentin on 7/3/19.
//
#include <assert.h>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/signal-array.h>
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/tracer.h>
#include <boost/foreach.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
#include <iostream>
#define BOOST_TEST_MODULE signal_array
using boost::test_tools::output_test_stream;
dynamicgraph::SignalArray_const<double> sig;
using namespace std;
using namespace dynamicgraph;
using namespace dynamicgraph::command;
BOOST_AUTO_TEST_CASE(test_array) {
SignalBase<int> sigBa("add test");
SignalArray_const<int> sigArr_C(1);
sigArr_C.operator<<(sigBa);
sigArr_C.operator<<(sigBa);
BOOST_CHECK_EQUAL(2, sigArr_C.getSize());
SignalArray<int> sigArr(1);
sigArr.operator<<(sigBa);
sigArr.operator<<(sigBa);
BOOST_CHECK_EQUAL(2, sigArr.getSize());
SignalBase<int> sigB("constructor test");
SignalArray<int> sigA(2);
sigA << sigB;
sigA.operator<<(sigB);
SignalArray_const<int> sig_C(sigA);
BOOST_CHECK_EQUAL(sigA.getSize(), sig_C.getSize());
}
BOOST_AUTO_TEST_CASE(test_base) {
SignalBase<int> sigA("testA");
SignalBase<int> sigB("test");
sigB.setReady();
BOOST_CHECK_EQUAL(true, sigB.getReady());
// Does nothing, just check that the interface
// still exist at the abstract level.
sigB.setPeriodTime(1);
sigB.getPeriodTime();
sigB.addDependency(sigA);
sigB.removeDependency(sigA);
sigB.clearDependencies();
BOOST_CHECK_EQUAL(true, sigB.needUpdate(10));
output_test_stream output;
sigB.writeGraph(output);
BOOST_CHECK(output.is_equal(""));
/// Verify plug operations
bool res = false;
try {
sigB.plug(&sigA);
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::PLUG_IMPOSSIBLE);
}
BOOST_CHECK(res);
res = false;
try {
sigB.unplug();
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::PLUG_IMPOSSIBLE);
}
BOOST_CHECK(res);
res = false;
try {
sigB.setConstantDefault();
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::PLUG_IMPOSSIBLE);
}
BOOST_CHECK(res);
res = false;
try {
/// Check signal compatibility.
sigB.checkCompatibility();
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::PLUG_IMPOSSIBLE);
}
/// Verify set command value
/// set
std::istringstream iss("empty");
res = false;
try {
sigB.set(iss);
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::SET_IMPOSSIBLE);
}
BOOST_CHECK(res);
/// get a value
res = false;
std::ostringstream oss;
try {
sigB.get(oss);
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::SET_IMPOSSIBLE);
}
BOOST_CHECK(res);
/// Trigger revaluation of the signal
res = false;
try {
sigB.recompute(100);
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::SET_IMPOSSIBLE);
}
BOOST_CHECK(res);
/// Trace the signal
res = false;
try {
sigB.trace(oss);
} catch (const ExceptionSignal &aea) {
res = (aea.getCode() == ExceptionSignal::SET_IMPOSSIBLE);
}
BOOST_CHECK(res);
/// Display the signal
sigB.display(output);
BOOST_CHECK(output.is_equal("Sig:test"));
}
BOOST_AUTO_TEST_CASE(test_cast_helper) {
std::istringstream iss;
iss.str("1");
signal_io<int>::cast(iss);
{
std::istringstream iss_fail;
iss.str("test");
BOOST_CHECK_THROW(signal_io<int>::cast(iss_fail), ExceptionSignal);
}
/// Test cast register with Vector
output_test_stream output;
dynamicgraph::Vector avec;
avec.resize(4);
avec[0] = 1.0;
avec[1] = 2.0;
avec[2] = 3.0;
avec[3] = 4.0;
BOOST_CHECK_NO_THROW(signal_io<Vector>::trace(avec, output));
/// Test cast register with Matrix
dynamicgraph::Matrix amatrix;
amatrix.resize(2, 2);
amatrix(0, 0) = 0.0;
amatrix(0, 1) = 1.0;
amatrix(1, 0) = 2.0;
amatrix(1, 1) = 3.0;
BOOST_CHECK_NO_THROW(signal_io<Matrix>::trace(amatrix, output));
std::istringstream aiss("test");
signal_io<std::string>::cast(aiss);
}
#include <Eigen/Dense>
// Copyright 2010 Thomas Moulard.
//
#include <string>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <Eigen/Dense>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/eigen-io.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/eigen-io.h>
#include <dynamic-graph/linear-algebra.h>
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/signal.h>
#include <dynamic-graph/signal-cast-helper.h>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <string>
#include "signal-cast-register-test.h"
#include "signal-cast-registerer-libA.hh"
#include "signal-cast-registerer-libB.hh"
#define BOOST_TEST_MODULE signal_cast_registerer
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 105900
#include <boost/test/tools/output_test_stream.hpp>
#else
#include <boost/test/output_test_stream.hpp>
#endif
#include <boost/test/unit_test.hpp>
#include <iostream>
using boost::test_tools::output_test_stream;
typedef Eigen::VectorXd Vector;
struct EigenCastRegisterer : public dynamicgraph::SignalCastRegisterer
{
typedef Vector bnuVector;
EigenCastRegisterer () :
SignalCastRegisterer
(typeid(bnuVector), dispVector, castVector, traceVector)
{}
static boost::any castVector (std::istringstream& iss)
{
bnuVector res;
iss >> res;
return res;
}
static void dispVector (const boost::any& object, std::ostream& os)
{
const bnuVector& v = boost::any_cast<bnuVector> (object);
os << "[ ";
for (int i = 0; i < v.size (); ++i)
os << v(i) << " ";
os << " ];" << std::endl;
}
static void traceVector (const boost::any& object, std::ostream& os)
{
const bnuVector& v = boost::any_cast<bnuVector> (object);
for (int i = 0; i < v.size (); ++i)
os << v(i) << " ";
os << std::endl;
}
};
EigenCastRegisterer myVectorCast;
// Define a new cast with a type that supports streaming operators to
// and from it (this could be automated with macros).
dynamicgraph::DefaultCastRegisterer<bool> myBooleanCast;
typedef Eigen::MatrixXd Matrix;
// Check standard double cast registerer.
BOOST_AUTO_TEST_CASE (standard_double_registerer)
{
BOOST_AUTO_TEST_CASE(standard_double_registerer) {
dynamicgraph::Signal<double, int> mySignal("out");
typedef std::pair<std::string, std::string> test_t;
std::vector<test_t> values;
values.push_back (std::make_pair ("42.0", "42\n"));
values.push_back (std::make_pair ("42.5", "42.5\n"));
values.push_back (std::make_pair ("-12.", "-12\n"));
values.push_back(std::make_pair("42.0", "42"));
values.push_back(std::make_pair("42.5", "42.5"));
values.push_back(std::make_pair("-12.", "-12"));
// Double special values.
// FIXME: these tests are failing :(
values.push_back (std::make_pair ("inf", "inf\n"));
values.push_back (std::make_pair ("-inf", "-inf\n"));
values.push_back (std::make_pair ("nan", "nan\n"));
values.push_back(std::make_pair("inf", "inf"));
values.push_back(std::make_pair("-inf", "-inf"));
values.push_back(std::make_pair("nan", "nan"));
BOOST_FOREACH (const test_t &test, values) {
// Set
std::istringstream value(test.first);
mySignal.set(value);
BOOST_FOREACH(const test_t& test, values)
// Get
{
// Set
std::istringstream value (test.first);
mySignal.set (value);
// Get
{
output_test_stream output;
mySignal.get (output);
BOOST_CHECK (output.is_equal (test.second));
}
// Trace
{
output_test_stream output;
mySignal.trace (output);
BOOST_CHECK (output.is_equal (test.second));
}
output_test_stream output;
mySignal.get(output);
BOOST_CHECK_EQUAL(output.str(), test.second);
}
// Trace
{
output_test_stream output;
mySignal.trace(output);
BOOST_CHECK_EQUAL(output.str(), test.second);
}
}
// Check invalid values.
// FIXME: this test is failing for now.
std::istringstream value ("This is not a valid double.");
BOOST_CHECK_THROW (mySignal.set (value), std::exception);
std::istringstream value("This is not a valid double.");
BOOST_CHECK_THROW(mySignal.set(value), std::exception);
}
// Check a custom cast registerer for Boost uBLAS vectors.
BOOST_AUTO_TEST_CASE (custom_vector_registerer)
{
BOOST_AUTO_TEST_CASE(custom_vector_registerer) {
dynamicgraph::Signal<dynamicgraph::Vector, int> myVectorSignal("vector");
// Print the signal name.
{
output_test_stream output;
output << myVectorSignal;
BOOST_CHECK (output.is_equal ("Sig:vector (Type Cst)"));
BOOST_CHECK(output.is_equal("Sig:vector (Type Cst)"));
}
for (unsigned int i = 0; i < 5; ++i)
{
Vector v = Vector::Unit(5,i) ;
std::ostringstream os;
os << v;
std::istringstream ss ("[5]("+os.str ()+")");
for (unsigned int i = 0; i < 5; ++i) {
Vector v = Vector::Unit(5, i);
std::ostringstream os;
os << v;
std::istringstream ss("[5](" + os.str() + ")");
// Set signal value.
myVectorSignal.set (ss);
// Set signal value.
myVectorSignal.set(ss);
// Print out signal value.
output_test_stream output;
myVectorSignal.get (output);
// Print out signal value.
output_test_stream output;
myVectorSignal.get(output);
boost::format fmt ("[ %d %d %d %d %d ];\n");
fmt
% (i == 0)
% (i == 1)
% (i == 2)
% (i == 3)
% (i == 4);
boost::format fmt("%d %d %d %d %d");
fmt % (i == 0) % (i == 1) % (i == 2) % (i == 3) % (i == 4);
BOOST_CHECK (output.is_equal (fmt.str ()));
}
BOOST_CHECK(output.is_equal(fmt.str()));
}
// Catch Exception of ss (not good input)
// ss[0] != "["
try {
std::istringstream ss("test");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[0] != \"[\"";
}
// ss[1] != %i
try {
std::istringstream ss("[test");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[1] != %i";
}
// ss[2] != "]"
try {
std::istringstream ss("[5[");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[2] != \"]\"";
}
// ss[3] != "("
try {
std::istringstream ss("[5]test");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[3] != \"(\"";
}
// ss[4] != ' ' || ','
try {
std::istringstream ss("[5](1, ");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[4] != \" \" || \",\"";
}
// ss[-1] != ")"
try {
std::istringstream ss("[5](1,2,3,4,5]");
myVectorSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[-1] != \")\"";
}
try {
output_test_stream output;
myVectorSignal.trace(output);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[-1] != \")\"";
}
}
BOOST_AUTO_TEST_CASE(custom_matrix_registerer) {
dynamicgraph::Signal<dynamicgraph::Matrix, int> myMatrixSignal("matrix");
// One issue with the strategy used by the
// dynamicgraph::SignalCastRegisterer is that it relies on the
// typeid. In practice, it means that two signals defined in two
// different libraries will have different typeid and one will not be
// able to plug one into the other unless the symbol have merged when
// the plug-in is loaded. See man(3) dlopen in Linux for more
// information about plug-in loading and the RTLD_GLOBAL flag
// necessary to make cast registerer work as expected.
//
// Here we make sure that two instances of the same type
// declared in two separate libraries are resolved into the
// same typeid.
BOOST_AUTO_TEST_CASE (typeid_issue)
{
BOOST_CHECK (typeid(vA) == typeid(vB));
BOOST_CHECK_EQUAL (std::string (typeid(vA).name ()),
std::string (typeid(vB).name ()));
// Print the signal name.
{
output_test_stream output;
output << myMatrixSignal;
BOOST_CHECK(output.is_equal("Sig:matrix (Type Cst)"));
}
// Catch Exception of ss (not good input)
// ss[0] != "["
try {
std::istringstream ss("test");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[0] != \"[\"";
}
// ss[1] != %i
try {
std::istringstream ss("[test");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[1] != %i";
}
// ss[2] != ","
try {
std::istringstream ss("[5[");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[2] != \",\"";
}
// ss[3] != %i
try {
std::istringstream ss("[5,c");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[3] != %i";
}
// ss[4] != "]"
try {
std::istringstream ss("[5,3[");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[4] != \"]\"";
}
// ss[5] != "("
try {
std::istringstream ss("[5,3]test");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[5] != \"(\"";
}
// ss[6] != "("
try {
std::istringstream ss("[5,3](test");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[6] != \"(\"";
}
// ss[8] != " " || ","
try {
std::istringstream ss("[5,3]((1,");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[8] != \" \" || \",\"";
}
// ss[6+n] != ")"
try {
std::istringstream ss("[5,3]((1,2,3]");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << ("ss[6+n] != \")\"");
}
// ss[-3] != ")"
try {
std::istringstream ss("[5,1]((1)(2)(3[");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[5] != \")\"";
}
// ss[-3] != ")"
try {
std::istringstream ss("[5,1]((1)(2)(3)[");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[5] != \")\"";
}
// ss[-1]!= ")"
try {
std::istringstream ss("[3,1]((1)(2),(3)[");
myMatrixSignal.set(ss);
} catch (ExceptionSignal &e) {
std::cout << "Test passed : ss[5] != \")\" and ignore \",\"";
}
//[...]((...))
}