contrib/mul/mbl/mbl_test.cxx
Go to the documentation of this file.
00001 //:
00002 // \file
00003 // \brief A place for useful things associated with testing.
00004 // \author iscott
00005 // \date  Aug 2005
00006 
00007 #include <vcl_cerrno.h>
00008 #include <vcl_string.h>
00009 #include <vcl_fstream.h>
00010 #include <vcl_ctime.h>
00011 #include <vcl_cstdlib.h>
00012 #include <vul/vul_file.h>
00013 #include <vul/vul_expand_path.h>
00014 #include <mbl/mbl_config.h>
00015 
00016 
00017 //: replace instances of 'from' in 's' with 'to'
00018 static unsigned replace(char from, char to, vcl_string &s)
00019 {
00020   unsigned c = 0;
00021   for (unsigned i=0; i<s.size(); ++i)
00022     if (s[i] == from)
00023     {
00024       c++;
00025       s[i] = to;
00026     }
00027     return c;
00028 }
00029 
00030 
00031 vcl_string timestamp()
00032 {
00033     char tmpbuf[128];
00034     vcl_time_t ltime;
00035     struct vcl_tm *today;
00036 
00037     /* Get UNIX-style time and display as number and string. */
00038     vcl_time( &ltime );
00039 
00040     /* Convert to time structure and adjust for PM if necessary. */
00041     today = vcl_localtime( &ltime );
00042 
00043     /* Use strftime to build a customized time string. */
00044     vcl_strftime( tmpbuf, 128,
00045       "%Y-%m-%d %H:%M:%S", today );
00046   return vcl_string(tmpbuf);
00047 }
00048 
00049 
00050 //: A historical measurement recording framework.
00051 // Currently the function will append the measurement to the file specified
00052 // by ${MBL_TEST_SAVE_MEASUREMENT_PATH}/measurement_path, and exports it to Dart.
00053 // In the longer term it may save the value via Dart2.
00054 void mbl_test_save_measurement( const vcl_string &measurement_path, double value)
00055 {
00056   vcl_cout << "<DartMeasurement name=\"" <<
00057     vul_file::strip_directory(measurement_path) <<
00058     "\" type=\"numeric/float\">"<<value<<"</DartMeasurement>" << vcl_endl;
00059 
00060   char * cpath = vcl_getenv("MBL_TEST_SAVE_MEASUREMENT_ROOT");
00061   vcl_string path(cpath?cpath:"");
00062   if (path.empty())
00063     path = MBL_CONFIG_TEST_SAVE_MEASUREMENT_ROOT;
00064   if (path.empty()) // Nobody wants the measurements stored this way.
00065     return;
00066 
00067   vcl_string config = MBL_CONFIG_BUILD_NAME;
00068   if (config.empty()) config="DEFAULT_CONFIG";
00069 
00070   path += '/' + measurement_path + ".txt";
00071   replace('\\', '/', path); // replace Windows-style "\" with Unix-style "/"
00072   path = vul_expand_path(path); // removes trailing or repeated "/"
00073   vul_file::make_directory_path(vul_file::dirname(path));
00074   vcl_ofstream file(path.c_str(), vcl_ios_app | vcl_ios_out);
00075 
00076   if (!file)
00077     vcl_cerr << "ERROR: mbl_test_save_measurement: Unable to open file " << path.c_str() <<
00078       "ERRNO: " << errno << vcl_endl;
00079   else
00080     file << timestamp() << ' ' << MBL_CONFIG_BUILD_NAME << ' ' << value << vcl_endl;
00081 }