debug = False
verboseImport = True
+
# get path to salomeTools sources
satdir = os.path.dirname(os.path.realpath(__file__))
###################################################################
if __name__ == '__main__':
# Make the src & command package accessible from all code
- # as export PATH=satdir:${PATH}
- sys.path.insert(0, satdir)
- errPrint("WARNING: export PATH=%s:${PATH}\n" % satdir)
+ # as export PYTHONPATH=satdir:${PYTHONPATH}
+ # https://docs.python.org/2/library/os.html
+ # On some platforms, including FreeBSD and Mac OS X,
+ # setting environ may cause memory leak
+ # so use sys.path
+ # errPrint("INFO : AllTestLauncherSat sys.path:\n'%s'" % PP.pformat(sys.path)
+ if sys.path[0] != satdir:
+ sys.path.insert(0, satdir)
+ errPrint("WARNING : sys.path prepend '%s'\n" % satdir)
args = getParser().parse_args(sys.argv[1:])
debug = args.debug
sys.path.insert(0, directory) #supposed to be root of a package
runOnArgs(args)
- del sys.path[0]
+
def make_alias(appli_path, alias_path, force=False):
assert len(alias_path) > 0, "Bad name for alias"
if os.path.exists(alias_path) and not force:
- raise src.SatException(_("Cannot create the alias '%s'\n") % alias_path)
+ raise Exception(_("Cannot create the alias '%s'\n") % alias_path)
else: # find relative path
os.symlink(appli_path, alias_path)
'KERNEL').install_dir
script = os.path.join(install_KERNEL_dir, "bin", "salome", "appli_gen.py")
if not os.path.exists(script):
- raise src.SatException(_("KERNEL is not installed"))
+ raise Exception(_("KERNEL is not installed"))
# Add SALOME python in the environment in order to avoid python version
# problems at appli_gen.py call
stderr=subprocess.STDOUT)
if res != 0:
- raise src.SatException(_("Cannot create application, code = %d\n") % res)
+ raise Exception(_("Cannot create application, code = %d\n") % res)
return res
if p not in cfg.APPLICATION.products:
msg = _("Product %(1)s not defined in application %(2)s") % \
{ '1': p, '2': cfg.VARS.application}
- raise src.SatException(msg)
+ raise Exception(msg)
# Construct the list of tuple containing
# the products name and their definition
products = options.products
for p in products:
if p not in cfg.APPLICATION.products:
- raise src.SatException(
+ raise Exception(
_("Product %(product)s not defined in application %(application)s") %
{ 'product': p, 'application': cfg.VARS.application} )
{"child_name" : child_name,
"product_name" : p_name.name,
"appli_name" : config.VARS.application} )
- raise src.SatException(msg)
+ raise Exception(msg)
prod_info_child = src.product.get_product_config(config,
child_name)
pname_pinfo_child = (prod_info_child.name, prod_info_child)
"%(appli_name)s" % {"father_name" : father_name,
"product_name" : p_name,
"appli_name" : config.VARS.application})
- raise src.SatException(msg)
+ raise Exception(msg)
prod_info_father = src.product.get_product_config(config,
father_name)
pname_pinfo_father = (prod_info_father.name, prod_info_father)
logger = self.getLogger()
options = self.getOptions()
+ if config is None:
+ return RCO.ReturnCode("KO", "config is None")
+
# Only useful for completion mechanism : print the keys of the config
if options.schema:
get_config_children(config, args)
if options.info in config.APPLICATION.products:
show_product_info(config, options.info, logger)
return RCO.ReturnCode("OK", "options.info")
- raise src.SatException(
+ raise Exception(
_("%(product_name)s is not a product of %(application_name)s.") % \
{'product_name' : options.info, 'application_name' : config.VARS.application} )
break
if len(source_full_path) == 0:
- raise src.SatException(
+ raise Exception(
_("Config file for product %s not found\n") % source )
else:
if len(args) > 0:
dest_file = os.path.join(
config.VARS.personalDir, 'Applications', dest + '.pyconf' )
if os.path.exists(dest_file):
- raise src.SatException(
+ raise Exception(
_("A personal application '%s' already exists") % dest )
# perform the copy
products = options.products
for p in products:
if p not in cfg.APPLICATION.products:
- raise src.SatException(
+ raise Exception(
_("Product %(product)s not defined in application %(application)s") %
{'product': p, 'application': cfg.VARS.application} )
out_dir = config.APPLICATION.workdir
if not os.path.exists(out_dir):
- raise src.SatException(_("Target directory not found: %s") % out_dir)
+ raise Exception(_("Target directory not found: %s") % out_dir)
if not silent:
logger.write(_("Creating environment files for %s\n") %
self.logger = logger
if (self.valMax - self.valMin) <= 0 or length <= 0:
out_err = _('ERROR: Wrong init values for the progress bar\n')
- raise src.SatException(out_err)
+ raise Exception(out_err)
def display_value_progression(self,val):
'''Display the progress bar.
ier = subprocess.call(command, shell=True, cwd=source_dir,
stdout=log_file, stderr=subprocess.STDOUT)
if ier != 0:
- raise src.SatException("bootstrap has ended in error")
+ raise Exception("bootstrap has ended in error")
# determine salome version
# (in order for the launcher to get python salomeContext API)
kernel_cfg = src.product.get_product_config(config, "KERNEL")
if not src.product.check_installation(kernel_cfg):
- raise src.SatException(_("KERNEL is not installed"))
+ raise Exception(_("KERNEL is not installed"))
kernel_root_dir = kernel_cfg.install_dir
# set kernel bin dir (considering fhs property)
products = options.products
for p in products:
if p not in cfg.APPLICATION.products:
- raise src.SatException(_("Product %(product)s "
+ raise Exception(_("Product %(product)s "
"not defined in application %(application)s") %
{ 'product': p, 'application': cfg.VARS.application} )
products = options.products
for p in products:
if p not in cfg.APPLICATION.products:
- raise src.SatException(_("Product %(product)s "
+ raise Exception(_("Product %(product)s "
"not defined in application %(application)s") %
{ 'product': p, 'application': cfg.VARS.application} )
kernel_cfg = src.product.get_product_config(config, "KERNEL")
kernel_root_dir = kernel_cfg.install_dir
if not src.product.check_installation(kernel_cfg):
- raise src.SatException(_("KERNEL is not installed"))
+ raise Exception(_("KERNEL is not installed"))
script = os.path.join(kernel_root_dir,"bin","salome","app-quickstart.py")
if not os.path.exists( script ):
- raise src.SatException(
+ raise Exception(
_("KERNEL's install has not the script app-quickstart.py") )
# Check that GUI is installed
gui_cfg = src.product.get_product_config(config, "GUI")
gui_root_dir = gui_cfg.install_dir
if not src.product.check_installation(gui_cfg):
- raise src.SatException(_("GUI is not installed"))
+ raise Exception(_("GUI is not installed"))
#Set prefix option passed to app-quickstart.py
name = get_profile_name ( options, config )
prefix = os.path.join( options.prefix, name )
if os.path.exists( prefix ) :
if not options.force :
- raise src.SatException(
+ raise Exception(
_("The path %s already exists, use option --force to remove it.") % prefix )
else :
shutil.rmtree( prefix )
stderr=subprocess.STDOUT)
#Check result of command
if res != 0:
- raise src.SatException(_("Cannot create application, code = %d\n") % res)
+ raise Exception(_("Cannot create application, code = %d\n") % res)
else:
logger.write(
_("Profile sources were generated in directory %s.\n" % prefix), 3 )
message = _("""\
The launcher %(1)s was not found in directory '%(2)s'.
Did you run the command 'sat launcher' ?\n""") % {"1": launcher_name, "2": launcher_dir}
- raise src.SatException(message)
+ raise Exception(message)
launcher_path = os.path.join(launcher_dir, launcher_name)
message = _("""\
The launcher at path '%s' is missing.
Did you run the command 'sat launcher' ?\n""") % launcher_path
- raise src.SatException(message)
+ raise Exception(message)
# Determine the command to launch (add the additional arguments)
command = launcher_path + " " + " ".join(args)
products = options.products
for p in products:
if p not in cfg.APPLICATION.products:
- raise src.SatException(_("Product %(product)s "
+ raise Exception(_("Product %(product)s "
"not defined in application %(application)s") % \
{ 'product': p, 'application': cfg.VARS.application} )
'''
# check archive exists
if not os.path.exists(product_info.archive_info.archive_name):
- raise src.SatException(_("Archive not found: '%s'") % \
+ raise Exception(_("Archive not found: '%s'") % \
product_info.archive_info.archive_name)
logger.write('arc:%s ... ' % \
if len(param_def) > 2: self.prompt = param_def[2]
if len(param_def) > 3: self.check_method = param_def[3]
else:
- raise src.SatException(_("ERROR in template parameter definition"))
+ raise Exception(_("ERROR in template parameter definition"))
self.raw_prompt = self.prompt
if len(self.prompt) == 0:
for pp in ["file_subst", "parameters"]:
if not ldic.has_key(pp): missing.append("'%s'" % pp)
if len(missing) > 0:
- raise src.SatException(
+ raise Exception(
_("Bad format in settings file! %s not defined.") % \
", ".join(missing) )
missing.append(p)
if len(missing) > 0:
- raise src.SatException(
+ raise Exception(
_("Missing parameters: %s") % ", ".join(missing) )
def get_parameters(self, conf_values=None):
break
if len(template_src_dir) == 0:
- raise src.SatException(_("Template not found: %s") % template)
+ raise Exception(_("Template not found: %s") % template)
return template_src_dir
##
# read settings
settings_file = os.path.join(target_dir, "template.info")
if not os.path.exists(settings_file):
- raise src.SatException(_("Settings file not found"))
+ raise Exception(_("Settings file not found"))
tsettings = TemplateSettings(compo_name, settings_file, target_dir)
# first rename the files
ff = fic.replace(tsettings.file_subst, compo_name)
if ff != fic:
if os.path.exists(os.path.join(root, ff)):
- raise src.SatException(
+ raise Exception(
_("Destination file already exists: %s") % \
os.path.join(root, ff) )
logger.write(" %s -> %s\n" % (fic, ff), 5)
dd = rep.replace(tsettings.file_subst, compo_name)
if dd != rep:
if os.path.exists(os.path.join(root, dd)):
- raise src.SatException(
+ raise Exception(
_("Destination directory already exists: %s") % \
os.path.join(root, dd) )
logger.write(" %s -> %s\n" % (rep, dd), 5)
settings_file = os.path.join(tmpdir, "template.info")
if not os.path.exists(settings_file):
- raise src.SatException(_("Settings file not found"))
+ raise Exception(_("Settings file not found"))
tsettings = TemplateSettings("NAME", settings_file, "target")
logger.write("\n", 3)
options.launcher = ""
elif not os.path.isabs(options.launcher):
if not src.config_has_application(config):
- raise src.SatException(
+ raise Exception(
_("An application is required to use a relative path with option --appli") )
options.launcher = os.path.join(config.APPLICATION.workdir, options.launcher)
if not os.path.exists(options.launcher):
- raise src.SatException(
+ raise Exception(
_("Launcher not found: %s") % options.launcher )
return
src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
with_application = True
elif not options.base:
- raise src.SatException(
+ raise Exception(
_('A test base is required. Use the --base option') )
# the launcher is specified either by the application, or by the --launcher option
def compil(config, builder, logger):
builder.prepare()
if not builder.source_dir.smartcopy(builder.install_dir):
- raise src.SatException(_("Error when copying %s sources to install dir") % builder.product_info.name)
+ raise Exception(_("Error when copying %s sources to install dir") % builder.product_info.name)
# test lrelease #.pyconf needs in ..._APPLI pre_depend : ['qt']
command = "which lrelease"
KOSYS = 1 # KO
# get path to salomeTools sources
-satdir = os.path.dirname(os.path.realpath(__file__))
+satdir = os.path.dirname(os.path.realpath(__file__))
# Make the src & commands package accessible from all code
sys.path.insert(0, satdir)
logger = LOG.getDefaultLogger()
-
+
#################################
# MAIN
#################################
return self.do_python_script_build(script, nb_proc)
msg = _("The script %s must have .sh, .bat or .py extension.") % script
- raise src.SatException(msg)
+ raise Exception(msg)
def put_txt_log_in_appli_log_dir(self, file_name):
'''Put the txt log (that contain the system logs, like make command
raise IOError(_("Configuration file '%s' not found") % name)
class ConfigManager:
- '''Class that manages the read of all the configuration files of salomeTools
- '''
- def __init__(self, datadir=None):
- self.logger = LOG.getDefaultLogger()
-
+ """\
+ Class that manages the read of all the config .pyconf files of salomeTools
+ """
+ def __init__(self, runner):
+ self.runner = runner
+ self.logger = runner.getLogger()
+ self.datadir = None
def _create_vars(self, application=None, command=None, datadir=None):
- '''Create a dictionary that stores all information about machine,
+ """Create a dictionary that stores all information about machine,
user, date, repositories, etc...
:param application str: The application for which salomeTools is called.
for salomeTools.
:return: The dictionary that stores all information.
:rtype: dict
- '''
+ """
var = {}
var['user'] = ARCH.get_user()
var['salometoolsway'] = os.path.dirname(
internal_cfg = PYCONF.Config(open(os.path.join(cfg.VARS.srcDir,
'internal_config', 'salomeTools.pyconf')))
except PYCONF.ConfigError as e:
- raise src.SatException(_("Error in configuration file:"
+ raise Exception(_("Error in configuration file:"
" salomeTools.pyconf\n %(error)s") % \
{'error': str(e) })
'local.pyconf')),
PWD = ('LOCAL', cfg.VARS.datadir) )
except PYCONF.ConfigError as e:
- raise src.SatException(_("Error in configuration file: "
+ raise Exception(_("Error in configuration file: "
"local.pyconf\n %(error)s") % \
{'error': str(e) })
except IOError as error:
e = str(error)
- raise src.SatException( e );
+ raise Exception( e );
merger.merge(cfg, local_cfg)
# When the key is "default", put the default value
try:
application_cfg = PYCONF.Config(application + '.pyconf')
except IOError as e:
- raise src.SatException(_("%s, use 'config --list' to get the"
+ raise Exception(_("%s, use 'config --list' to get the"
" list of available applications.") % e)
except PYCONF.ConfigError as e:
if (not ('-e' in parser.parse_args()[1])
or ('--edit' in parser.parse_args()[1])
and command == 'config'):
- raise src.SatException(
+ raise Exception(
_("Error in configuration file: (1)s.pyconf\n %(2)s") % \
{ 'application': application, 'error': str(e) } )
else:
('--edit' in parser.parse_args()[1]) and
command == 'config' ):
sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
- raise src.SatException(
+ raise Exception(
_("Error in configuration file: %s.pyconf\n") % application )
else:
sys.stdout.write(src.printcolors.printcWarning(
:rtype: str
'''
if not self.user_config_file_path:
- raise src.SatException(
+ raise Exception(
_("Error in get_user_config_file: missing user config file path") )
return self.user_config_file_path
try:
value = zt.substitute(self.environ)
except KeyError as exc:
- raise src.SatException(
+ raise Exception(
_("Missing definition in environment: %s") % str(exc) )
return value
env_script = product_info.environ.env_script
# Check that the script exists
if not os.path.exists(env_script):
- raise src.SatException(
+ raise Exception(
_("Environment script not found: %s") % env_script)
if not self.silent and logger is not None:
return
# Check that the script exists
if not os.path.exists(script_path):
- raise src.SatException(
+ raise Exception(
_("Environment script not found: %s") % script_path)
if not self.silent and logger is not None:
res = ("\n"+car*nb).join(s)
return res
+def indentUnittest(msg, prefix=" | "):
+ """
+ indent car multi lines message except first one
+ car default is less spaces for size logs files
+ keep human readable
+ """
+ s = msg.split("\n")
+ res = ("\n" + prefix).join(s)
+ return res
+
def log(msg):
"""elementary log when no logger yet"""
prefix = "%s.log: " % _name
class UnittestFormatter(logging.Formatter):
def format(self, record):
# print "", record.levelname #type(record), dir(record)
- nb = len("2018-03-17 12:15:41 :: INFO :: ")
- res = indent(super(UnittestFormatter, self).format(record), nb)
+ # nb = len("2018-03-17 12:15:41 :: INFO :: ")
+ res = indentUnittest(super(UnittestFormatter, self).format(record), " | ")
return COLS.toColor(res)
msg = _("The product %(prod)s has version %(ver)s but is "
"declared as native in its definition") % \
{'prod': prod_info.name, 'ver': version}
- raise src.SatException(msg)
+ raise Exception(msg)
# If there is no definition but the product is declared as native,
# construct a new definition containing only the get_source key
No definition corresponding to the version %(1)s was found in the file:
%(2)s.
Please add a section in it.""") % {"1" : vv, "2" : prod_pyconf_path}
- raise src.SatException(msg)
+ raise Exception(msg)
# Set the debug, dev and version keys
prod_info.debug = debug
if not arch_path:
msg = _("Archive %(1)s for %(2)s not found.\n") % \
{"1" : arch_name, "2" : prod_info.name}
- raise src.SatException(msg)
+ raise Exception(msg)
prod_info.archive_info.archive_name = arch_path
else:
if (os.path.basename(prod_info.archive_info.archive_name) ==
if not arch_path:
msg = _("Archive %(1)s for %(2)s not found:\n") % \
{"1" : arch_name, "2" : prod_info.name}
- raise src.SatException(msg)
+ raise Exception(msg)
prod_info.archive_info.archive_name = arch_path
# If the product compiles with a script, check the script existence
msg = _("""\
No compilation script found for the product %s.
Please provide a 'compil_script' key in its definition.""") % product_name
- raise src.SatException(msg)
+ raise Exception(msg)
# Get the path of the script
script = prod_info.compil_script
config.PATHS.PRODUCTPATH,
"compil_scripts")
if not script_path:
- raise src.SatException(
+ raise Exception(
_("Compilation script not found: %s") % script_name)
prod_info.compil_script = script_path
if src.architecture.is_windows():
# Check that the script is executable
if not os.access(prod_info.compil_script, os.X_OK):
- #raise src.SatException(
+ #raise Exception(
# _("Compilation script cannot be executed: %s") %
# prod_info.compil_script)
print("Compilation script cannot be executed: %s" % prod_info.compil_script)
if not patch_path:
msg = _("Patch %(1)s for %(2)s not found:\n") % \
{"1" : patch, "2" : prod_info.name}
- raise src.SatException(msg)
+ raise Exception(msg)
patches.append(patch_path)
prod_info.patches = patches
if not env_script_path:
msg = _("Environment script %(1)s for %(2)s not found.\n") % \
{"1" : env_script_path, "2" : prod_info.name}
- raise src.SatException(msg)
+ raise Exception(msg)
prod_info.environ.env_script = env_script_path
else:
msg = _("The %s product has no definition "
"in the configuration.") % prod
- raise src.SatException(msg)
+ raise Exception(msg)
return products_infos
def get_product_dependencies(config, product_info):
import src.debug as DBG # Easy print stderr (for DEBUG only)
import src.returnCode as RCO # Easy (ok/ko, why) return methods code
from src.options import Options
+import configManager as CFGMGR
# get path to src
rootdir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..") )
return sorted(cmd_list)
# The list of valid salomeTools commands from cmdsdir
-#_COMMANDS_NAMES = ['config', 'compile', 'prepare',...]
+# ['config', 'compile', 'prepare', ...]
_COMMANDS_NAMES = find_command_list(cmdsdir)
def getCommandsList():
"""
if "sat" not in command.split()[0]:
raise Exception(_("Not a valid command for launchSat: '%s'") % command)
- env = dict(os.environ) #copy
- # theorically useless
- # env["PATH"] = rootdir + ":" + env["PATH"]
- res =SP.Popen(command, shell=True, env=env, stdout=SP.PIPE, stderr=SP.PIPE).communicate()
+ env = dict(os.environ) # copy
+ # theorically useless, in user environ $PATH,
+ # on ne sait jamais
+ # https://docs.python.org/2/library/os.html
+ # On some platforms, including FreeBSD and Mac OS X,
+ # setting environ may cause memory leaks.
+ # see test/initializeTest.py
+ if rootdir not in env["PATH"].split(":"):
+ env["PATH"] = rootdir + ":" + env["PATH"]
+ # TODO setLocale not 'fr' on subprocesses, why not?
+ # env["LANG"] == ''
+ res = SP.Popen(command, shell=True, env=env, stdout=SP.PIPE, stderr=SP.PIPE).communicate()
return res
def setNotLocale():
# contains commands classes needed (think micro commands)
# if useful 'a la demande'
self.commands = {}
+ self.nameCommandToLoad = None
+ self.nameAppliToLoad = None
+ self.commandArguments = None
self.nameAppliLoaded = None
-
+
self.parser = self._getParser()
def __repr__(self):
self.print_help()
return RCO.ReturnCode("OK", "No arguments, as 'sat --help'")
- self.options, remaindersArgs = self.parseArguments(args)
+ self.options, remainderArgs = self.parseArguments(args)
# if the help option has been called, print command help and returns
if self.options.help:
self.print_help()
return RCO.ReturnCode("OK", "Option --help")
- # the command called
- cmdName = remaindersArgs[0]
+ self.nameCommandToLoad, self.nameAppliToLoad, self.commandArguments = \
+ self.getCommandAndAppli(remainderArgs)
+
+ cfgManager = CFGMGR.ConfigManager(self)
+ self.config = cfgManager.get_config(
+ application=self.nameAppliToLoad,
+ options=self.options,
+ command=self.nameCommandToLoad,
+ datadir=None)
+
# create/get dynamically the command instance to call its 'run' method
- cmdInstance = self.getCommandInstance(cmdName)
+ cmdInstance = self.getCommandInstance(self.nameCommandToLoad)
+
# Run the command using the arguments
- returnCode = cmdInstance.run(remaindersArgs[1:])
+ returnCode = cmdInstance.run(self.commandArguments)
return returnCode
+
+ def getCommandAndAppli(self, arguments):
+ args = self.assumeAsList(arguments)
+ namecmd, nameAppli, remainderArgs = None, None, []
+ iremain = 0
+ if len(args) > 0:
+ if "-" != args[0][0]:
+ namecmd = args[0]
+ iremain = 1
+ if len(args) > 1:
+ if "-" != args[1][0]:
+ nameAppli = args[1]
+ iremain = 2
+ remainderArgs = args[iremain:]
+ res = (namecmd, nameAppli, remainderArgs)
+ DBG.write("getCommandAndAppli", res)
+ return res
+
def get_help(self):
"""get general help colored string"""
self.logger.write(_("get test base from dir: %s\n") % \
src.printcolors.printcLabel(testbase_dir), 3)
if not os.access(testbase_dir, os.X_OK):
- raise src.SatException(
+ raise Exception(
_("testbase %(name)s (%(dir)s) does not exist ...\n") % \
{ 'name': testbase_name, 'dir': testbase_dir } )
stdout=self.logger.logTxtFile,
stderr=subprocess.PIPE)
if res != 0:
- raise src.SatException(_("Error: unable to get test base "
+ raise Exception(_("Error: unable to get test base "
"'%(name)s' from git '%(repo)s'.") % \
{ 'name': testbase_name,
'repo': testbase_base })
env=env_appli.environ.environ,)
if res != 0:
- raise src.SatException(
+ raise Exception(
_("ERROR: unable to get test base '%(name)s' from svn '%(repo)s'.") % \
{ 'name': testbase_name, 'repo': testbase_base } )
test_base_name,
test_base_info.info.base)
else:
- raise src.SatException(
+ raise Exception(
_("unknown source type '%(type)s' for test base '%(base)s' ...\n") % \
{'type': test_base_info.get_sources, 'base': test_base_name } )
" the list of available applications.\n")
if details :
details.append(message)
- raise SatException( message )
+ raise Exception( message )
def check_config_has_profile( config, details = None ):
'''check that the config has the key APPLICATION.profile.
message = _("A profile section is required in your application.\n")
if details :
details.append(message)
- raise SatException( message )
+ raise Exception( message )
def config_has_application( config ):
return 'APPLICATION' in config
"data",
"local.pyconf")
msg = _("Please define a base path in the file %s") % local_file_path
- raise SatException(msg)
+ raise Exception(msg)
base_path = os.path.abspath(config.LOCAL.base)
"data",
"local.pyconf")
msg = _("Please define a log_dir in the file %s") % local_file_path
- raise SatException(msg)
+ raise Exception(msg)
log_dir_path = os.path.abspath(config.LOCAL.log_dir)
try:
cfg_file = pyconf.Config(filePath)
except pyconf.ConfigError as e:
- raise SatException(_("Error in configuration file: %(file)s\n %(error)s") %
+ raise Exception(_("Error in configuration file: %(file)s\n %(error)s") %
{ 'file': filePath, 'error': str(e) } )
return cfg_file
--- /dev/null
+#!/usr/bin/env python
+#-*- coding:utf-8 -*-
+
+# Copyright (C) 2010-2018 CEA/DEN
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+"""\
+initialize PATH etc... for salomeTools unittest test files
+"""
+
+"""
+https://docs.python.org/2/library/os.html
+os.environ mapping is captured the first time the os module is imported,
+typically during Python startup as part of processing site.py.
+Changes to the environment made after this time are not reflected
+in os.environ, except for changes made by modifying os.environ directly.
+
+On some platforms, including FreeBSD and Mac OS X,
+setting environ may cause memory leaks.
+"""
+
+import os
+import sys
+import pprint as PP
+
+# get path to salomeTools sources directory parent
+satdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
+
+# sys.stderr.write("INFO : initializeTest needs '%s' in sys.path:\n%s\n" % (satdir, PP.pformat(sys.path)))
+
+if satdir not in sys.path:
+ # get path to salomeTools sources FIRST as prepend
+ # Make the src & commands package accessible from all test code
+ sys.path.insert(0, satdir)
+ sys.stderr.write("""\
+WARNING : sys.path not set for salomeTools, fixed for you:
+ sys.path prepend '%s'
+ sys.path:\n%s\n""" % (satdir, PP.pformat(sys.path)))
+ # os.environ PATH is not set...
+ # supposedly useful only for subprocess launch from sat
+ # see https://docs.python.org/2/library/os.html
+ # On some platforms, including FreeBSD and Mac OS X,
+ # setting environ may cause memory leaks.
+ # sys.stderr.write("os.environ PATH:\n%s\n" % PP.pformat(os.environ["PATH"].split(":")))
+ sys.stderr.write("INFO : to fix this message type:\n 'export PYTHONPATH=%s:${PYTHONPATH}'\n" % satdir)
+
+
import sys
import unittest
+import initializeTest # set PATH etc for test
+
import src.debug as DBG # Easy print stderr (for DEBUG only)
import src.pyconf as PYF # 0.3.7
import config_0_3_9.config as PYF9 # TODO 0.3.9
import sys
import unittest
+import initializeTest # set PATH etc for test
+
import src.debug as DBG # Easy print stderr (for DEBUG only)
import src.pyconf as PYF # 0.3.7
import config_0_3_9.config as PYF9 # TODO 0.3.9
import unittest
# import test_support
+
+import initializeTest # set PATH etc for test
+
import src.pyconf as config
from src.pyconf import Config, ConfigMerger, ConfigList
from src.pyconf import ConfigError, ConfigFormatError, ConfigResolutionError
import sys
import unittest
+import initializeTest # set PATH etc for test
+
import src.salomeTools as SAT
import src.debug as DBG # Easy print stderr (for DEBUG only)
import src.loggingSat as LOG
import sys
import unittest
+import initializeTest # set PATH etc for test
+
import src.salomeTools as SAT
import src.debug as DBG # Easy print stderr (for DEBUG only)
import src.loggingSat as LOG
DBG.write("s.getConfig()", s.getConfig()) #none
DBG.write("s.__dict__", s.__dict__) # have
returnCode = s.execute_cli(cmd)
+ DBG.write("test_010 returnCode", returnCode, True)
+ logs = self.logger.getLogs()
+ DBG.write("test_010 logger", logs, True)
self.assertTrue(returnCode.isOk())
if __name__ == '__main__':
+++ /dev/null
-#!/usr/bin/env python
-#-*- coding:utf-8 -*-
-# Copyright (C) 2010-2012 CEA/DEN
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-import tempfile
-import sys
-import subprocess
-import time
-
-class outRedirection():
- '''redirection of standart output
- useful for testing the terminal display
- '''
- def __init__(self):
- '''initialization
- '''
- self._fstream = tempfile.NamedTemporaryFile(mode='w')
- self.saveout = sys.stdout
- sys.stdout = self._fstream
-
- def flush(self):
- self._fstream.flush()
-
- def end_redirection(self):
- self._fstream.seek(0)
- ff = open(self._fstream.name, 'r')
- self.res = ff.read()
- self._fstream.close()
- sys.stdout = self.saveout
-
- def read_results(self):
- try:
- return self.res
- except Exception as exc:
- print('Problem with redirection : %s' % exc)
- sys.exit(1)
-
-def kill9(pid):
- subprocess.call("kill -9 " + pid, shell=True)
-
-def check_proc_existence_and_kill(regex):
- cmd = 'ps aux | grep "' + regex + '"'
- psRes = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
- psRes = psRes.split('\n')
- for line in psRes:
- if 'grep' in line or len(line) == 0:
- continue
- line2 = [i for i in line.split(' ') if i != '']
- pid = line2[1]
- kill9(pid)
- return pid
- return 0
-
-def check_proc_existence_and_kill_multi(regex, nb_kills, time_between_two_checks = 1):
- found = False
- i = 0
- while not found and i < nb_kills :
- found = check_proc_existence_and_kill(regex)
- if found:
- return found
- time.sleep(time_between_two_checks)
- i+=1
- return 0
\ No newline at end of file