contrib/mul/mbl/mbl_test.cxx
Go to the documentation of this file.
00001 #include "mbl_test.h"
00002 //:
00003 // \file
00004 // \brief A place for useful things associated with testing.
00005 // \author iscott
00006 // \date  Aug 2005
00007 
00008 #include <vcl_cerrno.h>
00009 #include <vcl_string.h>
00010 #include <vcl_fstream.h>
00011 #include <vcl_ctime.h>
00012 #include <vcl_cstdlib.h>
00013 #include <vul/vul_file.h>
00014 #include <vul/vul_expand_path.h>
00015 #include <mbl/mbl_config.h>
00016 
00017 
00018 //: replace instances of 'from' in 's' with 'to'
00019 static unsigned replace(char from, char to, vcl_string &s)
00020 {
00021   unsigned c = 0;
00022   for (unsigned i=0; i<s.size(); ++i)
00023     if (s[i] == from)
00024     {
00025       c++;
00026       s[i] = to;
00027     }
00028     return c;
00029 }
00030 
00031 
00032 vcl_string timestamp()
00033 {
00034   char tmpbuf[128];
00035   vcl_time_t ltime;
00036   struct vcl_tm *today;
00037 
00038   // Get UNIX-style time and display as number and string.
00039   vcl_time( &ltime );
00040 
00041   // Convert to time structure and adjust for PM if necessary.
00042   today = vcl_localtime( &ltime );
00043 
00044   // Use strftime to build a customized time string.
00045   vcl_strftime( tmpbuf, 128, "%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 << '\n';
00079   else
00080     file << timestamp() << ' ' << MBL_CONFIG_BUILD_NAME << ' ' << value << vcl_endl;
00081 }