26 #ifndef TEST_UNIT_TEST_BASE_H 27 #define TEST_UNIT_TEST_BASE_H 47 #include "cetlib/filesystem.h" 48 #include "cetlib/filepath_maker.h" 49 #include "cetlib/search_path.h" 57 #include <type_traits> 88 std::string
const&
Argument(
size_t iArg)
const {
return args[iArg]; }
92 std::vector<std::string>
args;
95 void Clear() { exec_name.clear(); args.clear(); }
102 if (argc == 0)
return;
106 args.resize(argc - 1);
107 std::copy(argv + 1, argv + argc,
args.begin());
114 <
typename TestEnv,
typename Pack,
typename... Provs>
137 { ParseCommandLine(argc, argv); }
159 auto iPath = test_paths.find(name);
160 return (iPath == test_paths.end())
161 ? (
"physics.analyzers." + name): iPath->second;
170 return MainTesterParameterSetName().empty()
171 ?
"": TesterParameterSetPath(MainTesterParameterSetName());
177 auto iPath = service_paths.find(name);
178 return (iPath == service_paths.end())
179 ? (
"services." + name): iPath->second;
184 {
return analyzers_default_cfg.at(tester_name); }
188 {
return services_default_cfg.at(service_name); }
192 {
return BuildDefaultConfiguration(); }
199 {
return arguments.Arguments(); }
215 { main_test_name = name; }
219 { test_paths[test_name] = path; }
224 if (MainTesterParameterSetName().empty()) {
225 throw std::logic_error
226 (
"Request setting configuration of non-existent main tester");
228 SetTesterParameterSetPath(MainTesterParameterSetName(), path);
233 { service_paths[service_name] = path; }
236 void AddDefaultServiceConfiguration
237 (std::string service_name, std::string service_cfg)
238 { services_default_cfg[service_name] = service_cfg; }
241 void AddDefaultTesterConfiguration
242 (std::string tester_name, std::string tester_cfg)
243 { analyzers_default_cfg[tester_name] = tester_cfg; }
248 if (MainTesterParameterSetName().empty()) {
249 throw std::logic_error
250 (
"Request adding configuration of non-existent main tester");
252 AddDefaultTesterConfiguration(MainTesterParameterSetName(), tester_cfg);
284 arguments.ParseArguments(argc, argv);
285 if (arguments.hasArgument(0))
286 SetConfigurationPath(arguments.Argument(0));
293 SetMainTesterParameterSetName(
"");
295 AddDefaultServiceConfiguration(
"message",
297 debugModules: [ '*' ] 308 statistics: {type:cout} 315 {
return BuildServiceConfiguration(services_default_cfg); }
319 {
return BuildTestConfiguration(analyzers_default_cfg); }
324 return BuildConfiguration(services_default_cfg, analyzers_default_cfg);
329 static std::string BuildServiceConfiguration
333 cfg +=
"\nservices: {";
334 for (
auto const& service_info: services) {
335 cfg +=
"\n " + service_info.first +
": {";
336 cfg +=
"\n" + service_info.second;
337 cfg +=
"\n } # " + service_info.first;
346 static std::string BuildTestConfiguration
354 for (
auto const& module_info: analyzers) {
355 cfg +=
"\n " + module_info.first +
": {";
356 cfg +=
"\n" + module_info.second;
357 cfg +=
"\n } # " + module_info.first;
366 static std::string BuildConfiguration
370 cfg += BuildServiceConfiguration(services);
371 cfg += BuildTestConfiguration(modules);
388 template <
typename RES>
400 { Resources[res_name] = res_ptr; }
404 { AddSharedResource(std::string(), res_ptr); }
407 template <
typename... Args>
412 AddSharedResource(res_name, res_ptr);
417 template <
typename... Args>
419 {
return ProvideSharedResource(std::string(), res_ptr); }
422 static bool ReplaceSharedResource(
424 std::string res_name,
429 if (current_res_ptr.get() != old_res_ptr)
return false;
430 AddSharedResource(res_name, res_ptr);
433 static bool ReplaceSharedResource
435 {
return ReplaceSharedResource(res_name, old_res_ptr.get(), res_ptr); }
439 static bool ReplaceDefaultSharedResource
442 {
return ReplaceSharedResource(std::string(), old_res_ptr, res_ptr); }
443 static bool ReplaceDefaultSharedResource
445 {
return ReplaceSharedResource(std::string(), old_res_ptr, res_ptr); }
449 template <
typename... Args>
453 AddSharedResource(res_name, res_ptr);
458 template <
typename... Args>
460 { CreateResource(std::string(), std::forward<Args>(
args)...); }
464 template <
typename... Args>
466 (std::string res_name, Args&&...
args)
468 return hasResource(res_name)?
470 CreateResource(res_name, std::forward<Args>(
args)...);
474 template <
typename... Args>
477 return ProposeSharedResource
478 (std::string(), std::forward<Args>(
args)...);
490 auto iRes = Resources.find(name);
491 return (iRes != Resources.end()) &&
bool(iRes->second);
497 auto iRes = Resources.find(name);
498 return (iRes == Resources.end())?
ResourcePtr_t(): iRes->second;
503 {
return *(Resources.at(name).get()); }
509 { Resources.erase(name); }
517 template <
typename RES>
518 std::map<std::string, typename TestSharedGlobalResource<RES>::ResourcePtr_t>
560 template <
typename ConfigurationClass>
592 {
if (bSetup) Setup(); }
595 {
if (bSetup) Setup(); }
612 (config.ServiceParameterSetPath(service_name));
619 (config.TesterParameterSetPath(test_name));
625 if (config.MainTesterParameterSetName().empty())
return {};
626 else return TesterParameters(config.MainTesterParameterSetName());
639 virtual void Setup();
642 virtual void Configure();
649 {
return CompileParameterSet(config.DefaultConfiguration()); }
672 bool MessageLevels =
false;
679 void ParseEnvironmentOptions();
746 template <
typename ConfigurationClass>
755 using TesterEnvBase_t::TesterEnvBase_t;
772 template <
typename Prov,
typename... Args>
775 if (!providers.setup<Prov>(std::forward<Args>(
args)...))
776 throw std::runtime_error(
"Provider already exists!");
777 return providers.getPointer<Prov>();
794 template <
typename Prov,
typename... Args>
797 return SetupProvider<Prov>
798 (this->ServiceParameters(name, std::forward<Args>(
args)...));
813 template <
typename Prov>
816 if (!providers.acquire(std::move(prov)))
817 throw std::runtime_error(
"Provider already exists!");
818 return providers.getPointer<Prov>();
837 template <
typename Interface,
typename Prov,
typename... Args>
840 auto prov = SetupProvider<Prov>(std::forward<Args>(
args)...);
841 providers.set_alias<Prov, Interface>();
864 template <
typename Interface,
typename Prov,
typename... Args>
868 = SetupProviderFromService<Prov>(name, std::forward<Args>(
args)...);
869 providers.set_alias<Prov, Interface>();
887 template <
typename Interface,
typename Prov>
890 auto prov_ptr = providers.acquire(prov);
891 providers.set_alias<Prov, Interface>();
907 template <
typename Prov>
915 template <
typename Prov>
918 if (!providers.erase<Prov>())
919 throw std::runtime_error(
"Provider not present!");
923 template <
typename Prov>
925 {
return providers.getPointer<Prov>(); }
932 template <
typename... Provs>
951 template <
typename Prov>
954 typename Prov::providers_type pack;
955 FillProviderPack(pack);
1006 (std::forward<CONFIG>(config), std::forward<ARGS>(other_args)...);
1020 first(true), after_paths(paths)
1023 virtual std::string operator() (std::string
const& filename);
1034 inline std::string FirstAbsoluteOrLookupWithDotPolicy::operator()
1035 (std::string
const &filename)
1039 if (cet::is_absolute_filepath(filename))
return filename;
1040 return cet::search_path(
"./:" + after_paths.to_string())
1041 .find_file(filename);
1043 return after_paths.find_file(filename);
1050 <
typename TestEnv,
typename Pack,
typename Prov,
typename... Others>
1052 static void fill(TestEnv
const& env, Pack& pack)
1054 pack.set(env.template Provider<Prov>());
1061 template <
typename TestEnv,
typename Pack>
1063 static void fill(TestEnv
const&, Pack&) {}
1071 template <
typename ConfigurationClass>
1074 mf::LogInfo(
"Test") << config.ApplicationName() <<
" completed.";
1083 template <
typename ConfigurationClass>
1099 template <
typename ConfigurationClass>
1102 (std::string config_path)
1105 char const* fhicl_env = getenv(
"FHICL_FILE_PATH");
1106 std::string search_path = fhicl_env? std::string(fhicl_env) +
":":
".:";
1135 template <
typename ConfigurationClass>
1137 std::string config_path = config.ConfigurationPath();
1138 params = config_path.empty()?
1139 DefaultParameters(): ParseParameters(config_path);
1149 template <
typename ConfigurationClass>
1156 (!pset.
get_if_present(config.ServiceParameterSetPath(
"message"), mf_pset))
1159 = CompileParameterSet(config.DefaultServiceConfiguration(
"message"));
1160 std::cout <<
"Using default message facility configuration:\n" 1167 if (options.MessageLevels) {
1168 std::cout <<
"Printing message levels in 'MessageFacility' category." 1171 mf::LogProblem(
"MessageFacility") <<
"Error messages are shown.";
1172 mf::LogPrint(
"MessageFacility") <<
"Warning messages are shown.";
1174 mf::LogTrace(
"MessageFacility") <<
"Debug messages are shown.";
1176 <<
"LOG_TRACE/LOG_DEBUG messages are not compiled away.";
1178 mf::LogInfo(
"MessageFacility") <<
"MessageFacility started.";
1184 template <
typename ConfigurationClass>
1196 ParseEnvironmentOptions();
1208 msg <<
"Complete configuration (";
1209 if (config.ConfigurationPath().empty()) msg <<
"default";
1210 else msg <<
"'" << config.ConfigurationPath() <<
"'";
1211 msg <<
"):\n" << Parameters().to_indented_string(1);
1215 mf::LogInfo(
"Test") << config.ApplicationName() <<
" base setup complete.";
1221 template <
typename ConfigurationClass>
1224 struct OptionsFromConfig_t {
1227 fhicl::Comment(
"prints a message per level (to verify the visible ones"),
1232 fhicl::Comment(
"prints a the list of options (this is one of them!)"),
1238 struct ValidationHelper {
1239 static void printDummy(std::ostream& out)
1243 .print_allowed_configuration(out);
1253 std::cerr <<
"Error parsing environment test options! Valid options:" 1255 ValidationHelper::printDummy(std::cerr);
1266 (ValidationHelper::validate(pset));
1268 if (configTable().printOptions()) {
1270 <<
"The following options can be passed to the test environment" 1271 <<
" by putting them in the \"test: {}\" table of the configuration file:" 1273 ValidationHelper::printDummy(std::cout);
1276 options.MessageLevels = configTable().messageLevels();
1283 #endif // TEST_UNIT_TEST_BASE_H Container of service providers accessed by type and optional label.
std::string main_test_name
name of main test algorithm
fhicl::ParameterSet const & Parameters() const
Returns the full configuration.
MaybeLogger_< ELseverityLevel::ELsev_info, true > LogVerbatim
static void fill(TestEnv const &env, Pack &pack)
fhicl::ParameterSet params
full configuration of the test
Prov const * Provider() const
Return the specified provider (throws if not available)
static fhicl::ParameterSet ParseParameters(std::string config_path)
Fills the test configuration from file or from default.
static void CreateDefaultResource(Args &&...args)
Constructs and registers a new resource with no name.
Helper classes to be used together with LArSoft's unit test.
void ParseArguments(int argc, char **argv)
Parses arguments.
std::string BuildDefaultConfiguration() const
A string describing the full default parameter set.
std::map< std::string, std::string > PathMap_t
Options_t options
options for the test environment
void SetApplicationName(std::string name)
Sets the name of the application.
std::map< std::string, std::string > ConfigurationMap_t
std::string DefaultConfiguration() const
A string describing the full default parameter set.
Prov * SetupProviderFromService(std::string name, Args &&...args)
Sets a service provider up by calling its testing::setupProvider()
virtual fhicl::ParameterSet DefaultParameters() const
Creates a full configuration for the test.
fhicl::ParameterSet TesterParameters(std::string test_name) const
Returns the configuration of the specified test.
Container for service providers used in a test.
MaybeLogger_< ELseverityLevel::ELsev_info, false > LogInfo
ConfigurationMap_t services_default_cfg
Configuration of all the services.
std::shared_ptr< Resource_t > ResourcePtr_t
BasicEnvironmentConfiguration(std::string name)
Constructor; accepts the name as parameter.
BasicTesterEnvironment(bool bSetup=true)
Constructor: sets everything up and declares the test started.
Configuration_t config
instance of the configurer
bool first
whether we are waiting for the first query
std::string main_test_path
path of main test algorithm configuration
void SetMainTesterParameterSetName(std::string name)
Sets the FHiCL name for the configuration of the test algorithm.
std::string DefaultTesterConfiguration(std::string tester_name) const
A string describing default parameter set to configure specified test.
std::string ExecutablePath() const
Returns the name of the executable as started.
virtual void Configure()
Reads and translates the configuration.
details::CommandLineArguments arguments
command line arguments
Class holding a configuration for a test environment.
void FillProviderPack(lar::ProviderPack< Provs... > &pack) const
Fills the specified provider pack with providers.
void make_ParameterSet(intermediate_table const &tbl, ParameterSet &ps)
static bool hasResource(std::string name="")
BasicEnvironmentConfiguration(int argc, char **argv, std::string name)
std::string Executable() const
Returns the name of the executable as started.
std::string TesterParameterSetPath(std::string name) const
FHiCL path for the configuration of the test algorithm.
static std::string DefaultApplicationName()
Returns the default test name.
Prov * SetupProviderFromServiceFor(std::string name, Args &&...args)
Sets a provider up, recording it as implementation of Interface.
Configuration_t const & Config() const
Returns a read-only version of the configuration.
Prov * AcquireProvider(std::unique_ptr< Prov > &&prov)
Acquires a service provider.
static void AddDefaultSharedResource(ResourcePtr_t res_ptr)
Adds a shared resource to the resource registry (empty name)
void ParseCommandLine(int argc, char **argv)
Extracts arguments from the command line, uses first one as config path.
void SetContextIteration(string const &val)
CommandLineArguments()
Constructor: automatically parses from Boost arguments.
PathMap_t test_paths
Set of paths for tester configuration.
Test environment options.
std::string MainTesterParameterSetPath() const
FHiCL path for the configuration of the test algorithm.
CommandLineArguments(int argc, char **argv)
Constructor: parses from specified arguments.
void SetupMessageFacility(fhicl::ParameterSet const &pset, std::string applName="standalone")
Sets up the message facility service.
MaybeLogger_< ELseverityLevel::ELsev_error, true > LogProblem
std::string ServiceParameterSetPath(std::string name) const
FHiCL path for the configuration of the service.
void StartMessageFacility(fhicl::ParameterSet const &pset, string const &applicationName)
Prov::providers_type ProviderPackFor() const
Returns a provider pack for the specified provider.
static Resource_t & DestroyResource(std::string name="")
Destroys the specified resource (does nothing if no such resource)
Prov * SimpleProviderSetup()
Oversimplified provider setup.
ProviderList providers
list of available providers
static std::map< std::string, ResourcePtr_t > Resources
FirstAbsoluteOrLookupWithDotPolicy(std::string const &paths)
bool hasArgument(size_t iArg) const
Returns whether we have arguments up to the iArg-th (0-based)
void DropProvider()
Removes and destroys the specified provider.
std::string config_path
configuration file path
std::string MainTesterParameterSetName() const
Name of the test algorithm instance.
void ParseEnvironmentOptions()
Parses the configuration, looking for the test environment options.
std::string DefaultServiceConfiguration(std::string service_name) const
A string describing the default parameter set to configure the test.
static Resource_t & Resource(std::string name="")
Retrieves the specified resource, or throws if not available.
static ResourcePtr_t ShareResource(std::string name="")
Retrieves the specified resource for sharing (nullptr if none)
std::vector< std::string > const & Arguments() const
Returns the list of non-Boost-test arguments on the command line.
T get(std::string const &key) const
std::string exec_name
name of the test executable (from argv[0])
TESTENV CreateTesterEnvironment(CONFIG &&config, ARGS...other_args)
Constructs and returns a TesterEnvironment object.
std::vector< std::string > args
command line arguments (from argv[0])
std::string to_indented_string() const
void fill(const art::PtrVector< recob::Hit > &hits, int only_plane)
bool get_if_present(std::string const &key, T &value) const
ConfigurationClass Configuration_t
fhicl::ParameterSet ServiceParameters(std::string service_name) const
Returns the configuration of the specified service.
std::string const & Argument(size_t iArg) const
Returns the value of the iArg-th (0-based; no range check!)
Reads and makes available the command line parameters.
Utility class providing singleton objects to the derived classes.
void SetTesterParameterSetPath(std::string test_name, std::string path)
Sets the FHiCL path for the configuration of a test algorithm.
std::string BuildDefaultTestConfiguration() const
A string describing the full default parameter set.
PathMap_t service_paths
Set of paths for service configuration.
Prov * SetupProvider(Args &&...args)
Sets a service provider up by calling its testing::setupProvider()
cet::search_path after_paths
path for the other queries
virtual void Setup()
The complete initialization, ran at construction by default.
A test environment with some support for service providers.
BasicEnvironmentConfiguration()
Default constructor; this is what is used in Boost unit test.
Prov * AcquireProviderFor(std::unique_ptr< Prov > &&prov)
Acquires a service provider implementing an interface.
void SetConfigurationPath(std::string path)
Sets the path to the configuration file.
fhicl::ParameterSet TesterParameters() const
Returns the configuration of the main test (undefined if no main test)
void AddDefaultTesterConfiguration(std::string tester_cfg)
Adds a default configuration for the main tester.
static ResourcePtr_t ProvideDefaultSharedResource(ResourcePtr_t res_ptr)
Creates a shared resource as default only if none exists yet.
BasicTesterEnvironment(Configuration_t &&configurer, bool bSetup=true)
Setup from a configuration.
std::string ConfigurationPath() const
Path to the configuration file.
Container for a list of pointers to providers.
std::string appl_name
name of the application
void SetContextSinglet(string const &val)
std::string BuildDefaultServiceConfiguration() const
A string describing the full default parameter set.
Data structure containing constant pointers to classes.
std::vector< std::string > const & EexcutableArguments() const
Returns the list of non-Boost-test arguments on the command line.
MaybeLogger_< ELseverityLevel::ELsev_success, true > LogTrace
static void fill(TestEnv const &, Pack &)
void Clear()
Erases the stored arguments.
void SetServiceParameterSetPath(std::string service_name, std::string path)
Sets the FHiCL path for the configuration of a test algorithm.
std::string ApplicationName() const
Path to the configuration file.
void SetMainTesterParameterSetPath(std::string path)
Sets the FHiCL path for the configuration of the main test algorithm.
void DefaultInit()
Initialize with some default values.
static fhicl::ParameterSet CompileParameterSet(std::string cfg)
Compiles a parameter set from a string.
static ResourcePtr_t ProposeDefaultSharedResource(Args &&...args)
Creates a shared resource as default only if none exists yet.
ConfigurationMap_t analyzers_default_cfg
Configuration of all the analyzer modules.
void SetApplicationName(string const &applicationName)
static ResourcePtr_t CreateResource(std::string res_name, Args &&...args)
Constructs and registers a new resource with a specified name.
static void AddSharedResource(std::string res_name, ResourcePtr_t res_ptr)
Adds a shared resource to the resource registry.
virtual ~BasicTesterEnvironment()
Destructor: closing remarks.
void parse_document(std::string const &filename, cet::filepath_maker &maker, intermediate_table &result)
MaybeLogger_< ELseverityLevel::ELsev_warning, true > LogPrint
virtual void SetupMessageFacility() const
Sets up the message facility.
Prov * SetupProviderFor(Args &&...args)
Sets a provider up, recording it as implementation of Interface.
BasicEnvironmentConfiguration(int argc, char **argv)
Constructor: acquires parameters from the command line.