id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,200
ARMmbed/icetea
icetea_lib/LogManager.py
get_external_logger
def get_external_logger(name=None, short_name=" ", log_to_file=True): """ Get a logger for external modules, whose logging should usually be on a less verbose level. :param name: Name for logger :param short_name: Shorthand name for logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger """ global LOGGERS loggername = name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logging_config = LOGGING_CONFIG.get(name, LOGGING_CONFIG.get("external")) filename = logging_config.get("file", {}).get("name", loggername) if not filename.endswith(".log"): filename = str(filename) + ".log" logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(filename)) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL == 1 and not SILENT_ON: cbh.setLevel(logging.INFO) elif VERBOSE_LEVEL >= 2 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.ERROR) else: cbh.setLevel(getattr(logging, logging_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
python
def get_external_logger(name=None, short_name=" ", log_to_file=True): global LOGGERS loggername = name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logging_config = LOGGING_CONFIG.get(name, LOGGING_CONFIG.get("external")) filename = logging_config.get("file", {}).get("name", loggername) if not filename.endswith(".log"): filename = str(filename) + ".log" logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(filename)) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL == 1 and not SILENT_ON: cbh.setLevel(logging.INFO) elif VERBOSE_LEVEL >= 2 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.ERROR) else: cbh.setLevel(getattr(logging, logging_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
[ "def", "get_external_logger", "(", "name", "=", "None", ",", "short_name", "=", "\" \"", ",", "log_to_file", "=", "True", ")", ":", "global", "LOGGERS", "loggername", "=", "name", "logger", "=", "_check_existing_logger", "(", "loggername", ",", "short_name", "...
Get a logger for external modules, whose logging should usually be on a less verbose level. :param name: Name for logger :param short_name: Shorthand name for logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger
[ "Get", "a", "logger", "for", "external", "modules", "whose", "logging", "should", "usually", "be", "on", "a", "less", "verbose", "level", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L382-L417
27,201
ARMmbed/icetea
icetea_lib/LogManager.py
get_bench_logger
def get_bench_logger(name=None, short_name=" ", log_to_file=True): """ Return a logger instance for given name. The logger will be a child of the bench logger, so anything that is logged to it, will be also logged to bench logger. If a logger with the given name doesn't already exist, create it using the given parameters. :param name: Name of the logger :param short_name: A short name (preferably 3 characters) describing the logger :param log_to_file: Boolean, if True the logger will also log to a file "name.log" """ global LOGGERS # Get the root bench logger if name is none or empty or bench if name is None or name == "" or name == "bench": return LOGGERS["bench"] loggername = "bench." + name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logger = _get_basic_logger(loggername, log_to_file, get_testcase_logfilename(loggername + ".log")) logger.propagate = True LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
python
def get_bench_logger(name=None, short_name=" ", log_to_file=True): global LOGGERS # Get the root bench logger if name is none or empty or bench if name is None or name == "" or name == "bench": return LOGGERS["bench"] loggername = "bench." + name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logger = _get_basic_logger(loggername, log_to_file, get_testcase_logfilename(loggername + ".log")) logger.propagate = True LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
[ "def", "get_bench_logger", "(", "name", "=", "None", ",", "short_name", "=", "\" \"", ",", "log_to_file", "=", "True", ")", ":", "global", "LOGGERS", "# Get the root bench logger if name is none or empty or bench", "if", "name", "is", "None", "or", "name", "==", ...
Return a logger instance for given name. The logger will be a child of the bench logger, so anything that is logged to it, will be also logged to bench logger. If a logger with the given name doesn't already exist, create it using the given parameters. :param name: Name of the logger :param short_name: A short name (preferably 3 characters) describing the logger :param log_to_file: Boolean, if True the logger will also log to a file "name.log"
[ "Return", "a", "logger", "instance", "for", "given", "name", ".", "The", "logger", "will", "be", "a", "child", "of", "the", "bench", "logger", "so", "anything", "that", "is", "logged", "to", "it", "will", "be", "also", "logged", "to", "bench", "logger", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L420-L447
27,202
ARMmbed/icetea
icetea_lib/LogManager.py
init_base_logging
def init_base_logging(directory="./log", verbose=0, silent=False, color=False, no_file=False, truncate=True, config_location=None): """ Initialize the Icetea logging by creating a directory to store logs for this run and initialize the console logger for Icetea itself. :param directory: Directory where to store the resulting logs :param verbose: Log level as integer :param silent: Log level warning :param no_file: Log to file :param color: Log coloring :param truncate: Log truncating :param config_location: Location of config file. :raises IOError if unable to read configuration file. :raises OSError if log path already exists. :raises ImportError if colored logging was requested but coloredlogs module is not installed. """ global LOGPATHDIR global STANDALONE_LOGGING global TRUNCATE_LOG global COLOR_ON global SILENT_ON global VERBOSE_LEVEL if config_location: try: _read_config(config_location) except IOError as error: raise IOError("Unable to read from configuration file {}: {}".format(config_location, error)) except jsonschema.SchemaError as error: raise jsonschema.SchemaError("Logging configuration schema " "file malformed: {}".format(error)) LOGPATHDIR = os.path.join(directory, datetime.datetime.now().strftime( "%Y-%m-%d_%H%M%S.%f").rstrip("0")) # Initialize the simple console logger for IceteaManager icetealogger = logging.getLogger("icetea") icetealogger.propagate = False icetealogger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() formatter = BenchFormatter(LOGGING_CONFIG.get("IceteaManager").get("format"), LOGGING_CONFIG.get("IceteaManager").get("dateformat")) if not color: stream_handler.setFormatter(formatter) elif color and not COLORS: raise ImportError("Missing coloredlogs module. Please install with " "pip to use colors in logging.") else: class ColoredBenchFormatter(coloredlogs.ColoredFormatter): """ This is defined as an internal class here because coloredlogs is and optional dependency. """ converter = datetime.datetime.fromtimestamp def formatTime(self, record, datefmt=None): date_and_time = self.converter(record.created, tz=pytz.utc) if "%F" in datefmt: msec = "%03d" % record.msecs datefmt = datefmt.replace("%F", msec) str_time = date_and_time.strftime(datefmt) return str_time COLOR_ON = color stream_handler.setFormatter(ColoredBenchFormatter( LOGGING_CONFIG.get("IceteaManager").get("format"), LOGGING_CONFIG.get("IceteaManager").get("dateformat"), LEVEL_FORMATS, FIELD_STYLES)) SILENT_ON = silent VERBOSE_LEVEL = verbose if not no_file: try: os.makedirs(LOGPATHDIR) except OSError: raise OSError("Log path %s already exists." % LOGPATHDIR) filename = LOGGING_CONFIG.get("IceteaManager").get("file").get("name", "icetea.log") icetealogger = _add_filehandler(icetealogger, get_base_logfilename(filename), formatter, "IceteaManager") if verbose and not silent: stream_handler.setLevel(logging.DEBUG) elif silent: stream_handler.setLevel(logging.WARN) else: stream_handler.setLevel(getattr(logging, LOGGING_CONFIG.get("IceteaManager").get("level"))) icetealogger.addHandler(stream_handler) TRUNCATE_LOG = truncate if TRUNCATE_LOG: icetealogger.addFilter(ContextFilter()) STANDALONE_LOGGING = False
python
def init_base_logging(directory="./log", verbose=0, silent=False, color=False, no_file=False, truncate=True, config_location=None): global LOGPATHDIR global STANDALONE_LOGGING global TRUNCATE_LOG global COLOR_ON global SILENT_ON global VERBOSE_LEVEL if config_location: try: _read_config(config_location) except IOError as error: raise IOError("Unable to read from configuration file {}: {}".format(config_location, error)) except jsonschema.SchemaError as error: raise jsonschema.SchemaError("Logging configuration schema " "file malformed: {}".format(error)) LOGPATHDIR = os.path.join(directory, datetime.datetime.now().strftime( "%Y-%m-%d_%H%M%S.%f").rstrip("0")) # Initialize the simple console logger for IceteaManager icetealogger = logging.getLogger("icetea") icetealogger.propagate = False icetealogger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() formatter = BenchFormatter(LOGGING_CONFIG.get("IceteaManager").get("format"), LOGGING_CONFIG.get("IceteaManager").get("dateformat")) if not color: stream_handler.setFormatter(formatter) elif color and not COLORS: raise ImportError("Missing coloredlogs module. Please install with " "pip to use colors in logging.") else: class ColoredBenchFormatter(coloredlogs.ColoredFormatter): """ This is defined as an internal class here because coloredlogs is and optional dependency. """ converter = datetime.datetime.fromtimestamp def formatTime(self, record, datefmt=None): date_and_time = self.converter(record.created, tz=pytz.utc) if "%F" in datefmt: msec = "%03d" % record.msecs datefmt = datefmt.replace("%F", msec) str_time = date_and_time.strftime(datefmt) return str_time COLOR_ON = color stream_handler.setFormatter(ColoredBenchFormatter( LOGGING_CONFIG.get("IceteaManager").get("format"), LOGGING_CONFIG.get("IceteaManager").get("dateformat"), LEVEL_FORMATS, FIELD_STYLES)) SILENT_ON = silent VERBOSE_LEVEL = verbose if not no_file: try: os.makedirs(LOGPATHDIR) except OSError: raise OSError("Log path %s already exists." % LOGPATHDIR) filename = LOGGING_CONFIG.get("IceteaManager").get("file").get("name", "icetea.log") icetealogger = _add_filehandler(icetealogger, get_base_logfilename(filename), formatter, "IceteaManager") if verbose and not silent: stream_handler.setLevel(logging.DEBUG) elif silent: stream_handler.setLevel(logging.WARN) else: stream_handler.setLevel(getattr(logging, LOGGING_CONFIG.get("IceteaManager").get("level"))) icetealogger.addHandler(stream_handler) TRUNCATE_LOG = truncate if TRUNCATE_LOG: icetealogger.addFilter(ContextFilter()) STANDALONE_LOGGING = False
[ "def", "init_base_logging", "(", "directory", "=", "\"./log\"", ",", "verbose", "=", "0", ",", "silent", "=", "False", ",", "color", "=", "False", ",", "no_file", "=", "False", ",", "truncate", "=", "True", ",", "config_location", "=", "None", ")", ":", ...
Initialize the Icetea logging by creating a directory to store logs for this run and initialize the console logger for Icetea itself. :param directory: Directory where to store the resulting logs :param verbose: Log level as integer :param silent: Log level warning :param no_file: Log to file :param color: Log coloring :param truncate: Log truncating :param config_location: Location of config file. :raises IOError if unable to read configuration file. :raises OSError if log path already exists. :raises ImportError if colored logging was requested but coloredlogs module is not installed.
[ "Initialize", "the", "Icetea", "logging", "by", "creating", "a", "directory", "to", "store", "logs", "for", "this", "run", "and", "initialize", "the", "console", "logger", "for", "Icetea", "itself", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L480-L572
27,203
ARMmbed/icetea
icetea_lib/LogManager.py
_read_config
def _read_config(config_location): """ Read configuration for logging from a json file. Merges the read dictionary to LOGGING_CONFIG. :param config_location: Location of file. :return: nothing. """ global LOGGING_CONFIG with open(config_location, "r") as config_loc: cfg_file = json.load(config_loc) if "logging" in cfg_file: log_dict = cfg_file.get("logging") with open(os.path.abspath(os.path.join(__file__, os.path.pardir, 'logging_schema.json'))) as schema_file: logging_schema = json.load(schema_file) jsonschema.validate(log_dict, logging_schema) merged = jsonmerge.merge(LOGGING_CONFIG, log_dict) LOGGING_CONFIG = merged
python
def _read_config(config_location): global LOGGING_CONFIG with open(config_location, "r") as config_loc: cfg_file = json.load(config_loc) if "logging" in cfg_file: log_dict = cfg_file.get("logging") with open(os.path.abspath(os.path.join(__file__, os.path.pardir, 'logging_schema.json'))) as schema_file: logging_schema = json.load(schema_file) jsonschema.validate(log_dict, logging_schema) merged = jsonmerge.merge(LOGGING_CONFIG, log_dict) LOGGING_CONFIG = merged
[ "def", "_read_config", "(", "config_location", ")", ":", "global", "LOGGING_CONFIG", "with", "open", "(", "config_location", ",", "\"r\"", ")", "as", "config_loc", ":", "cfg_file", "=", "json", ".", "load", "(", "config_loc", ")", "if", "\"logging\"", "in", ...
Read configuration for logging from a json file. Merges the read dictionary to LOGGING_CONFIG. :param config_location: Location of file. :return: nothing.
[ "Read", "configuration", "for", "logging", "from", "a", "json", "file", ".", "Merges", "the", "read", "dictionary", "to", "LOGGING_CONFIG", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L762-L780
27,204
ARMmbed/icetea
icetea_lib/LogManager.py
BenchFormatterWithType.format
def format(self, record): """ Format record with formatter. :param record: Record to format :return: Formatted record """ if not hasattr(record, "type"): record.type = " " return self._formatter.format(record)
python
def format(self, record): if not hasattr(record, "type"): record.type = " " return self._formatter.format(record)
[ "def", "format", "(", "self", ",", "record", ")", ":", "if", "not", "hasattr", "(", "record", ",", "\"type\"", ")", ":", "record", ".", "type", "=", "\" \"", "return", "self", ".", "_formatter", ".", "format", "(", "record", ")" ]
Format record with formatter. :param record: Record to format :return: Formatted record
[ "Format", "record", "with", "formatter", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L172-L181
27,205
ARMmbed/icetea
icetea_lib/tools/asserts.py
format_message
def format_message(msg): """ Formatting function for assert messages. Fetches the filename, function and line number of the code causing the fail and formats it into a three-line error message. Stack inspection is used to get the information. Originally done by BLE-team for their testcases. :param msg: Message to be printed along with the information. :return: Formatted message as string. """ callerframerecord = inspect.stack()[2] frame = callerframerecord[0] info = inspect.getframeinfo(frame) _, filename = os.path.split(info.filename) caller_site = "In file {!s}, in function {!s}, at line {:d}".format(filename, info.function, info.lineno) return "{!s}\n{!s}\n{!s}".format(msg, caller_site, info.code_context)
python
def format_message(msg): callerframerecord = inspect.stack()[2] frame = callerframerecord[0] info = inspect.getframeinfo(frame) _, filename = os.path.split(info.filename) caller_site = "In file {!s}, in function {!s}, at line {:d}".format(filename, info.function, info.lineno) return "{!s}\n{!s}\n{!s}".format(msg, caller_site, info.code_context)
[ "def", "format_message", "(", "msg", ")", ":", "callerframerecord", "=", "inspect", ".", "stack", "(", ")", "[", "2", "]", "frame", "=", "callerframerecord", "[", "0", "]", "info", "=", "inspect", ".", "getframeinfo", "(", "frame", ")", "_", ",", "file...
Formatting function for assert messages. Fetches the filename, function and line number of the code causing the fail and formats it into a three-line error message. Stack inspection is used to get the information. Originally done by BLE-team for their testcases. :param msg: Message to be printed along with the information. :return: Formatted message as string.
[ "Formatting", "function", "for", "assert", "messages", ".", "Fetches", "the", "filename", "function", "and", "line", "number", "of", "the", "code", "causing", "the", "fail", "and", "formats", "it", "into", "a", "three", "-", "line", "error", "message", ".", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L25-L42
27,206
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertTraceDoesNotContain
def assertTraceDoesNotContain(response, message): """ Raise TestStepFail if response.verify_trace finds message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns True. """ if not hasattr(response, "verify_trace"): raise AttributeError("Response object does not contain verify_trace method!") if response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message)
python
def assertTraceDoesNotContain(response, message): if not hasattr(response, "verify_trace"): raise AttributeError("Response object does not contain verify_trace method!") if response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message)
[ "def", "assertTraceDoesNotContain", "(", "response", ",", "message", ")", ":", "if", "not", "hasattr", "(", "response", ",", "\"verify_trace\"", ")", ":", "raise", "AttributeError", "(", "\"Response object does not contain verify_trace method!\"", ")", "if", "response",...
Raise TestStepFail if response.verify_trace finds message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns True.
[ "Raise", "TestStepFail", "if", "response", ".", "verify_trace", "finds", "message", "from", "response", "traces", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L45-L58
27,207
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertTraceContains
def assertTraceContains(response, message): """ Raise TestStepFail if response.verify_trace does not find message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns False. """ if not hasattr(response, "verify_trace"): raise AttributeError("Response object does not contain verify_trace method!") if not response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" not in response' % message)
python
def assertTraceContains(response, message): if not hasattr(response, "verify_trace"): raise AttributeError("Response object does not contain verify_trace method!") if not response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" not in response' % message)
[ "def", "assertTraceContains", "(", "response", ",", "message", ")", ":", "if", "not", "hasattr", "(", "response", ",", "\"verify_trace\"", ")", ":", "raise", "AttributeError", "(", "\"Response object does not contain verify_trace method!\"", ")", "if", "not", "respons...
Raise TestStepFail if response.verify_trace does not find message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns False.
[ "Raise", "TestStepFail", "if", "response", ".", "verify_trace", "does", "not", "find", "message", "from", "response", "traces", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L61-L74
27,208
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertDutTraceDoesNotContain
def assertDutTraceDoesNotContain(dut, message, bench): """ Raise TestStepFail if bench.verify_trace does not find message from dut traces. :param dut: Dut object. :param message: Message to look for. :param: Bench, must contain verify_trace method. :raises: AttributeError if bench does not contain verify_trace method. TestStepFail if verify_trace returns True. """ if not hasattr(bench, "verify_trace"): raise AttributeError("Bench object does not contain verify_trace method!") if bench.verify_trace(dut, message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message)
python
def assertDutTraceDoesNotContain(dut, message, bench): if not hasattr(bench, "verify_trace"): raise AttributeError("Bench object does not contain verify_trace method!") if bench.verify_trace(dut, message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message)
[ "def", "assertDutTraceDoesNotContain", "(", "dut", ",", "message", ",", "bench", ")", ":", "if", "not", "hasattr", "(", "bench", ",", "\"verify_trace\"", ")", ":", "raise", "AttributeError", "(", "\"Bench object does not contain verify_trace method!\"", ")", "if", "...
Raise TestStepFail if bench.verify_trace does not find message from dut traces. :param dut: Dut object. :param message: Message to look for. :param: Bench, must contain verify_trace method. :raises: AttributeError if bench does not contain verify_trace method. TestStepFail if verify_trace returns True.
[ "Raise", "TestStepFail", "if", "bench", ".", "verify_trace", "does", "not", "find", "message", "from", "dut", "traces", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L77-L90
27,209
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertNone
def assertNone(expr, message=None): """ Assert that expr is None. :param expr: expression. :param message: Message set to raised Exception :raises: TestStepFail if expr is not None. """ if expr is not None: raise TestStepFail( format_message(message) if message is not None else "Assert: %s != None" % str(expr))
python
def assertNone(expr, message=None): if expr is not None: raise TestStepFail( format_message(message) if message is not None else "Assert: %s != None" % str(expr))
[ "def", "assertNone", "(", "expr", ",", "message", "=", "None", ")", ":", "if", "expr", "is", "not", "None", ":", "raise", "TestStepFail", "(", "format_message", "(", "message", ")", "if", "message", "is", "not", "None", "else", "\"Assert: %s != None\"", "%...
Assert that expr is None. :param expr: expression. :param message: Message set to raised Exception :raises: TestStepFail if expr is not None.
[ "Assert", "that", "expr", "is", "None", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L135-L145
27,210
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertNotNone
def assertNotNone(expr, message=None): """ Assert that expr is not None. :param expr: expression. :param message: Message set to raised Exception :raises: TestStepFail if expr is None. """ if expr is None: raise TestStepFail( format_message(message) if message is not None else "Assert: %s == None" % str(expr))
python
def assertNotNone(expr, message=None): if expr is None: raise TestStepFail( format_message(message) if message is not None else "Assert: %s == None" % str(expr))
[ "def", "assertNotNone", "(", "expr", ",", "message", "=", "None", ")", ":", "if", "expr", "is", "None", ":", "raise", "TestStepFail", "(", "format_message", "(", "message", ")", "if", "message", "is", "not", "None", "else", "\"Assert: %s == None\"", "%", "...
Assert that expr is not None. :param expr: expression. :param message: Message set to raised Exception :raises: TestStepFail if expr is None.
[ "Assert", "that", "expr", "is", "not", "None", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L148-L158
27,211
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertEqual
def assertEqual(first, second, message=None): """ Assert that first equals second. :param first: First part to evaluate :param second: Second part to evaluate :param message: Failure message :raises: TestStepFail if not first == second """ if not first == second: raise TestStepFail( format_message(message) if message is not None else "Assert: %s != %s" % (str(first), str(second)))
python
def assertEqual(first, second, message=None): if not first == second: raise TestStepFail( format_message(message) if message is not None else "Assert: %s != %s" % (str(first), str(second)))
[ "def", "assertEqual", "(", "first", ",", "second", ",", "message", "=", "None", ")", ":", "if", "not", "first", "==", "second", ":", "raise", "TestStepFail", "(", "format_message", "(", "message", ")", "if", "message", "is", "not", "None", "else", "\"Ass...
Assert that first equals second. :param first: First part to evaluate :param second: Second part to evaluate :param message: Failure message :raises: TestStepFail if not first == second
[ "Assert", "that", "first", "equals", "second", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L161-L173
27,212
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertNotEqual
def assertNotEqual(first, second, message=None): """ Assert that first does not equal second. :param first: First part to evaluate :param second: Second part to evaluate :param message: Failure message :raises: TestStepFail if not first != second """ if not first != second: raise TestStepFail( format_message(message) if message is not None else "Assert: %s == %s" % (str(first), str(second)))
python
def assertNotEqual(first, second, message=None): if not first != second: raise TestStepFail( format_message(message) if message is not None else "Assert: %s == %s" % (str(first), str(second)))
[ "def", "assertNotEqual", "(", "first", ",", "second", ",", "message", "=", "None", ")", ":", "if", "not", "first", "!=", "second", ":", "raise", "TestStepFail", "(", "format_message", "(", "message", ")", "if", "message", "is", "not", "None", "else", "\"...
Assert that first does not equal second. :param first: First part to evaluate :param second: Second part to evaluate :param message: Failure message :raises: TestStepFail if not first != second
[ "Assert", "that", "first", "does", "not", "equal", "second", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L176-L188
27,213
ARMmbed/icetea
icetea_lib/tools/asserts.py
assertJsonContains
def assertJsonContains(jsonStr=None, key=None, message=None): """ Assert that jsonStr contains key. :param jsonStr: Json as string :param key: Key to look for :param message: Failure message :raises: TestStepFail if key is not in jsonStr or if loading jsonStr to a dictionary fails or if jsonStr is None. """ if jsonStr is not None: try: data = json.loads(jsonStr) if key not in data: raise TestStepFail( format_message(message) if message is not None else "Assert: " "Key : %s is not " "in : %s" % (str(key), str(jsonStr))) except (TypeError, ValueError) as e: raise TestStepFail( format_message(message) if message is not None else "Unable to parse json "+str(e)) else: raise TestStepFail( format_message(message) if message is not None else "Json string is empty")
python
def assertJsonContains(jsonStr=None, key=None, message=None): if jsonStr is not None: try: data = json.loads(jsonStr) if key not in data: raise TestStepFail( format_message(message) if message is not None else "Assert: " "Key : %s is not " "in : %s" % (str(key), str(jsonStr))) except (TypeError, ValueError) as e: raise TestStepFail( format_message(message) if message is not None else "Unable to parse json "+str(e)) else: raise TestStepFail( format_message(message) if message is not None else "Json string is empty")
[ "def", "assertJsonContains", "(", "jsonStr", "=", "None", ",", "key", "=", "None", ",", "message", "=", "None", ")", ":", "if", "jsonStr", "is", "not", "None", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "jsonStr", ")", "if", "key", "n...
Assert that jsonStr contains key. :param jsonStr: Json as string :param key: Key to look for :param message: Failure message :raises: TestStepFail if key is not in jsonStr or if loading jsonStr to a dictionary fails or if jsonStr is None.
[ "Assert", "that", "jsonStr", "contains", "key", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/asserts.py#L191-L215
27,214
ARMmbed/icetea
icetea_lib/tools/GitTool.py
get_path
def get_path(filename): """ Get absolute path for filename. :param filename: file :return: path """ path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename)) return path
python
def get_path(filename): path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename)) return path
[ "def", "get_path", "(", "filename", ")", ":", "path", "=", "abspath", "(", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", "else", "dirname", "(", "abspath", "(", "filename", ")", ")", "return", "path" ]
Get absolute path for filename. :param filename: file :return: path
[ "Get", "absolute", "path", "for", "filename", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GitTool.py#L24-L32
27,215
ARMmbed/icetea
icetea_lib/tools/GitTool.py
get_git_file_path
def get_git_file_path(filename): """ Get relative path for filename in git root. :param filename: File name :return: relative path or None """ git_root = get_git_root(filename) return relpath(filename, git_root).replace("\\", "/") if git_root else ''
python
def get_git_file_path(filename): git_root = get_git_root(filename) return relpath(filename, git_root).replace("\\", "/") if git_root else ''
[ "def", "get_git_file_path", "(", "filename", ")", ":", "git_root", "=", "get_git_root", "(", "filename", ")", "return", "relpath", "(", "filename", ",", "git_root", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "if", "git_root", "else", "''" ]
Get relative path for filename in git root. :param filename: File name :return: relative path or None
[ "Get", "relative", "path", "for", "filename", "in", "git", "root", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GitTool.py#L46-L54
27,216
ARMmbed/icetea
icetea_lib/tools/GitTool.py
get_git_info
def get_git_info(git_folder, verbose=False): """ Detect GIT information by folder. :param git_folder: Folder :param verbose: Verbosity, boolean, default is False :return: dict """ if verbose: print("detect GIT info by folder: '%s'" % git_folder) try: git_info = { "commitid": get_commit_id(git_folder), "branch": get_current_branch(git_folder), "git_path": get_git_file_path(git_folder), "url": get_remote_url(git_folder), "scm": "unknown", "scm_group": "unknown", "scm_path": "unknown", "scm_link": "" } if is_git_root_dirty(git_folder): git_info['dirty'] = True except Exception as err: # pylint: disable=broad-except print("GitTool exception:") print(err) return {} if isinstance(git_info['url'], str): match = re.search(r"github\.com:(.*)\/(.*)", git_info['url']) if match: git_info["scm"] = "github.com" git_info["scm_path"] = match.group(2) git_info["scm_group"] = match.group(1) scm_link_end = " %s/%s" % (git_info["scm_group"], git_info["scm_path"].replace(".git", "")) git_info["scm_link"] = "https://github.com/" + scm_link_end git_info["scm_link"] += "/tree/%s/%s" % (git_info['commitid'], git_info["git_path"]) if verbose: print("all git_info:") print(git_info) return git_info
python
def get_git_info(git_folder, verbose=False): if verbose: print("detect GIT info by folder: '%s'" % git_folder) try: git_info = { "commitid": get_commit_id(git_folder), "branch": get_current_branch(git_folder), "git_path": get_git_file_path(git_folder), "url": get_remote_url(git_folder), "scm": "unknown", "scm_group": "unknown", "scm_path": "unknown", "scm_link": "" } if is_git_root_dirty(git_folder): git_info['dirty'] = True except Exception as err: # pylint: disable=broad-except print("GitTool exception:") print(err) return {} if isinstance(git_info['url'], str): match = re.search(r"github\.com:(.*)\/(.*)", git_info['url']) if match: git_info["scm"] = "github.com" git_info["scm_path"] = match.group(2) git_info["scm_group"] = match.group(1) scm_link_end = " %s/%s" % (git_info["scm_group"], git_info["scm_path"].replace(".git", "")) git_info["scm_link"] = "https://github.com/" + scm_link_end git_info["scm_link"] += "/tree/%s/%s" % (git_info['commitid'], git_info["git_path"]) if verbose: print("all git_info:") print(git_info) return git_info
[ "def", "get_git_info", "(", "git_folder", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", "\"detect GIT info by folder: '%s'\"", "%", "git_folder", ")", "try", ":", "git_info", "=", "{", "\"commitid\"", ":", "get_commit_id", "(", "g...
Detect GIT information by folder. :param git_folder: Folder :param verbose: Verbosity, boolean, default is False :return: dict
[ "Detect", "GIT", "information", "by", "folder", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GitTool.py#L105-L148
27,217
ARMmbed/icetea
icetea_lib/tools/GitTool.py
__get_git_bin
def __get_git_bin(): """ Get git binary location. :return: Check git location """ git = 'git' alternatives = [ '/usr/bin/git' ] for alt in alternatives: if os.path.exists(alt): git = alt break return git
python
def __get_git_bin(): git = 'git' alternatives = [ '/usr/bin/git' ] for alt in alternatives: if os.path.exists(alt): git = alt break return git
[ "def", "__get_git_bin", "(", ")", ":", "git", "=", "'git'", "alternatives", "=", "[", "'/usr/bin/git'", "]", "for", "alt", "in", "alternatives", ":", "if", "os", ".", "path", ".", "exists", "(", "alt", ")", ":", "git", "=", "alt", "break", "return", ...
Get git binary location. :return: Check git location
[ "Get", "git", "binary", "location", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GitTool.py#L151-L165
27,218
ARMmbed/icetea
icetea_lib/Result.py
Result.build
def build(self): """ get build name. :return: build name. None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.name return None
python
def build(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.name return None
[ "def", "build", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ")", "...
get build name. :return: build name. None if not found
[ "get", "build", "name", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L140-L149
27,219
ARMmbed/icetea
icetea_lib/Result.py
Result.build_date
def build_date(self): """ get build date. :return: build date. None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.date return None
python
def build_date(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.date return None
[ "def", "build_date", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ")"...
get build date. :return: build date. None if not found
[ "get", "build", "date", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L159-L168
27,220
ARMmbed/icetea
icetea_lib/Result.py
Result.build_sha1
def build_sha1(self): """ get sha1 hash of build. :return: build sha1 or None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.sha1 return None
python
def build_sha1(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.sha1 return None
[ "def", "build_sha1", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ")"...
get sha1 hash of build. :return: build sha1 or None if not found
[ "get", "sha1", "hash", "of", "build", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L178-L187
27,221
ARMmbed/icetea
icetea_lib/Result.py
Result.build_git_url
def build_git_url(self): """ get build git url. :return: build git url or None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.giturl return None
python
def build_git_url(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.giturl return None
[ "def", "build_git_url", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ...
get build git url. :return: build git url or None if not found
[ "get", "build", "git", "url", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L214-L223
27,222
ARMmbed/icetea
icetea_lib/Result.py
Result.build_data
def build_data(self): """ get build data. :return: build data or None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.get_data() return None
python
def build_data(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.get_data() return None
[ "def", "build_data", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ")"...
get build data. :return: build data or None if not found
[ "get", "build", "data", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L232-L241
27,223
ARMmbed/icetea
icetea_lib/Result.py
Result.build_branch
def build_branch(self): """ get build branch. :return: build branch or None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.branch return None
python
def build_branch(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.branch return None
[ "def", "build_branch", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", "...
get build branch. :return: build branch or None if not found
[ "get", "build", "branch", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L244-L253
27,224
ARMmbed/icetea
icetea_lib/Result.py
Result.buildcommit
def buildcommit(self): """ get build commit id. :return: build commit id or None if not found """ # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.commit_id return None
python
def buildcommit(self): # pylint: disable=len-as-condition if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.commit_id return None
[ "def", "buildcommit", "(", "self", ")", ":", "# pylint: disable=len-as-condition", "if", "len", "(", "self", ".", "dutinformation", ")", ">", "0", "and", "(", "self", ".", "dutinformation", ".", "get", "(", "0", ")", ".", "build", "is", "not", "None", ")...
get build commit id. :return: build commit id or None if not found
[ "get", "build", "commit", "id", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L262-L271
27,225
ARMmbed/icetea
icetea_lib/Result.py
Result.set_verdict
def set_verdict(self, verdict, retcode=-1, duration=-1): """ Set the final verdict for this Result. :param verdict: Verdict, must be from ['pass', 'fail', 'unknown', 'skip', 'inconclusive']' :param retcode: integer return code :param duration: test duration :return: Nothing :raises: ValueError if verdict was unknown. """ verdict = verdict.lower() if not verdict in ['pass', 'fail', 'unknown', 'skip', 'inconclusive']: raise ValueError("Unknown verdict {}".format(verdict)) if retcode == -1 and verdict == 'pass': retcode = 0 self.__verdict = verdict self.retcode = retcode if duration >= 0: self.duration = duration
python
def set_verdict(self, verdict, retcode=-1, duration=-1): verdict = verdict.lower() if not verdict in ['pass', 'fail', 'unknown', 'skip', 'inconclusive']: raise ValueError("Unknown verdict {}".format(verdict)) if retcode == -1 and verdict == 'pass': retcode = 0 self.__verdict = verdict self.retcode = retcode if duration >= 0: self.duration = duration
[ "def", "set_verdict", "(", "self", ",", "verdict", ",", "retcode", "=", "-", "1", ",", "duration", "=", "-", "1", ")", ":", "verdict", "=", "verdict", ".", "lower", "(", ")", "if", "not", "verdict", "in", "[", "'pass'", ",", "'fail'", ",", "'unknow...
Set the final verdict for this Result. :param verdict: Verdict, must be from ['pass', 'fail', 'unknown', 'skip', 'inconclusive']' :param retcode: integer return code :param duration: test duration :return: Nothing :raises: ValueError if verdict was unknown.
[ "Set", "the", "final", "verdict", "for", "this", "Result", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L352-L370
27,226
ARMmbed/icetea
icetea_lib/Result.py
Result.build_result_metadata
def build_result_metadata(self, data=None, args=None): """ collect metadata into this object :param data: dict :param args: build from args instead of data """ data = data if data else self._build_result_metainfo(args) if data.get("build_branch"): self.build_branch = data.get("build_branch") if data.get("buildcommit"): self.buildcommit = data.get("buildcommit") if data.get("build_git_url"): self.build_git_url = data.get("build_git_url") if data.get("build_url"): self.build_url = data.get("build_url") if data.get("campaign"): self.campaign = data.get("campaign") if data.get("job_id"): self.job_id = data.get("job_id") if data.get("toolchain"): self.toolchain = data.get("toolchain") if data.get("build_date"): self.build_date = data.get("build_date")
python
def build_result_metadata(self, data=None, args=None): data = data if data else self._build_result_metainfo(args) if data.get("build_branch"): self.build_branch = data.get("build_branch") if data.get("buildcommit"): self.buildcommit = data.get("buildcommit") if data.get("build_git_url"): self.build_git_url = data.get("build_git_url") if data.get("build_url"): self.build_url = data.get("build_url") if data.get("campaign"): self.campaign = data.get("campaign") if data.get("job_id"): self.job_id = data.get("job_id") if data.get("toolchain"): self.toolchain = data.get("toolchain") if data.get("build_date"): self.build_date = data.get("build_date")
[ "def", "build_result_metadata", "(", "self", ",", "data", "=", "None", ",", "args", "=", "None", ")", ":", "data", "=", "data", "if", "data", "else", "self", ".", "_build_result_metainfo", "(", "args", ")", "if", "data", ".", "get", "(", "\"build_branch\...
collect metadata into this object :param data: dict :param args: build from args instead of data
[ "collect", "metadata", "into", "this", "object" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L372-L395
27,227
ARMmbed/icetea
icetea_lib/Result.py
Result._build_result_metainfo
def _build_result_metainfo(args): """ Internal helper for collecting metadata from args to results """ data = dict() if hasattr(args, "branch") and args.branch: data["build_branch"] = args.branch if hasattr(args, "commitId") and args.commitId: data["buildcommit"] = args.commitId if hasattr(args, "gitUrl") and args.gitUrl: data["build_git_url"] = args.gitUrl if hasattr(args, "buildUrl") and args.buildUrl: data["build_url"] = args.buildUrl if hasattr(args, "campaign") and args.campaign: data["campaign"] = args.campaign if hasattr(args, "jobId") and args.jobId: data["job_id"] = args.jobId if hasattr(args, "toolchain") and args.toolchain: data["toolchain"] = args.toolchain if hasattr(args, "buildDate") and args.buildDate: data["build_date"] = args.buildDate return data
python
def _build_result_metainfo(args): data = dict() if hasattr(args, "branch") and args.branch: data["build_branch"] = args.branch if hasattr(args, "commitId") and args.commitId: data["buildcommit"] = args.commitId if hasattr(args, "gitUrl") and args.gitUrl: data["build_git_url"] = args.gitUrl if hasattr(args, "buildUrl") and args.buildUrl: data["build_url"] = args.buildUrl if hasattr(args, "campaign") and args.campaign: data["campaign"] = args.campaign if hasattr(args, "jobId") and args.jobId: data["job_id"] = args.jobId if hasattr(args, "toolchain") and args.toolchain: data["toolchain"] = args.toolchain if hasattr(args, "buildDate") and args.buildDate: data["build_date"] = args.buildDate return data
[ "def", "_build_result_metainfo", "(", "args", ")", ":", "data", "=", "dict", "(", ")", "if", "hasattr", "(", "args", ",", "\"branch\"", ")", "and", "args", ".", "branch", ":", "data", "[", "\"build_branch\"", "]", "=", "args", ".", "branch", "if", "has...
Internal helper for collecting metadata from args to results
[ "Internal", "helper", "for", "collecting", "metadata", "from", "args", "to", "results" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L398-L419
27,228
ARMmbed/icetea
icetea_lib/Result.py
Result.get_duration
def get_duration(self, seconds=False): """ Get test case duration. :param seconds: if set to True, return tc duration in seconds, otherwise as str( datetime.timedelta) :return: str(datetime.timedelta) or duration as string in seconds """ if seconds: return str(self.duration) delta = datetime.timedelta(seconds=self.duration) return str(delta)
python
def get_duration(self, seconds=False): if seconds: return str(self.duration) delta = datetime.timedelta(seconds=self.duration) return str(delta)
[ "def", "get_duration", "(", "self", ",", "seconds", "=", "False", ")", ":", "if", "seconds", ":", "return", "str", "(", "self", ".", "duration", ")", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "duration", ")", "return...
Get test case duration. :param seconds: if set to True, return tc duration in seconds, otherwise as str( datetime.timedelta) :return: str(datetime.timedelta) or duration as string in seconds
[ "Get", "test", "case", "duration", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L531-L542
27,229
ARMmbed/icetea
icetea_lib/Result.py
Result.has_logs
def has_logs(self): """ Check if log files are available and return file names if they exist. :return: list """ found_files = [] if self.logpath is None: return found_files if os.path.exists(self.logpath): for root, _, files in os.walk(os.path.abspath(self.logpath)): for fil in files: found_files.append(os.path.join(root, fil)) return found_files
python
def has_logs(self): found_files = [] if self.logpath is None: return found_files if os.path.exists(self.logpath): for root, _, files in os.walk(os.path.abspath(self.logpath)): for fil in files: found_files.append(os.path.join(root, fil)) return found_files
[ "def", "has_logs", "(", "self", ")", ":", "found_files", "=", "[", "]", "if", "self", ".", "logpath", "is", "None", ":", "return", "found_files", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "logpath", ")", ":", "for", "root", ",", "_"...
Check if log files are available and return file names if they exist. :return: list
[ "Check", "if", "log", "files", "are", "available", "and", "return", "file", "names", "if", "they", "exist", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L553-L567
27,230
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutProcess.py
DutProcess.open_connection
def open_connection(self): """ Open connection by starting the process. :raises: DutConnectionError """ self.logger.debug("Open CLI Process '%s'", (self.comport), extra={'type': '<->'}) self.cmd = self.comport if isinstance(self.comport, list) else [self.comport] if not self.comport: raise DutConnectionError("Process not defined!") try: self.build = Build.init(self.cmd[0]) except NotImplementedError as error: self.logger.error("Build initialization failed. Check your build location.") self.logger.debug(error) raise DutConnectionError(error) # Start process&reader thread. Call Dut.process_dut() when new data is coming app = self.config.get("application") if app and app.get("bin_args"): self.cmd = self.cmd + app.get("bin_args") try: self.start_process(self.cmd, processing_callback=lambda: Dut.process_dut(self)) except KeyboardInterrupt: raise except Exception as error: raise DutConnectionError("Couldn't start DUT target process {}".format(error))
python
def open_connection(self): self.logger.debug("Open CLI Process '%s'", (self.comport), extra={'type': '<->'}) self.cmd = self.comport if isinstance(self.comport, list) else [self.comport] if not self.comport: raise DutConnectionError("Process not defined!") try: self.build = Build.init(self.cmd[0]) except NotImplementedError as error: self.logger.error("Build initialization failed. Check your build location.") self.logger.debug(error) raise DutConnectionError(error) # Start process&reader thread. Call Dut.process_dut() when new data is coming app = self.config.get("application") if app and app.get("bin_args"): self.cmd = self.cmd + app.get("bin_args") try: self.start_process(self.cmd, processing_callback=lambda: Dut.process_dut(self)) except KeyboardInterrupt: raise except Exception as error: raise DutConnectionError("Couldn't start DUT target process {}".format(error))
[ "def", "open_connection", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Open CLI Process '%s'\"", ",", "(", "self", ".", "comport", ")", ",", "extra", "=", "{", "'type'", ":", "'<->'", "}", ")", "self", ".", "cmd", "=", "self", ...
Open connection by starting the process. :raises: DutConnectionError
[ "Open", "connection", "by", "starting", "the", "process", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutProcess.py#L42-L68
27,231
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutProcess.py
DutProcess.writeline
def writeline(self, data, crlf="\n"): # pylint: disable=arguments-differ """ Write data to process. :param data: data to write :param crlf: line end character :return: Nothing """ GenericProcess.writeline(self, data, crlf=crlf)
python
def writeline(self, data, crlf="\n"): # pylint: disable=arguments-differ GenericProcess.writeline(self, data, crlf=crlf)
[ "def", "writeline", "(", "self", ",", "data", ",", "crlf", "=", "\"\\n\"", ")", ":", "# pylint: disable=arguments-differ", "GenericProcess", ".", "writeline", "(", "self", ",", "data", ",", "crlf", "=", "crlf", ")" ]
Write data to process. :param data: data to write :param crlf: line end character :return: Nothing
[ "Write", "data", "to", "process", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutProcess.py#L96-L104
27,232
ARMmbed/icetea
icetea_lib/Plugin/plugins/FileApi.py
FileApiPlugin._jsonfileconstructor
def _jsonfileconstructor(self, filename=None, filepath=None, logger=None): """ Constructor method for the JsonFile object. :param filename: Name of the file :param filepath: Path to the file :param logger: Optional logger. :return: JsonFile """ if filepath: path = filepath else: tc_path = os.path.abspath(os.path.join(inspect.getfile(self.bench.__class__), os.pardir)) path = os.path.abspath(os.path.join(tc_path, os.pardir, "session_data")) name = "default_file.json" if not filename else filename log = self.bench.logger if not logger else logger self.bench.logger.info("Setting json file location to: {}".format(path)) return files.JsonFile(log, path, name)
python
def _jsonfileconstructor(self, filename=None, filepath=None, logger=None): if filepath: path = filepath else: tc_path = os.path.abspath(os.path.join(inspect.getfile(self.bench.__class__), os.pardir)) path = os.path.abspath(os.path.join(tc_path, os.pardir, "session_data")) name = "default_file.json" if not filename else filename log = self.bench.logger if not logger else logger self.bench.logger.info("Setting json file location to: {}".format(path)) return files.JsonFile(log, path, name)
[ "def", "_jsonfileconstructor", "(", "self", ",", "filename", "=", "None", ",", "filepath", "=", "None", ",", "logger", "=", "None", ")", ":", "if", "filepath", ":", "path", "=", "filepath", "else", ":", "tc_path", "=", "os", ".", "path", ".", "abspath"...
Constructor method for the JsonFile object. :param filename: Name of the file :param filepath: Path to the file :param logger: Optional logger. :return: JsonFile
[ "Constructor", "method", "for", "the", "JsonFile", "object", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/FileApi.py#L52-L70
27,233
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
NonBlockingStreamReader._get_sd
def _get_sd(file_descr): """ Get streamdescriptor matching file_descr fileno. :param file_descr: file object :return: StreamDescriptor or None """ for stream_descr in NonBlockingStreamReader._streams: if file_descr == stream_descr.stream.fileno(): return stream_descr return None
python
def _get_sd(file_descr): for stream_descr in NonBlockingStreamReader._streams: if file_descr == stream_descr.stream.fileno(): return stream_descr return None
[ "def", "_get_sd", "(", "file_descr", ")", ":", "for", "stream_descr", "in", "NonBlockingStreamReader", ".", "_streams", ":", "if", "file_descr", "==", "stream_descr", ".", "stream", ".", "fileno", "(", ")", ":", "return", "stream_descr", "return", "None" ]
Get streamdescriptor matching file_descr fileno. :param file_descr: file object :return: StreamDescriptor or None
[ "Get", "streamdescriptor", "matching", "file_descr", "fileno", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L76-L86
27,234
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
NonBlockingStreamReader._read_fd
def _read_fd(file_descr): """ Read incoming data from file handle. Then find the matching StreamDescriptor by file_descr value. :param file_descr: file object :return: Return number of bytes read """ try: line = os.read(file_descr, 1024 * 1024) except OSError: stream_desc = NonBlockingStreamReader._get_sd(file_descr) if stream_desc is not None: stream_desc.has_error = True if stream_desc.callback is not None: stream_desc.callback() return 0 if line: stream_desc = NonBlockingStreamReader._get_sd(file_descr) if stream_desc is None: return 0 # Process closing if IS_PYTHON3: try: # @TODO: further develop for not ascii/unicode binary content line = line.decode("ascii") except UnicodeDecodeError: line = repr(line) stream_desc.buf += line # Break lines split = stream_desc.buf.split(os.linesep) for line in split[:-1]: stream_desc.read_queue.appendleft(strip_escape(line.strip())) if stream_desc.callback is not None: stream_desc.callback() # Store the remainded, its either '' if last char was '\n' # or remaining buffer before line end stream_desc.buf = split[-1] return len(line) return 0
python
def _read_fd(file_descr): try: line = os.read(file_descr, 1024 * 1024) except OSError: stream_desc = NonBlockingStreamReader._get_sd(file_descr) if stream_desc is not None: stream_desc.has_error = True if stream_desc.callback is not None: stream_desc.callback() return 0 if line: stream_desc = NonBlockingStreamReader._get_sd(file_descr) if stream_desc is None: return 0 # Process closing if IS_PYTHON3: try: # @TODO: further develop for not ascii/unicode binary content line = line.decode("ascii") except UnicodeDecodeError: line = repr(line) stream_desc.buf += line # Break lines split = stream_desc.buf.split(os.linesep) for line in split[:-1]: stream_desc.read_queue.appendleft(strip_escape(line.strip())) if stream_desc.callback is not None: stream_desc.callback() # Store the remainded, its either '' if last char was '\n' # or remaining buffer before line end stream_desc.buf = split[-1] return len(line) return 0
[ "def", "_read_fd", "(", "file_descr", ")", ":", "try", ":", "line", "=", "os", ".", "read", "(", "file_descr", ",", "1024", "*", "1024", ")", "except", "OSError", ":", "stream_desc", "=", "NonBlockingStreamReader", ".", "_get_sd", "(", "file_descr", ")", ...
Read incoming data from file handle. Then find the matching StreamDescriptor by file_descr value. :param file_descr: file object :return: Return number of bytes read
[ "Read", "incoming", "data", "from", "file", "handle", ".", "Then", "find", "the", "matching", "StreamDescriptor", "by", "file_descr", "value", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L89-L129
27,235
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
NonBlockingStreamReader._read_select_kqueue
def _read_select_kqueue(k_queue): """ Read PIPES using BSD Kqueue """ npipes = len(NonBlockingStreamReader._streams) # Create list of kevent objects # pylint: disable=no-member kevents = [select.kevent(s.stream.fileno(), filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD | select.KQ_EV_ENABLE) for s in NonBlockingStreamReader._streams] while NonBlockingStreamReader._run_flag: events = k_queue.control(kevents, npipes, 0.5) # Wake up twice in second for event in events: if event.filter == select.KQ_FILTER_READ: # pylint: disable=no-member NonBlockingStreamReader._read_fd(event.ident) # Check if new pipes added. if npipes != len(NonBlockingStreamReader._streams): return
python
def _read_select_kqueue(k_queue): npipes = len(NonBlockingStreamReader._streams) # Create list of kevent objects # pylint: disable=no-member kevents = [select.kevent(s.stream.fileno(), filter=select.KQ_FILTER_READ, flags=select.KQ_EV_ADD | select.KQ_EV_ENABLE) for s in NonBlockingStreamReader._streams] while NonBlockingStreamReader._run_flag: events = k_queue.control(kevents, npipes, 0.5) # Wake up twice in second for event in events: if event.filter == select.KQ_FILTER_READ: # pylint: disable=no-member NonBlockingStreamReader._read_fd(event.ident) # Check if new pipes added. if npipes != len(NonBlockingStreamReader._streams): return
[ "def", "_read_select_kqueue", "(", "k_queue", ")", ":", "npipes", "=", "len", "(", "NonBlockingStreamReader", ".", "_streams", ")", "# Create list of kevent objects", "# pylint: disable=no-member", "kevents", "=", "[", "select", ".", "kevent", "(", "s", ".", "stream...
Read PIPES using BSD Kqueue
[ "Read", "PIPES", "using", "BSD", "Kqueue" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L167-L185
27,236
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
NonBlockingStreamReader.stop
def stop(self): """ Stop the reader """ # print('stopping NonBlockingStreamReader..') # print('acquire..') NonBlockingStreamReader._stream_mtx.acquire() # print('acquire..ok') NonBlockingStreamReader._streams.remove(self._descriptor) if not NonBlockingStreamReader._streams: NonBlockingStreamReader._run_flag = False # print('release..') NonBlockingStreamReader._stream_mtx.release() # print('release..ok') if NonBlockingStreamReader._run_flag is False: # print('join..') NonBlockingStreamReader._rt.join() # print('join..ok') del NonBlockingStreamReader._rt NonBlockingStreamReader._rt = None
python
def stop(self): # print('stopping NonBlockingStreamReader..') # print('acquire..') NonBlockingStreamReader._stream_mtx.acquire() # print('acquire..ok') NonBlockingStreamReader._streams.remove(self._descriptor) if not NonBlockingStreamReader._streams: NonBlockingStreamReader._run_flag = False # print('release..') NonBlockingStreamReader._stream_mtx.release() # print('release..ok') if NonBlockingStreamReader._run_flag is False: # print('join..') NonBlockingStreamReader._rt.join() # print('join..ok') del NonBlockingStreamReader._rt NonBlockingStreamReader._rt = None
[ "def", "stop", "(", "self", ")", ":", "# print('stopping NonBlockingStreamReader..')", "# print('acquire..')", "NonBlockingStreamReader", ".", "_stream_mtx", ".", "acquire", "(", ")", "# print('acquire..ok')", "NonBlockingStreamReader", ".", "_streams", ".", "remove", "(", ...
Stop the reader
[ "Stop", "the", "reader" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L219-L238
27,237
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
GenericProcess.use_gdbs
def use_gdbs(self, gdbs=True, port=2345): """ Set gdbs use for process. :param gdbs: Boolean, default is True :param port: Port number for gdbserver """ self.gdbs = gdbs self.gdbs_port = port
python
def use_gdbs(self, gdbs=True, port=2345): self.gdbs = gdbs self.gdbs_port = port
[ "def", "use_gdbs", "(", "self", ",", "gdbs", "=", "True", ",", "port", "=", "2345", ")", ":", "self", ".", "gdbs", "=", "gdbs", "self", ".", "gdbs_port", "=", "port" ]
Set gdbs use for process. :param gdbs: Boolean, default is True :param port: Port number for gdbserver
[ "Set", "gdbs", "use", "for", "process", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L331-L339
27,238
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
GenericProcess.use_valgrind
def use_valgrind(self, tool, xml, console, track_origins, valgrind_extra_params): """ Use Valgrind. :param tool: Tool name, must be memcheck, callgrind or massif :param xml: Boolean output xml :param console: Dump output to console, Boolean :param track_origins: Boolean, set --track-origins=yes :param valgrind_extra_params: Extra parameters :return: Nothing :raises: AttributeError if invalid tool set. """ self.valgrind = tool self.valgrind_xml = xml self.valgrind_console = console self.valgrind_track_origins = track_origins self.valgrind_extra_params = valgrind_extra_params if not tool in ['memcheck', 'callgrind', 'massif']: raise AttributeError("Invalid valgrind tool: %s" % tool)
python
def use_valgrind(self, tool, xml, console, track_origins, valgrind_extra_params): self.valgrind = tool self.valgrind_xml = xml self.valgrind_console = console self.valgrind_track_origins = track_origins self.valgrind_extra_params = valgrind_extra_params if not tool in ['memcheck', 'callgrind', 'massif']: raise AttributeError("Invalid valgrind tool: %s" % tool)
[ "def", "use_valgrind", "(", "self", ",", "tool", ",", "xml", ",", "console", ",", "track_origins", ",", "valgrind_extra_params", ")", ":", "self", ".", "valgrind", "=", "tool", "self", ".", "valgrind_xml", "=", "xml", "self", ".", "valgrind_console", "=", ...
Use Valgrind. :param tool: Tool name, must be memcheck, callgrind or massif :param xml: Boolean output xml :param console: Dump output to console, Boolean :param track_origins: Boolean, set --track-origins=yes :param valgrind_extra_params: Extra parameters :return: Nothing :raises: AttributeError if invalid tool set.
[ "Use", "Valgrind", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L359-L377
27,239
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
GenericProcess.__get_valgrind_params
def __get_valgrind_params(self): """ Get Valgrind command as list. :return: list """ valgrind = [] if self.valgrind: valgrind.extend(['valgrind']) if self.valgrind == 'memcheck': valgrind.extend(['--tool=memcheck', '--leak-check=full']) if self.valgrind_track_origins: valgrind.extend(['--track-origins=yes']) if self.valgrind_console: # just dump the default output, which is text dumped to console valgrind.extend([]) elif self.valgrind_xml: valgrind.extend([ '--xml=yes', '--xml-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_mem.xml', prepend_tc_name=True) ]) else: valgrind.extend([ '--log-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_mem.txt') ]) elif self.valgrind == 'callgrind': valgrind.extend([ '--tool=callgrind', '--dump-instr=yes', '--simulate-cache=yes', '--collect-jumps=yes']) if self.valgrind_console: # just dump the default output, which is text dumped to console valgrind.extend([]) elif self.valgrind_xml: valgrind.extend([ '--xml=yes', '--xml-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_calls.xml', prepend_tc_name=True) ]) else: valgrind.extend([ '--callgrind-out-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_calls.data') ]) elif self.valgrind == 'massif': valgrind.extend(['--tool=massif']) valgrind.extend([ '--massif-out-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_massif.data') ]) # this allows one to specify misc params to valgrind, # eg. "--threshold=0.4" to get some more data from massif if self.valgrind_extra_params != '': valgrind.extend(self.valgrind_extra_params.split()) return valgrind
python
def __get_valgrind_params(self): valgrind = [] if self.valgrind: valgrind.extend(['valgrind']) if self.valgrind == 'memcheck': valgrind.extend(['--tool=memcheck', '--leak-check=full']) if self.valgrind_track_origins: valgrind.extend(['--track-origins=yes']) if self.valgrind_console: # just dump the default output, which is text dumped to console valgrind.extend([]) elif self.valgrind_xml: valgrind.extend([ '--xml=yes', '--xml-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_mem.xml', prepend_tc_name=True) ]) else: valgrind.extend([ '--log-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_mem.txt') ]) elif self.valgrind == 'callgrind': valgrind.extend([ '--tool=callgrind', '--dump-instr=yes', '--simulate-cache=yes', '--collect-jumps=yes']) if self.valgrind_console: # just dump the default output, which is text dumped to console valgrind.extend([]) elif self.valgrind_xml: valgrind.extend([ '--xml=yes', '--xml-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_calls.xml', prepend_tc_name=True) ]) else: valgrind.extend([ '--callgrind-out-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_calls.data') ]) elif self.valgrind == 'massif': valgrind.extend(['--tool=massif']) valgrind.extend([ '--massif-out-file=' + LogManager.get_testcase_logfilename( self.name + '_valgrind_massif.data') ]) # this allows one to specify misc params to valgrind, # eg. "--threshold=0.4" to get some more data from massif if self.valgrind_extra_params != '': valgrind.extend(self.valgrind_extra_params.split()) return valgrind
[ "def", "__get_valgrind_params", "(", "self", ")", ":", "valgrind", "=", "[", "]", "if", "self", ".", "valgrind", ":", "valgrind", ".", "extend", "(", "[", "'valgrind'", "]", ")", "if", "self", ".", "valgrind", "==", "'memcheck'", ":", "valgrind", ".", ...
Get Valgrind command as list. :return: list
[ "Get", "Valgrind", "command", "as", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L379-L438
27,240
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
GenericProcess.writeline
def writeline(self, data, crlf="\r\n"): """ Writeline implementation. :param data: Data to write :param crlf: Line end characters, defailt is \r\n :return: Nothing :raises: RuntimeError if errors happen while writing to PIPE or process stops. """ if self.read_thread: if self.read_thread.has_error(): raise RuntimeError("Error writing PIPE") # Check if process still alive if self.proc.poll() is not None: raise RuntimeError("Process stopped") if self.__print_io: self.logger.info(data, extra={'type': '-->'}) self.proc.stdin.write(bytearray(data + crlf, 'ascii')) self.proc.stdin.flush()
python
def writeline(self, data, crlf="\r\n"): if self.read_thread: if self.read_thread.has_error(): raise RuntimeError("Error writing PIPE") # Check if process still alive if self.proc.poll() is not None: raise RuntimeError("Process stopped") if self.__print_io: self.logger.info(data, extra={'type': '-->'}) self.proc.stdin.write(bytearray(data + crlf, 'ascii')) self.proc.stdin.flush()
[ "def", "writeline", "(", "self", ",", "data", ",", "crlf", "=", "\"\\r\\n\"", ")", ":", "if", "self", ".", "read_thread", ":", "if", "self", ".", "read_thread", ".", "has_error", "(", ")", ":", "raise", "RuntimeError", "(", "\"Error writing PIPE\"", ")", ...
Writeline implementation. :param data: Data to write :param crlf: Line end characters, defailt is \r\n :return: Nothing :raises: RuntimeError if errors happen while writing to PIPE or process stops.
[ "Writeline", "implementation", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L572-L590
27,241
ARMmbed/icetea
icetea_lib/Randomize/seed.py
SeedInteger.load
def load(filename): """ Load seed from a file. :param filename: Source file name :return: SeedInteger """ json_obj = Seed.load(filename) return SeedInteger(json_obj["seed_value"], json_obj["seed_id"], json_obj["date"])
python
def load(filename): json_obj = Seed.load(filename) return SeedInteger(json_obj["seed_value"], json_obj["seed_id"], json_obj["date"])
[ "def", "load", "(", "filename", ")", ":", "json_obj", "=", "Seed", ".", "load", "(", "filename", ")", "return", "SeedInteger", "(", "json_obj", "[", "\"seed_value\"", "]", ",", "json_obj", "[", "\"seed_id\"", "]", ",", "json_obj", "[", "\"date\"", "]", "...
Load seed from a file. :param filename: Source file name :return: SeedInteger
[ "Load", "seed", "from", "a", "file", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Randomize/seed.py#L100-L108
27,242
ARMmbed/icetea
icetea_lib/enhancedserial.py
EnhancedSerial.get_pyserial_version
def get_pyserial_version(self): """! Retrieve pyserial module version @return Returns float with pyserial module number """ pyserial_version = pkg_resources.require("pyserial")[0].version version = 3.0 match = self.re_float.search(pyserial_version) if match: try: version = float(match.group(0)) except ValueError: version = 3.0 # We will assume you've got latest (3.0+) return version
python
def get_pyserial_version(self): pyserial_version = pkg_resources.require("pyserial")[0].version version = 3.0 match = self.re_float.search(pyserial_version) if match: try: version = float(match.group(0)) except ValueError: version = 3.0 # We will assume you've got latest (3.0+) return version
[ "def", "get_pyserial_version", "(", "self", ")", ":", "pyserial_version", "=", "pkg_resources", ".", "require", "(", "\"pyserial\"", ")", "[", "0", "]", ".", "version", "version", "=", "3.0", "match", "=", "self", ".", "re_float", ".", "search", "(", "pyse...
! Retrieve pyserial module version @return Returns float with pyserial module number
[ "!", "Retrieve", "pyserial", "module", "version" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/enhancedserial.py#L40-L52
27,243
ARMmbed/icetea
icetea_lib/enhancedserial.py
EnhancedSerial.readline
def readline(self, timeout=1): """ maxsize is ignored, timeout in seconds is the max time that is way for a complete line """ tries = 0 while 1: try: block = self.read(512) if isinstance(block, bytes): block = block.decode() elif isinstance(block, str): block = block.decode() else: raise ValueError("Unknown data") except SerialTimeoutException: # Exception that is raised on write timeouts. block = '' except SerialException: # In case the device can not be found or can not be configured. block = '' except ValueError: # Will be raised when parameter are out of range, e.g. baud rate, data bits. # UnicodeError-Raised when a Unicode-related encoding or # decoding error occurs. It is a subclass of ValueError. block = '' with self.buffer_lock: # Let's lock, just in case self.buf += block pos = self.buf.find('\n') if pos >= 0: line, self.buf = self.buf[:pos+1], self.buf[pos+1:] return line tries += 1 if tries * self.timeout > timeout: break return None
python
def readline(self, timeout=1): tries = 0 while 1: try: block = self.read(512) if isinstance(block, bytes): block = block.decode() elif isinstance(block, str): block = block.decode() else: raise ValueError("Unknown data") except SerialTimeoutException: # Exception that is raised on write timeouts. block = '' except SerialException: # In case the device can not be found or can not be configured. block = '' except ValueError: # Will be raised when parameter are out of range, e.g. baud rate, data bits. # UnicodeError-Raised when a Unicode-related encoding or # decoding error occurs. It is a subclass of ValueError. block = '' with self.buffer_lock: # Let's lock, just in case self.buf += block pos = self.buf.find('\n') if pos >= 0: line, self.buf = self.buf[:pos+1], self.buf[pos+1:] return line tries += 1 if tries * self.timeout > timeout: break return None
[ "def", "readline", "(", "self", ",", "timeout", "=", "1", ")", ":", "tries", "=", "0", "while", "1", ":", "try", ":", "block", "=", "self", ".", "read", "(", "512", ")", "if", "isinstance", "(", "block", ",", "bytes", ")", ":", "block", "=", "b...
maxsize is ignored, timeout in seconds is the max time that is way for a complete line
[ "maxsize", "is", "ignored", "timeout", "in", "seconds", "is", "the", "max", "time", "that", "is", "way", "for", "a", "complete", "line" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/enhancedserial.py#L97-L132
27,244
ARMmbed/icetea
icetea_lib/enhancedserial.py
EnhancedSerial.readlines
def readlines(self, timeout=1): """ read all lines that are available. abort after timeout when no more data arrives. """ lines = [] while 1: line = self.readline(timeout=timeout) if line: lines.append(line) if not line or line[-1:] != '\n': break return lines
python
def readlines(self, timeout=1): lines = [] while 1: line = self.readline(timeout=timeout) if line: lines.append(line) if not line or line[-1:] != '\n': break return lines
[ "def", "readlines", "(", "self", ",", "timeout", "=", "1", ")", ":", "lines", "=", "[", "]", "while", "1", ":", "line", "=", "self", ".", "readline", "(", "timeout", "=", "timeout", ")", "if", "line", ":", "lines", ".", "append", "(", "line", ")"...
read all lines that are available. abort after timeout when no more data arrives.
[ "read", "all", "lines", "that", "are", "available", ".", "abort", "after", "timeout", "when", "no", "more", "data", "arrives", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/enhancedserial.py#L144-L156
27,245
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceRequirements.py
ResourceRequirements.set
def set(self, key, value): """ Sets the value for a specific requirement. :param key: Name of requirement to be set :param value: Value to set for requirement key :return: Nothing, modifies requirement """ if key == "tags": self._set_tag(tags=value) else: if isinstance(value, dict) and key in self._requirements and isinstance( self._requirements[key], dict): self._requirements[key] = merge(self._requirements[key], value) else: self._requirements[key] = value
python
def set(self, key, value): if key == "tags": self._set_tag(tags=value) else: if isinstance(value, dict) and key in self._requirements and isinstance( self._requirements[key], dict): self._requirements[key] = merge(self._requirements[key], value) else: self._requirements[key] = value
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "\"tags\"", ":", "self", ".", "_set_tag", "(", "tags", "=", "value", ")", "else", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "key", "in", "self...
Sets the value for a specific requirement. :param key: Name of requirement to be set :param value: Value to set for requirement key :return: Nothing, modifies requirement
[ "Sets", "the", "value", "for", "a", "specific", "requirement", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceRequirements.py#L32-L47
27,246
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceRequirements.py
ResourceRequirements._set_tag
def _set_tag(self, tag=None, tags=None, value=True): """ Sets the value of a specific tag or merges existing tags with a dict of new tags. Either tag or tags must be None. :param tag: Tag which needs to be set. :param tags: Set of tags which needs to be merged with existing tags. :param value: Value to set for net tag named by :param tag. :return: Nothing """ existing_tags = self._requirements.get("tags") if tags and not tag: existing_tags = merge(existing_tags, tags) self._requirements["tags"] = existing_tags elif tag and not tags: existing_tags[tag] = value self._requirements["tags"] = existing_tags
python
def _set_tag(self, tag=None, tags=None, value=True): existing_tags = self._requirements.get("tags") if tags and not tag: existing_tags = merge(existing_tags, tags) self._requirements["tags"] = existing_tags elif tag and not tags: existing_tags[tag] = value self._requirements["tags"] = existing_tags
[ "def", "_set_tag", "(", "self", ",", "tag", "=", "None", ",", "tags", "=", "None", ",", "value", "=", "True", ")", ":", "existing_tags", "=", "self", ".", "_requirements", ".", "get", "(", "\"tags\"", ")", "if", "tags", "and", "not", "tag", ":", "e...
Sets the value of a specific tag or merges existing tags with a dict of new tags. Either tag or tags must be None. :param tag: Tag which needs to be set. :param tags: Set of tags which needs to be merged with existing tags. :param value: Value to set for net tag named by :param tag. :return: Nothing
[ "Sets", "the", "value", "of", "a", "specific", "tag", "or", "merges", "existing", "tags", "with", "a", "dict", "of", "new", "tags", ".", "Either", "tag", "or", "tags", "must", "be", "None", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceRequirements.py#L85-L101
27,247
ARMmbed/icetea
icetea_lib/main.py
icetea_main
def icetea_main(): """ Main function for running Icetea. Calls sys.exit with the return code to exit. :return: Nothing. """ from icetea_lib import IceteaManager manager = IceteaManager.IceteaManager() return_code = manager.run() sys.exit(return_code)
python
def icetea_main(): from icetea_lib import IceteaManager manager = IceteaManager.IceteaManager() return_code = manager.run() sys.exit(return_code)
[ "def", "icetea_main", "(", ")", ":", "from", "icetea_lib", "import", "IceteaManager", "manager", "=", "IceteaManager", ".", "IceteaManager", "(", ")", "return_code", "=", "manager", ".", "run", "(", ")", "sys", ".", "exit", "(", "return_code", ")" ]
Main function for running Icetea. Calls sys.exit with the return code to exit. :return: Nothing.
[ "Main", "function", "for", "running", "Icetea", ".", "Calls", "sys", ".", "exit", "with", "the", "return", "code", "to", "exit", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/main.py#L19-L28
27,248
ARMmbed/icetea
build_docs.py
build_docs
def build_docs(location="doc-source", target=None, library="icetea_lib"): """ Build documentation for Icetea. Start by autogenerating module documentation and finish by building html. :param location: Documentation source :param target: Documentation target path :param library: Library location for autodoc. :return: -1 if something fails. 0 if successfull. """ cmd_ar = ["sphinx-apidoc", "-o", location, library] try: print("Generating api docs.") retcode = check_call(cmd_ar) except CalledProcessError as error: print("Documentation build failed. Return code: {}".format(error.returncode)) return 3 except OSError as error: print(error) print("Documentation build failed. Are you missing Sphinx? Please install sphinx using " "'pip install sphinx'.") return 3 target = "doc{}html".format(os.sep) if target is None else target cmd_ar = ["sphinx-build", "-b", "html", location, target] try: print("Building html documentation.") retcode = check_call(cmd_ar) except CalledProcessError as error: print("Documentation build failed. Return code: {}".format(error.returncode)) return 3 except OSError as error: print(error) print("Documentation build failed. Are you missing Sphinx? Please install sphinx using " "'pip install sphinx'.") return 3 print("Documentation built.") return 0
python
def build_docs(location="doc-source", target=None, library="icetea_lib"): cmd_ar = ["sphinx-apidoc", "-o", location, library] try: print("Generating api docs.") retcode = check_call(cmd_ar) except CalledProcessError as error: print("Documentation build failed. Return code: {}".format(error.returncode)) return 3 except OSError as error: print(error) print("Documentation build failed. Are you missing Sphinx? Please install sphinx using " "'pip install sphinx'.") return 3 target = "doc{}html".format(os.sep) if target is None else target cmd_ar = ["sphinx-build", "-b", "html", location, target] try: print("Building html documentation.") retcode = check_call(cmd_ar) except CalledProcessError as error: print("Documentation build failed. Return code: {}".format(error.returncode)) return 3 except OSError as error: print(error) print("Documentation build failed. Are you missing Sphinx? Please install sphinx using " "'pip install sphinx'.") return 3 print("Documentation built.") return 0
[ "def", "build_docs", "(", "location", "=", "\"doc-source\"", ",", "target", "=", "None", ",", "library", "=", "\"icetea_lib\"", ")", ":", "cmd_ar", "=", "[", "\"sphinx-apidoc\"", ",", "\"-o\"", ",", "location", ",", "library", "]", "try", ":", "print", "("...
Build documentation for Icetea. Start by autogenerating module documentation and finish by building html. :param location: Documentation source :param target: Documentation target path :param library: Library location for autodoc. :return: -1 if something fails. 0 if successfull.
[ "Build", "documentation", "for", "Icetea", ".", "Start", "by", "autogenerating", "module", "documentation", "and", "finish", "by", "building", "html", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/build_docs.py#L23-L60
27,249
ARMmbed/icetea
icetea_lib/Searcher.py
find_next
def find_next(lines, find_str, start_index): """ Find the next instance of find_str from lines starting from start_index. :param lines: Lines to look through :param find_str: String or Invert to look for :param start_index: Index to start from :return: (boolean, index, line) """ mode = None if isinstance(find_str, basestring): mode = 'normal' message = find_str elif isinstance(find_str, Invert): mode = 'invert' message = str(find_str) else: raise TypeError("Unsupported message type") for i in range(start_index, len(lines)): if re.search(message, lines[i]): return mode == 'normal', i, lines[i] elif message in lines[i]: return mode == 'normal', i, lines[i] if mode == 'invert': return True, len(lines), None raise LookupError("Not found")
python
def find_next(lines, find_str, start_index): mode = None if isinstance(find_str, basestring): mode = 'normal' message = find_str elif isinstance(find_str, Invert): mode = 'invert' message = str(find_str) else: raise TypeError("Unsupported message type") for i in range(start_index, len(lines)): if re.search(message, lines[i]): return mode == 'normal', i, lines[i] elif message in lines[i]: return mode == 'normal', i, lines[i] if mode == 'invert': return True, len(lines), None raise LookupError("Not found")
[ "def", "find_next", "(", "lines", ",", "find_str", ",", "start_index", ")", ":", "mode", "=", "None", "if", "isinstance", "(", "find_str", ",", "basestring", ")", ":", "mode", "=", "'normal'", "message", "=", "find_str", "elif", "isinstance", "(", "find_st...
Find the next instance of find_str from lines starting from start_index. :param lines: Lines to look through :param find_str: String or Invert to look for :param start_index: Index to start from :return: (boolean, index, line)
[ "Find", "the", "next", "instance", "of", "find_str", "from", "lines", "starting", "from", "start_index", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Searcher.py#L37-L62
27,250
ARMmbed/icetea
icetea_lib/Searcher.py
verify_message
def verify_message(lines, expected_response): """ Looks for expectedResponse in lines. :param lines: a list of strings to look through :param expected_response: list or str to look for in lines. :return: True or False. :raises: TypeError if expectedResponse was not list or str. LookUpError through FindNext function. """ position = 0 if isinstance(expected_response, basestring): expected_response = [expected_response] if isinstance(expected_response, set): expected_response = list(expected_response) if not isinstance(expected_response, list): raise TypeError("verify_message: expectedResponse must be list, set or string") for message in expected_response: try: found, position, _ = find_next(lines, message, position) if not found: return False position = position + 1 except TypeError: return False except LookupError: return False return True
python
def verify_message(lines, expected_response): position = 0 if isinstance(expected_response, basestring): expected_response = [expected_response] if isinstance(expected_response, set): expected_response = list(expected_response) if not isinstance(expected_response, list): raise TypeError("verify_message: expectedResponse must be list, set or string") for message in expected_response: try: found, position, _ = find_next(lines, message, position) if not found: return False position = position + 1 except TypeError: return False except LookupError: return False return True
[ "def", "verify_message", "(", "lines", ",", "expected_response", ")", ":", "position", "=", "0", "if", "isinstance", "(", "expected_response", ",", "basestring", ")", ":", "expected_response", "=", "[", "expected_response", "]", "if", "isinstance", "(", "expecte...
Looks for expectedResponse in lines. :param lines: a list of strings to look through :param expected_response: list or str to look for in lines. :return: True or False. :raises: TypeError if expectedResponse was not list or str. LookUpError through FindNext function.
[ "Looks", "for", "expectedResponse", "in", "lines", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Searcher.py#L65-L92
27,251
ARMmbed/icetea
icetea_lib/IceteaManager.py
_cleanlogs
def _cleanlogs(silent=False, log_location="log"): """ Cleans up Mbed-test default log directory. :param silent: Defaults to False :param log_location: Location of log files, defaults to "log" :return: Nothing """ try: print("cleaning up Icetea log directory.") shutil.rmtree(log_location, ignore_errors=silent, onerror=None if silent else _clean_onerror) except OSError as error: print(error)
python
def _cleanlogs(silent=False, log_location="log"): try: print("cleaning up Icetea log directory.") shutil.rmtree(log_location, ignore_errors=silent, onerror=None if silent else _clean_onerror) except OSError as error: print(error)
[ "def", "_cleanlogs", "(", "silent", "=", "False", ",", "log_location", "=", "\"log\"", ")", ":", "try", ":", "print", "(", "\"cleaning up Icetea log directory.\"", ")", "shutil", ".", "rmtree", "(", "log_location", ",", "ignore_errors", "=", "silent", ",", "on...
Cleans up Mbed-test default log directory. :param silent: Defaults to False :param log_location: Location of log files, defaults to "log" :return: Nothing
[ "Cleans", "up", "Mbed", "-", "test", "default", "log", "directory", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L50-L63
27,252
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager.list_suites
def list_suites(suitedir="./testcases/suites", cloud=False): """ Static method for listing suites from both local source and cloud. Uses PrettyTable to generate the table. :param suitedir: Local directory for suites. :param cloud: cloud module :return: PrettyTable object or None if no test cases were found """ suites = [] suites.extend(TestSuite.get_suite_files(suitedir)) # no suitedir, or no suites -> append cloud.get_campaigns() if cloud: names = cloud.get_campaign_names() if names: suites.append("------------------------------------") suites.append("FROM CLOUD:") suites.extend(names) if not suites: return None from prettytable import PrettyTable table = PrettyTable(["Testcase suites"]) for suite in suites: table.add_row([suite]) return table
python
def list_suites(suitedir="./testcases/suites", cloud=False): suites = [] suites.extend(TestSuite.get_suite_files(suitedir)) # no suitedir, or no suites -> append cloud.get_campaigns() if cloud: names = cloud.get_campaign_names() if names: suites.append("------------------------------------") suites.append("FROM CLOUD:") suites.extend(names) if not suites: return None from prettytable import PrettyTable table = PrettyTable(["Testcase suites"]) for suite in suites: table.add_row([suite]) return table
[ "def", "list_suites", "(", "suitedir", "=", "\"./testcases/suites\"", ",", "cloud", "=", "False", ")", ":", "suites", "=", "[", "]", "suites", ".", "extend", "(", "TestSuite", ".", "get_suite_files", "(", "suitedir", ")", ")", "# no suitedir, or no suites -> app...
Static method for listing suites from both local source and cloud. Uses PrettyTable to generate the table. :param suitedir: Local directory for suites. :param cloud: cloud module :return: PrettyTable object or None if no test cases were found
[ "Static", "method", "for", "listing", "suites", "from", "both", "local", "source", "and", "cloud", ".", "Uses", "PrettyTable", "to", "generate", "the", "table", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L129-L156
27,253
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager._parse_arguments
def _parse_arguments(): """ Static method for paring arguments """ parser = get_base_arguments(get_parser()) parser = get_tc_arguments(parser) args, unknown = parser.parse_known_args() return args, unknown
python
def _parse_arguments(): parser = get_base_arguments(get_parser()) parser = get_tc_arguments(parser) args, unknown = parser.parse_known_args() return args, unknown
[ "def", "_parse_arguments", "(", ")", ":", "parser", "=", "get_base_arguments", "(", "get_parser", "(", ")", ")", "parser", "=", "get_tc_arguments", "(", "parser", ")", "args", ",", "unknown", "=", "parser", ".", "parse_known_args", "(", ")", "return", "args"...
Static method for paring arguments
[ "Static", "method", "for", "paring", "arguments" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L159-L166
27,254
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager.check_args
def check_args(self): """ Validates that a valid number of arguments were received and that all arguments were recognised. :return: True or False. """ parser = get_base_arguments(get_parser()) parser = get_tc_arguments(parser) # Disable "Do not use len(SEQ) as condition value" # pylint: disable=C1801 if len(sys.argv) < 2: self.logger.error("Icetea called with no arguments! ") parser.print_help() return False elif not self.args.ignore_invalid_params and self.unknown: self.logger.error("Unknown parameters received, exiting. " "To ignore this add --ignore_invalid_params flag.") self.logger.error("Following parameters were unknown: {}".format(self.unknown)) parser.print_help() return False return True
python
def check_args(self): parser = get_base_arguments(get_parser()) parser = get_tc_arguments(parser) # Disable "Do not use len(SEQ) as condition value" # pylint: disable=C1801 if len(sys.argv) < 2: self.logger.error("Icetea called with no arguments! ") parser.print_help() return False elif not self.args.ignore_invalid_params and self.unknown: self.logger.error("Unknown parameters received, exiting. " "To ignore this add --ignore_invalid_params flag.") self.logger.error("Following parameters were unknown: {}".format(self.unknown)) parser.print_help() return False return True
[ "def", "check_args", "(", "self", ")", ":", "parser", "=", "get_base_arguments", "(", "get_parser", "(", ")", ")", "parser", "=", "get_tc_arguments", "(", "parser", ")", "# Disable \"Do not use len(SEQ) as condition value\"", "# pylint: disable=C1801", "if", "len", "(...
Validates that a valid number of arguments were received and that all arguments were recognised. :return: True or False.
[ "Validates", "that", "a", "valid", "number", "of", "arguments", "were", "received", "and", "that", "all", "arguments", "were", "recognised", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L168-L189
27,255
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager._init_pluginmanager
def _init_pluginmanager(self): """ Initialize PluginManager and load run wide plugins. """ self.pluginmanager = PluginManager(logger=self.logger) self.logger.debug("Registering execution wide plugins:") self.pluginmanager.load_default_run_plugins() self.pluginmanager.load_custom_run_plugins(self.args.plugin_path) self.logger.debug("Execution wide plugins loaded and registered.")
python
def _init_pluginmanager(self): self.pluginmanager = PluginManager(logger=self.logger) self.logger.debug("Registering execution wide plugins:") self.pluginmanager.load_default_run_plugins() self.pluginmanager.load_custom_run_plugins(self.args.plugin_path) self.logger.debug("Execution wide plugins loaded and registered.")
[ "def", "_init_pluginmanager", "(", "self", ")", ":", "self", ".", "pluginmanager", "=", "PluginManager", "(", "logger", "=", "self", ".", "logger", ")", "self", ".", "logger", ".", "debug", "(", "\"Registering execution wide plugins:\"", ")", "self", ".", "plu...
Initialize PluginManager and load run wide plugins.
[ "Initialize", "PluginManager", "and", "load", "run", "wide", "plugins", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L191-L199
27,256
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager.run
def run(self, args=None): """ Runs the set of tests within the given path. """ # Disable "Too many branches" and "Too many return statemets" warnings # pylint: disable=R0912,R0911 retcodesummary = ExitCodes.EXIT_SUCCESS self.args = args if args else self.args if not self.check_args(): return retcodesummary if self.args.clean: if not self.args.tc and not self.args.suite: return retcodesummary # If called with --version print version and exit version = get_fw_version() if self.args.version and version: print(version) return retcodesummary elif self.args.version and not version: print("Unable to get version. Have you installed Icetea correctly?") return retcodesummary self.logger.info("Using Icetea version {}".format(version) if version else "Unable to get Icetea version. Is Icetea installed?") # If cloud set, import cloud, get parameters from environment, initialize cloud cloud = self._init_cloud(self.args.cloud) # Check if called with listsuites. If so, print out suites either from cloud or from local if self.args.listsuites: table = self.list_suites(self.args.suitedir, cloud) if table is None: self.logger.error("No suites found!") retcodesummary = ExitCodes.EXIT_FAIL else: print(table) return retcodesummary try: testsuite = TestSuite(logger=self.logger, cloud_module=cloud, args=self.args) except SuiteException as error: self.logger.error("Something went wrong in suite creation! {}".format(error)) retcodesummary = ExitCodes.EXIT_INCONC return retcodesummary if self.args.list: if self.args.cloud: testsuite.update_testcases() testcases = testsuite.list_testcases() print(testcases) return retcodesummary results = self.runtestsuite(testsuite=testsuite) if not results: retcodesummary = ExitCodes.EXIT_SUCCESS elif results.failure_count() and self.args.failure_return_value is True: retcodesummary = ExitCodes.EXIT_FAIL elif results.inconclusive_count() and self.args.failure_return_value is True: retcodesummary = ExitCodes.EXIT_INCONC return retcodesummary
python
def run(self, args=None): # Disable "Too many branches" and "Too many return statemets" warnings # pylint: disable=R0912,R0911 retcodesummary = ExitCodes.EXIT_SUCCESS self.args = args if args else self.args if not self.check_args(): return retcodesummary if self.args.clean: if not self.args.tc and not self.args.suite: return retcodesummary # If called with --version print version and exit version = get_fw_version() if self.args.version and version: print(version) return retcodesummary elif self.args.version and not version: print("Unable to get version. Have you installed Icetea correctly?") return retcodesummary self.logger.info("Using Icetea version {}".format(version) if version else "Unable to get Icetea version. Is Icetea installed?") # If cloud set, import cloud, get parameters from environment, initialize cloud cloud = self._init_cloud(self.args.cloud) # Check if called with listsuites. If so, print out suites either from cloud or from local if self.args.listsuites: table = self.list_suites(self.args.suitedir, cloud) if table is None: self.logger.error("No suites found!") retcodesummary = ExitCodes.EXIT_FAIL else: print(table) return retcodesummary try: testsuite = TestSuite(logger=self.logger, cloud_module=cloud, args=self.args) except SuiteException as error: self.logger.error("Something went wrong in suite creation! {}".format(error)) retcodesummary = ExitCodes.EXIT_INCONC return retcodesummary if self.args.list: if self.args.cloud: testsuite.update_testcases() testcases = testsuite.list_testcases() print(testcases) return retcodesummary results = self.runtestsuite(testsuite=testsuite) if not results: retcodesummary = ExitCodes.EXIT_SUCCESS elif results.failure_count() and self.args.failure_return_value is True: retcodesummary = ExitCodes.EXIT_FAIL elif results.inconclusive_count() and self.args.failure_return_value is True: retcodesummary = ExitCodes.EXIT_INCONC return retcodesummary
[ "def", "run", "(", "self", ",", "args", "=", "None", ")", ":", "# Disable \"Too many branches\" and \"Too many return statemets\" warnings", "# pylint: disable=R0912,R0911", "retcodesummary", "=", "ExitCodes", ".", "EXIT_SUCCESS", "self", ".", "args", "=", "args", "if", ...
Runs the set of tests within the given path.
[ "Runs", "the", "set", "of", "tests", "within", "the", "given", "path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L201-L265
27,257
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager._cleanup_resourceprovider
def _cleanup_resourceprovider(self): """ Calls cleanup for ResourceProvider of this run. :return: Nothing """ # Disable too broad exception warning # pylint: disable=W0703 self.resourceprovider = ResourceProvider(self.args) try: self.resourceprovider.cleanup() self.logger.info("Cleanup done.") except Exception as error: self.logger.error("Cleanup failed! %s", error)
python
def _cleanup_resourceprovider(self): # Disable too broad exception warning # pylint: disable=W0703 self.resourceprovider = ResourceProvider(self.args) try: self.resourceprovider.cleanup() self.logger.info("Cleanup done.") except Exception as error: self.logger.error("Cleanup failed! %s", error)
[ "def", "_cleanup_resourceprovider", "(", "self", ")", ":", "# Disable too broad exception warning", "# pylint: disable=W0703", "self", ".", "resourceprovider", "=", "ResourceProvider", "(", "self", ".", "args", ")", "try", ":", "self", ".", "resourceprovider", ".", "c...
Calls cleanup for ResourceProvider of this run. :return: Nothing
[ "Calls", "cleanup", "for", "ResourceProvider", "of", "this", "run", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L292-L305
27,258
ARMmbed/icetea
icetea_lib/IceteaManager.py
IceteaManager._init_cloud
def _init_cloud(self, cloud_arg): """ Initializes Cloud module if cloud_arg is set. :param cloud_arg: taken from args.cloud :return: cloud module object instance """ # Disable too broad exception warning # pylint: disable=W0703 cloud = None if cloud_arg: try: if hasattr(self.args, "cm"): cloud_module = self.args.cm if self.args.cm else None self.logger.info("Creating cloud module {}.".format(cloud_module)) else: cloud_module = None cloud = Cloud(host=None, module=cloud_module, logger=self.logger, args=self.args) except Exception as error: self.logger.warning("Cloud module could not be initialized: {}".format(error)) cloud = None return cloud
python
def _init_cloud(self, cloud_arg): # Disable too broad exception warning # pylint: disable=W0703 cloud = None if cloud_arg: try: if hasattr(self.args, "cm"): cloud_module = self.args.cm if self.args.cm else None self.logger.info("Creating cloud module {}.".format(cloud_module)) else: cloud_module = None cloud = Cloud(host=None, module=cloud_module, logger=self.logger, args=self.args) except Exception as error: self.logger.warning("Cloud module could not be initialized: {}".format(error)) cloud = None return cloud
[ "def", "_init_cloud", "(", "self", ",", "cloud_arg", ")", ":", "# Disable too broad exception warning", "# pylint: disable=W0703", "cloud", "=", "None", "if", "cloud_arg", ":", "try", ":", "if", "hasattr", "(", "self", ".", "args", ",", "\"cm\"", ")", ":", "cl...
Initializes Cloud module if cloud_arg is set. :param cloud_arg: taken from args.cloud :return: cloud module object instance
[ "Initializes", "Cloud", "module", "if", "cloud_arg", "is", "set", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L307-L329
27,259
ARMmbed/icetea
icetea_lib/Reports/ReportHtml.py
ReportHtml.generate
def generate(self, *args, **kwargs): """ Implementation for the generate method defined in ReportBase. Generates a html report and saves it. :param args: 1 argument, which is the filename :param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh' :return: Nothing. """ title = kwargs.get("title") heads = kwargs.get("heads") refresh = kwargs.get("refresh") filename = args[0] report = self._create(title, heads, refresh, path_start=os.path.dirname(filename)) ReportHtml.save(report, filename)
python
def generate(self, *args, **kwargs): title = kwargs.get("title") heads = kwargs.get("heads") refresh = kwargs.get("refresh") filename = args[0] report = self._create(title, heads, refresh, path_start=os.path.dirname(filename)) ReportHtml.save(report, filename)
[ "def", "generate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "title", "=", "kwargs", ".", "get", "(", "\"title\"", ")", "heads", "=", "kwargs", ".", "get", "(", "\"heads\"", ")", "refresh", "=", "kwargs", ".", "get", "(", ...
Implementation for the generate method defined in ReportBase. Generates a html report and saves it. :param args: 1 argument, which is the filename :param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh' :return: Nothing.
[ "Implementation", "for", "the", "generate", "method", "defined", "in", "ReportBase", ".", "Generates", "a", "html", "report", "and", "saves", "it", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportHtml.py#L35-L49
27,260
ARMmbed/icetea
icetea_lib/tools/tools.py
check_int
def check_int(integer): """ Check if number is integer or not. :param integer: Number as str :return: Boolean """ if not isinstance(integer, str): return False if integer[0] in ('-', '+'): return integer[1:].isdigit() return integer.isdigit()
python
def check_int(integer): if not isinstance(integer, str): return False if integer[0] in ('-', '+'): return integer[1:].isdigit() return integer.isdigit()
[ "def", "check_int", "(", "integer", ")", ":", "if", "not", "isinstance", "(", "integer", ",", "str", ")", ":", "return", "False", "if", "integer", "[", "0", "]", "in", "(", "'-'", ",", "'+'", ")", ":", "return", "integer", "[", "1", ":", "]", "."...
Check if number is integer or not. :param integer: Number as str :return: Boolean
[ "Check", "if", "number", "is", "integer", "or", "not", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L92-L103
27,261
ARMmbed/icetea
icetea_lib/tools/tools.py
_is_pid_running_on_unix
def _is_pid_running_on_unix(pid): """ Check if PID is running for Unix systems. """ try: os.kill(pid, 0) except OSError as err: # if error is ESRCH, it means the process doesn't exist return not err.errno == os.errno.ESRCH return True
python
def _is_pid_running_on_unix(pid): try: os.kill(pid, 0) except OSError as err: # if error is ESRCH, it means the process doesn't exist return not err.errno == os.errno.ESRCH return True
[ "def", "_is_pid_running_on_unix", "(", "pid", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "0", ")", "except", "OSError", "as", "err", ":", "# if error is ESRCH, it means the process doesn't exist", "return", "not", "err", ".", "errno", "==", "os"...
Check if PID is running for Unix systems.
[ "Check", "if", "PID", "is", "running", "for", "Unix", "systems", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L135-L144
27,262
ARMmbed/icetea
icetea_lib/tools/tools.py
_is_pid_running_on_windows
def _is_pid_running_on_windows(pid): """ Check if PID is running for Windows systems """ import ctypes.wintypes kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) if handle == 0: return False exit_code = ctypes.wintypes.DWORD() ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)) is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE) # pylint: disable=undefined-variable kernel32.CloseHandle(handle) return is_alive
python
def _is_pid_running_on_windows(pid): import ctypes.wintypes kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) if handle == 0: return False exit_code = ctypes.wintypes.DWORD() ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)) is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE) # pylint: disable=undefined-variable kernel32.CloseHandle(handle) return is_alive
[ "def", "_is_pid_running_on_windows", "(", "pid", ")", ":", "import", "ctypes", ".", "wintypes", "kernel32", "=", "ctypes", ".", "windll", ".", "kernel32", "handle", "=", "kernel32", ".", "OpenProcess", "(", "1", ",", "0", ",", "pid", ")", "if", "handle", ...
Check if PID is running for Windows systems
[ "Check", "if", "PID", "is", "running", "for", "Windows", "systems" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L147-L161
27,263
ARMmbed/icetea
icetea_lib/tools/tools.py
strip_escape
def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name """ Strip escape characters from string. :param string: string to work on :param encoding: string name of the encoding used. :return: stripped string """ matches = [] try: if hasattr(string, "decode"): string = string.decode(encoding) except Exception: # pylint: disable=broad-except # Tried to decode something that is not decodeable in the specified encoding. Let's just # move on. pass try: for match in ansi_eng.finditer(string): matches.append(match) except TypeError as error: raise TypeError("Unable to strip escape characters from data {}: {}".format( string, error)) matches.reverse() for match in matches: start = match.start() end = match.end() string = string[0:start] + string[end:] return string
python
def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name matches = [] try: if hasattr(string, "decode"): string = string.decode(encoding) except Exception: # pylint: disable=broad-except # Tried to decode something that is not decodeable in the specified encoding. Let's just # move on. pass try: for match in ansi_eng.finditer(string): matches.append(match) except TypeError as error: raise TypeError("Unable to strip escape characters from data {}: {}".format( string, error)) matches.reverse() for match in matches: start = match.start() end = match.end() string = string[0:start] + string[end:] return string
[ "def", "strip_escape", "(", "string", "=", "''", ",", "encoding", "=", "\"utf-8\"", ")", ":", "# pylint: disable=redefined-outer-name", "matches", "=", "[", "]", "try", ":", "if", "hasattr", "(", "string", ",", "\"decode\"", ")", ":", "string", "=", "string"...
Strip escape characters from string. :param string: string to work on :param encoding: string name of the encoding used. :return: stripped string
[ "Strip", "escape", "characters", "from", "string", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L167-L194
27,264
ARMmbed/icetea
icetea_lib/tools/tools.py
import_module
def import_module(modulename): """ Static method for importing module modulename. Can handle relative imports as well. :param modulename: Name of module to import. Can be relative :return: imported module instance. """ module = None try: module = importlib.import_module(modulename) except ImportError: # If importing fails we see if the modulename has dots in it, split the name. if "." in modulename: modules = modulename.split(".") package = ".".join(modules[1:len(modules)]) # Might raise an ImportError again. If so, we really failed to import the module. module = importlib.import_module(package) else: # No dots, really unable to import the module. Raise. raise return module
python
def import_module(modulename): module = None try: module = importlib.import_module(modulename) except ImportError: # If importing fails we see if the modulename has dots in it, split the name. if "." in modulename: modules = modulename.split(".") package = ".".join(modules[1:len(modules)]) # Might raise an ImportError again. If so, we really failed to import the module. module = importlib.import_module(package) else: # No dots, really unable to import the module. Raise. raise return module
[ "def", "import_module", "(", "modulename", ")", ":", "module", "=", "None", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "modulename", ")", "except", "ImportError", ":", "# If importing fails we see if the modulename has dots in it, split the name.",...
Static method for importing module modulename. Can handle relative imports as well. :param modulename: Name of module to import. Can be relative :return: imported module instance.
[ "Static", "method", "for", "importing", "module", "modulename", ".", "Can", "handle", "relative", "imports", "as", "well", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L222-L242
27,265
ARMmbed/icetea
icetea_lib/tools/tools.py
get_abs_path
def get_abs_path(relative_path): """ Get absolute path for relative path. :param relative_path: Relative path :return: absolute path """ abs_path = os.path.sep.join( os.path.abspath(sys.modules[__name__].__file__).split(os.path.sep)[:-1]) abs_path = os.path.abspath(abs_path + os.path.sep + relative_path) return abs_path
python
def get_abs_path(relative_path): abs_path = os.path.sep.join( os.path.abspath(sys.modules[__name__].__file__).split(os.path.sep)[:-1]) abs_path = os.path.abspath(abs_path + os.path.sep + relative_path) return abs_path
[ "def", "get_abs_path", "(", "relative_path", ")", ":", "abs_path", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "sys", ".", "modules", "[", "__name__", "]", ".", "__file__", ")", ".", "split", "(", "...
Get absolute path for relative path. :param relative_path: Relative path :return: absolute path
[ "Get", "absolute", "path", "for", "relative", "path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L259-L269
27,266
ARMmbed/icetea
icetea_lib/tools/tools.py
get_pkg_version
def get_pkg_version(pkg_name, parse=False): """ Verify and get installed python package version. :param pkg_name: python package name :param parse: parse version number with pkg_resourc.parse_version -function :return: None if pkg is not installed, otherwise version as a string or parsed version when parse=True """ import pkg_resources # part of setuptools try: version = pkg_resources.require(pkg_name)[0].version return pkg_resources.parse_version(version) if parse else version except pkg_resources.DistributionNotFound: return None
python
def get_pkg_version(pkg_name, parse=False): import pkg_resources # part of setuptools try: version = pkg_resources.require(pkg_name)[0].version return pkg_resources.parse_version(version) if parse else version except pkg_resources.DistributionNotFound: return None
[ "def", "get_pkg_version", "(", "pkg_name", ",", "parse", "=", "False", ")", ":", "import", "pkg_resources", "# part of setuptools", "try", ":", "version", "=", "pkg_resources", ".", "require", "(", "pkg_name", ")", "[", "0", "]", ".", "version", "return", "p...
Verify and get installed python package version. :param pkg_name: python package name :param parse: parse version number with pkg_resourc.parse_version -function :return: None if pkg is not installed, otherwise version as a string or parsed version when parse=True
[ "Verify", "and", "get", "installed", "python", "package", "version", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L272-L286
27,267
ARMmbed/icetea
icetea_lib/tools/tools.py
generate_object_graphs_by_class
def generate_object_graphs_by_class(classlist): """ Generate reference and backreference graphs for objects of type class for each class given in classlist. Useful for debugging reference leaks in framework etc. Usage example to generate graphs for class "someclass": >>> import someclass >>> someclassobject = someclass() >>> generate_object_graphs_by_class(someclass) Needs "objgraph" module installed. """ try: import objgraph import gc except ImportError: return graphcount = 0 if not isinstance(classlist, list): classlist = [classlist] for class_item in classlist: for obj in gc.get_objects(): if isinstance(obj, class_item): graphcount += 1 objgraph.show_refs([obj], filename='%d_%s_%d_refs.png' % ( ogcounter, obj.__class__.__name__, graphcount)) objgraph.show_backrefs([obj], filename='%d_%s_%d_backrefs.png' % ( ogcounter, obj.__class__.__name__, graphcount))
python
def generate_object_graphs_by_class(classlist): try: import objgraph import gc except ImportError: return graphcount = 0 if not isinstance(classlist, list): classlist = [classlist] for class_item in classlist: for obj in gc.get_objects(): if isinstance(obj, class_item): graphcount += 1 objgraph.show_refs([obj], filename='%d_%s_%d_refs.png' % ( ogcounter, obj.__class__.__name__, graphcount)) objgraph.show_backrefs([obj], filename='%d_%s_%d_backrefs.png' % ( ogcounter, obj.__class__.__name__, graphcount))
[ "def", "generate_object_graphs_by_class", "(", "classlist", ")", ":", "try", ":", "import", "objgraph", "import", "gc", "except", "ImportError", ":", "return", "graphcount", "=", "0", "if", "not", "isinstance", "(", "classlist", ",", "list", ")", ":", "classli...
Generate reference and backreference graphs for objects of type class for each class given in classlist. Useful for debugging reference leaks in framework etc. Usage example to generate graphs for class "someclass": >>> import someclass >>> someclassobject = someclass() >>> generate_object_graphs_by_class(someclass) Needs "objgraph" module installed.
[ "Generate", "reference", "and", "backreference", "graphs", "for", "objects", "of", "type", "class", "for", "each", "class", "given", "in", "classlist", ".", "Useful", "for", "debugging", "reference", "leaks", "in", "framework", "etc", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L303-L331
27,268
ARMmbed/icetea
icetea_lib/tools/tools.py
remove_empty_from_dict
def remove_empty_from_dict(dictionary): """ Remove empty items from dictionary d :param dictionary: :return: """ if isinstance(dictionary, dict): return dict( (k, remove_empty_from_dict(v)) for k, v in iteritems( dictionary) if v and remove_empty_from_dict(v)) elif isinstance(dictionary, list): return [remove_empty_from_dict(v) for v in dictionary if v and remove_empty_from_dict(v)] return dictionary
python
def remove_empty_from_dict(dictionary): if isinstance(dictionary, dict): return dict( (k, remove_empty_from_dict(v)) for k, v in iteritems( dictionary) if v and remove_empty_from_dict(v)) elif isinstance(dictionary, list): return [remove_empty_from_dict(v) for v in dictionary if v and remove_empty_from_dict(v)] return dictionary
[ "def", "remove_empty_from_dict", "(", "dictionary", ")", ":", "if", "isinstance", "(", "dictionary", ",", "dict", ")", ":", "return", "dict", "(", "(", "k", ",", "remove_empty_from_dict", "(", "v", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", ...
Remove empty items from dictionary d :param dictionary: :return:
[ "Remove", "empty", "items", "from", "dictionary", "d" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L396-L410
27,269
ARMmbed/icetea
icetea_lib/tools/tools.py
set_or_delete
def set_or_delete(dictionary, key, value): """ Set value as value of dict key key. If value is None, delete key key from dict. :param dictionary: Dictionary to work on. :param key: Key to set or delete. If deleting and key does not exist in dict, nothing is done. :param value: Value to set. If value is None, delete key. :return: Nothing, modifies dict in place. """ if value: dictionary[key] = value else: if dictionary.get(key): del dictionary[key]
python
def set_or_delete(dictionary, key, value): if value: dictionary[key] = value else: if dictionary.get(key): del dictionary[key]
[ "def", "set_or_delete", "(", "dictionary", ",", "key", ",", "value", ")", ":", "if", "value", ":", "dictionary", "[", "key", "]", "=", "value", "else", ":", "if", "dictionary", ".", "get", "(", "key", ")", ":", "del", "dictionary", "[", "key", "]" ]
Set value as value of dict key key. If value is None, delete key key from dict. :param dictionary: Dictionary to work on. :param key: Key to set or delete. If deleting and key does not exist in dict, nothing is done. :param value: Value to set. If value is None, delete key. :return: Nothing, modifies dict in place.
[ "Set", "value", "as", "value", "of", "dict", "key", "key", ".", "If", "value", "is", "None", "delete", "key", "key", "from", "dict", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L434-L447
27,270
ARMmbed/icetea
icetea_lib/tools/tools.py
initLogger
def initLogger(name): # pylint: disable=invalid-name ''' Initializes a basic logger. Can be replaced when constructing the HttpApi object or afterwards with setter ''' logger = logging.getLogger(name) logger.setLevel(logging.INFO) # Skip attaching StreamHandler if one is already attached to logger if not getattr(logger, "streamhandler_set", None): consolehandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') consolehandler.setFormatter(formatter) consolehandler.setLevel(logging.INFO) logger.addHandler(consolehandler) logger.streamhandler_set = True return logger
python
def initLogger(name): # pylint: disable=invalid-name ''' Initializes a basic logger. Can be replaced when constructing the HttpApi object or afterwards with setter ''' logger = logging.getLogger(name) logger.setLevel(logging.INFO) # Skip attaching StreamHandler if one is already attached to logger if not getattr(logger, "streamhandler_set", None): consolehandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') consolehandler.setFormatter(formatter) consolehandler.setLevel(logging.INFO) logger.addHandler(consolehandler) logger.streamhandler_set = True return logger
[ "def", "initLogger", "(", "name", ")", ":", "# pylint: disable=invalid-name", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "# Skip attaching StreamHandler if one is already attached to logger"...
Initializes a basic logger. Can be replaced when constructing the HttpApi object or afterwards with setter
[ "Initializes", "a", "basic", "logger", ".", "Can", "be", "replaced", "when", "constructing", "the", "HttpApi", "object", "or", "afterwards", "with", "setter" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L499-L514
27,271
ARMmbed/icetea
icetea_lib/tools/tools.py
find_duplicate_keys
def find_duplicate_keys(data): """ Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable for json.load or loads. :param data: ordered pairs :return: Dictionary with no duplicate keys :raises ValueError if duplicate keys are found """ out_dict = {} for key, value in data: if key in out_dict: raise ValueError("Duplicate key: {}".format(key)) out_dict[key] = value return out_dict
python
def find_duplicate_keys(data): out_dict = {} for key, value in data: if key in out_dict: raise ValueError("Duplicate key: {}".format(key)) out_dict[key] = value return out_dict
[ "def", "find_duplicate_keys", "(", "data", ")", ":", "out_dict", "=", "{", "}", "for", "key", ",", "value", "in", "data", ":", "if", "key", "in", "out_dict", ":", "raise", "ValueError", "(", "\"Duplicate key: {}\"", ".", "format", "(", "key", ")", ")", ...
Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable for json.load or loads. :param data: ordered pairs :return: Dictionary with no duplicate keys :raises ValueError if duplicate keys are found
[ "Find", "duplicate", "keys", "in", "a", "layer", "of", "ordered", "pairs", ".", "Intended", "as", "the", "object_pairs_hook", "callable", "for", "json", ".", "load", "or", "loads", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L613-L627
27,272
ARMmbed/icetea
icetea_lib/build/build.py
BuildFile._load
def _load(self): """ Function load. :return: file contents :raises: NotFoundError if file not found """ if self.is_exists(): return open(self._ref, "rb").read() raise NotFoundError("File %s not found" % self._ref)
python
def _load(self): if self.is_exists(): return open(self._ref, "rb").read() raise NotFoundError("File %s not found" % self._ref)
[ "def", "_load", "(", "self", ")", ":", "if", "self", ".", "is_exists", "(", ")", ":", "return", "open", "(", "self", ".", "_ref", ",", "\"rb\"", ")", ".", "read", "(", ")", "raise", "NotFoundError", "(", "\"File %s not found\"", "%", "self", ".", "_r...
Function load. :return: file contents :raises: NotFoundError if file not found
[ "Function", "load", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/build/build.py#L152-L161
27,273
ARMmbed/icetea
icetea_lib/build/build.py
BuildHttp.get_file
def get_file(self): """ Load data into a file and return file path. :return: path to file as string """ content = self._load() if not content: return None filename = "temporary_file.bin" with open(filename, "wb") as file_name: file_name.write(content) return filename
python
def get_file(self): content = self._load() if not content: return None filename = "temporary_file.bin" with open(filename, "wb") as file_name: file_name.write(content) return filename
[ "def", "get_file", "(", "self", ")", ":", "content", "=", "self", ".", "_load", "(", ")", "if", "not", "content", ":", "return", "None", "filename", "=", "\"temporary_file.bin\"", "with", "open", "(", "filename", ",", "\"wb\"", ")", "as", "file_name", ":...
Load data into a file and return file path. :return: path to file as string
[ "Load", "data", "into", "a", "file", "and", "return", "file", "path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/build/build.py#L200-L212
27,274
ARMmbed/icetea
icetea_lib/DeviceConnectors/DutInformation.py
DutInformation.as_dict
def as_dict(self): """ Generate a dictionary of the contents of this DutInformation object. :return: dict """ my_info = {} if self.platform: my_info["model"] = self.platform if self.resource_id: my_info["sn"] = self.resource_id if self.vendor: my_info["vendor"] = self.vendor if self.provider: my_info["provider"] = self.provider return my_info
python
def as_dict(self): my_info = {} if self.platform: my_info["model"] = self.platform if self.resource_id: my_info["sn"] = self.resource_id if self.vendor: my_info["vendor"] = self.vendor if self.provider: my_info["provider"] = self.provider return my_info
[ "def", "as_dict", "(", "self", ")", ":", "my_info", "=", "{", "}", "if", "self", ".", "platform", ":", "my_info", "[", "\"model\"", "]", "=", "self", ".", "platform", "if", "self", ".", "resource_id", ":", "my_info", "[", "\"sn\"", "]", "=", "self", ...
Generate a dictionary of the contents of this DutInformation object. :return: dict
[ "Generate", "a", "dictionary", "of", "the", "contents", "of", "this", "DutInformation", "object", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L44-L59
27,275
ARMmbed/icetea
icetea_lib/DeviceConnectors/DutInformation.py
DutInformationList.get_resource_ids
def get_resource_ids(self): """ Get resource ids as a list. :return: List of resource id:s or "unknown" """ resids = [] if self.dutinformations: for info in self.dutinformations: resids.append(info.resource_id) return resids return "unknown"
python
def get_resource_ids(self): resids = [] if self.dutinformations: for info in self.dutinformations: resids.append(info.resource_id) return resids return "unknown"
[ "def", "get_resource_ids", "(", "self", ")", ":", "resids", "=", "[", "]", "if", "self", ".", "dutinformations", ":", "for", "info", "in", "self", ".", "dutinformations", ":", "resids", ".", "append", "(", "info", ".", "resource_id", ")", "return", "resi...
Get resource ids as a list. :return: List of resource id:s or "unknown"
[ "Get", "resource", "ids", "as", "a", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L133-L144
27,276
ARMmbed/icetea
icetea_lib/DeviceConnectors/DutInformation.py
DutInformationList.push_resource_cache
def push_resource_cache(resourceid, info): """ Cache resource specific information :param resourceid: Resource id as string :param info: Dict to push :return: Nothing """ if not resourceid: raise ResourceInitError("Resource id missing") if not DutInformationList._cache.get(resourceid): DutInformationList._cache[resourceid] = dict() DutInformationList._cache[resourceid] = merge(DutInformationList._cache[resourceid], info)
python
def push_resource_cache(resourceid, info): if not resourceid: raise ResourceInitError("Resource id missing") if not DutInformationList._cache.get(resourceid): DutInformationList._cache[resourceid] = dict() DutInformationList._cache[resourceid] = merge(DutInformationList._cache[resourceid], info)
[ "def", "push_resource_cache", "(", "resourceid", ",", "info", ")", ":", "if", "not", "resourceid", ":", "raise", "ResourceInitError", "(", "\"Resource id missing\"", ")", "if", "not", "DutInformationList", ".", "_cache", ".", "get", "(", "resourceid", ")", ":", ...
Cache resource specific information :param resourceid: Resource id as string :param info: Dict to push :return: Nothing
[ "Cache", "resource", "specific", "information" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L164-L176
27,277
ARMmbed/icetea
icetea_lib/DeviceConnectors/DutInformation.py
DutInformationList.get_resource_cache
def get_resource_cache(resourceid): """ Get a cached dictionary related to an individual resourceid. :param resourceid: String resource id. :return: dict """ if not resourceid: raise ResourceInitError("Resource id missing") if not DutInformationList._cache.get(resourceid): DutInformationList._cache[resourceid] = dict() return DutInformationList._cache[resourceid]
python
def get_resource_cache(resourceid): if not resourceid: raise ResourceInitError("Resource id missing") if not DutInformationList._cache.get(resourceid): DutInformationList._cache[resourceid] = dict() return DutInformationList._cache[resourceid]
[ "def", "get_resource_cache", "(", "resourceid", ")", ":", "if", "not", "resourceid", ":", "raise", "ResourceInitError", "(", "\"Resource id missing\"", ")", "if", "not", "DutInformationList", ".", "_cache", ".", "get", "(", "resourceid", ")", ":", "DutInformationL...
Get a cached dictionary related to an individual resourceid. :param resourceid: String resource id. :return: dict
[ "Get", "a", "cached", "dictionary", "related", "to", "an", "individual", "resourceid", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L179-L190
27,278
ARMmbed/icetea
icetea_lib/cloud.py
create_result_object
def create_result_object(result): """ Create cloud result object from Result. :param result: Result :return: dictionary """ _result = { 'tcid': result.get_tc_name(), 'campaign': result.campaign, 'cre': { 'user': result.tester }, 'job': { 'id': result.job_id }, 'exec': { 'verdict': result.get_verdict(), 'duration': result.duration, 'note': result.get_fail_reason(), 'dut': { 'count': result.dut_count, 'type': result.dut_type }, 'sut': { 'branch': result.build_branch, 'commitId': result.buildcommit, 'buildDate': result.build_date, 'buildSha1': result.build_sha1, 'buildUrl': result.build_url, 'gitUrl': result.build_git_url, 'cut': result.component, # Component Under Uest 'fut': result.feature # Feature Under Test }, 'env': { 'framework': { 'name': result.fw_name, 'ver': result.fw_version } }, "logs": [] } } if result.dut_resource_id: _result["exec"]["dut"]["sn"] = result.dut_resource_id if result.dut_vendor and result.dut_vendor[0]: _result["exec"]["dut"]["vendor"] = result.dut_vendor[0] if result.dut_models and result.dut_models[0]: _result["exec"]["dut"]["model"] = result.dut_models[0] # pylint: disable=len-as-condition if len(result.dut_models) == 1 and len(result.dut_resource_id) == 1: _result["exec"]["dut"]["sn"] = result.dut_resource_id[0] return remove_empty_from_dict(_result)
python
def create_result_object(result): _result = { 'tcid': result.get_tc_name(), 'campaign': result.campaign, 'cre': { 'user': result.tester }, 'job': { 'id': result.job_id }, 'exec': { 'verdict': result.get_verdict(), 'duration': result.duration, 'note': result.get_fail_reason(), 'dut': { 'count': result.dut_count, 'type': result.dut_type }, 'sut': { 'branch': result.build_branch, 'commitId': result.buildcommit, 'buildDate': result.build_date, 'buildSha1': result.build_sha1, 'buildUrl': result.build_url, 'gitUrl': result.build_git_url, 'cut': result.component, # Component Under Uest 'fut': result.feature # Feature Under Test }, 'env': { 'framework': { 'name': result.fw_name, 'ver': result.fw_version } }, "logs": [] } } if result.dut_resource_id: _result["exec"]["dut"]["sn"] = result.dut_resource_id if result.dut_vendor and result.dut_vendor[0]: _result["exec"]["dut"]["vendor"] = result.dut_vendor[0] if result.dut_models and result.dut_models[0]: _result["exec"]["dut"]["model"] = result.dut_models[0] # pylint: disable=len-as-condition if len(result.dut_models) == 1 and len(result.dut_resource_id) == 1: _result["exec"]["dut"]["sn"] = result.dut_resource_id[0] return remove_empty_from_dict(_result)
[ "def", "create_result_object", "(", "result", ")", ":", "_result", "=", "{", "'tcid'", ":", "result", ".", "get_tc_name", "(", ")", ",", "'campaign'", ":", "result", ".", "campaign", ",", "'cre'", ":", "{", "'user'", ":", "result", ".", "tester", "}", ...
Create cloud result object from Result. :param result: Result :return: dictionary
[ "Create", "cloud", "result", "object", "from", "Result", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/cloud.py#L25-L80
27,279
ARMmbed/icetea
icetea_lib/cloud.py
append_logs_to_result_object
def append_logs_to_result_object(result_obj, result): """ Append log files to cloud result object from Result. :param result_obj: Target result object :param result: Result :return: Nothing, modifies result_obj in place. """ logs = result.has_logs() result_obj["exec"]["logs"] = [] if logs and result.logfiles: for log in logs: typ = None parts = log.split(os.sep) if "bench" in parts[len(parts) - 1]: typ = "framework" # elif "Dut" in parts[len(parts)-1]: # typ = "dut" if typ is not None: name = parts[len(parts) - 1] try: with open(log, "r") as file_name: data = file_name.read() dic = {"data": data, "name": name, "from": typ} result_obj["exec"]["logs"].append(dic) except OSError: pass else: continue
python
def append_logs_to_result_object(result_obj, result): logs = result.has_logs() result_obj["exec"]["logs"] = [] if logs and result.logfiles: for log in logs: typ = None parts = log.split(os.sep) if "bench" in parts[len(parts) - 1]: typ = "framework" # elif "Dut" in parts[len(parts)-1]: # typ = "dut" if typ is not None: name = parts[len(parts) - 1] try: with open(log, "r") as file_name: data = file_name.read() dic = {"data": data, "name": name, "from": typ} result_obj["exec"]["logs"].append(dic) except OSError: pass else: continue
[ "def", "append_logs_to_result_object", "(", "result_obj", ",", "result", ")", ":", "logs", "=", "result", ".", "has_logs", "(", ")", "result_obj", "[", "\"exec\"", "]", "[", "\"logs\"", "]", "=", "[", "]", "if", "logs", "and", "result", ".", "logfiles", ...
Append log files to cloud result object from Result. :param result_obj: Target result object :param result: Result :return: Nothing, modifies result_obj in place.
[ "Append", "log", "files", "to", "cloud", "result", "object", "from", "Result", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/cloud.py#L83-L112
27,280
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py
DutDetection.get_available_devices
def get_available_devices(self): """ Gets available devices using mbedls and self.available_edbg_ports. :return: List of connected devices as dictionaries. """ connected_devices = self.mbeds.list_mbeds() if self.mbeds else [] # Check non mbedOS supported devices. # Just for backward compatible reason - is obsolete.. edbg_ports = self.available_edbg_ports() for port in edbg_ports: connected_devices.append({ "platform_name": "SAM4E", "serial_port": port, "mount_point": None, "target_id": None, "baud_rate": 460800 }) for dev in connected_devices: dev['state'] = "unknown" return connected_devices
python
def get_available_devices(self): connected_devices = self.mbeds.list_mbeds() if self.mbeds else [] # Check non mbedOS supported devices. # Just for backward compatible reason - is obsolete.. edbg_ports = self.available_edbg_ports() for port in edbg_ports: connected_devices.append({ "platform_name": "SAM4E", "serial_port": port, "mount_point": None, "target_id": None, "baud_rate": 460800 }) for dev in connected_devices: dev['state'] = "unknown" return connected_devices
[ "def", "get_available_devices", "(", "self", ")", ":", "connected_devices", "=", "self", ".", "mbeds", ".", "list_mbeds", "(", ")", "if", "self", ".", "mbeds", "else", "[", "]", "# Check non mbedOS supported devices.", "# Just for backward compatible reason - is obsolet...
Gets available devices using mbedls and self.available_edbg_ports. :return: List of connected devices as dictionaries.
[ "Gets", "available", "devices", "using", "mbedls", "and", "self", ".", "available_edbg_ports", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py#L58-L79
27,281
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py
DutDetection.available_edbg_ports
def available_edbg_ports(self): """ Finds available EDBG COM ports. :return: list of available ports """ ports_available = sorted(list(list_ports.comports())) edbg_ports = [] for iport in ports_available: port = iport[0] desc = iport[1] hwid = iport[2] if str(desc).startswith("EDBG Virtual COM Port") or \ "VID:PID=03EB:2111" in str(hwid).upper(): # print("%-10s: %s (%s)\n" % (port, desc, hwid)) try: edbg_ports.index(port, 0) print("There is multiple %s ports with same number!" % port) except ValueError: edbg_ports.append(port) # print("Detected %i DUT's" % len(edbg_ports)) return edbg_ports
python
def available_edbg_ports(self): ports_available = sorted(list(list_ports.comports())) edbg_ports = [] for iport in ports_available: port = iport[0] desc = iport[1] hwid = iport[2] if str(desc).startswith("EDBG Virtual COM Port") or \ "VID:PID=03EB:2111" in str(hwid).upper(): # print("%-10s: %s (%s)\n" % (port, desc, hwid)) try: edbg_ports.index(port, 0) print("There is multiple %s ports with same number!" % port) except ValueError: edbg_ports.append(port) # print("Detected %i DUT's" % len(edbg_ports)) return edbg_ports
[ "def", "available_edbg_ports", "(", "self", ")", ":", "ports_available", "=", "sorted", "(", "list", "(", "list_ports", ".", "comports", "(", ")", ")", ")", "edbg_ports", "=", "[", "]", "for", "iport", "in", "ports_available", ":", "port", "=", "iport", ...
Finds available EDBG COM ports. :return: list of available ports
[ "Finds", "available", "EDBG", "COM", "ports", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py#L81-L102
27,282
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.store_traces
def store_traces(self, value): """ Setter for _store_traces. _store_traces controls in memory storing of received lines. Also logs the change for the user. :param value: Boolean :return: Nothing """ if not value: self.logger.debug("Stopping storing received lines for dut %d", self.index) self._store_traces = False else: self.logger.debug("Resuming storing received lines for dut %d", self.index) self._store_traces = True
python
def store_traces(self, value): if not value: self.logger.debug("Stopping storing received lines for dut %d", self.index) self._store_traces = False else: self.logger.debug("Resuming storing received lines for dut %d", self.index) self._store_traces = True
[ "def", "store_traces", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "self", ".", "logger", ".", "debug", "(", "\"Stopping storing received lines for dut %d\"", ",", "self", ".", "index", ")", "self", ".", "_store_traces", "=", "False", "el...
Setter for _store_traces. _store_traces controls in memory storing of received lines. Also logs the change for the user. :param value: Boolean :return: Nothing
[ "Setter", "for", "_store_traces", ".", "_store_traces", "controls", "in", "memory", "storing", "of", "received", "lines", ".", "Also", "logs", "the", "change", "for", "the", "user", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L196-L209
27,283
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.init_wait_register
def init_wait_register(self): """ Initialize EventMatcher to wait for certain cli_ready_trigger to arrive from this Dut. :return: None """ app = self.config.get("application") if app: bef_init_cmds = app.get("cli_ready_trigger") if bef_init_cmds: self.init_done.clear() self.init_event_matcher = EventMatcher(EventTypes.DUT_LINE_RECEIVED, bef_init_cmds, self, self.init_done) self.init_wait_timeout = app.get("cli_ready_trigger_timeout", 30) return self.init_done.set() return
python
def init_wait_register(self): app = self.config.get("application") if app: bef_init_cmds = app.get("cli_ready_trigger") if bef_init_cmds: self.init_done.clear() self.init_event_matcher = EventMatcher(EventTypes.DUT_LINE_RECEIVED, bef_init_cmds, self, self.init_done) self.init_wait_timeout = app.get("cli_ready_trigger_timeout", 30) return self.init_done.set() return
[ "def", "init_wait_register", "(", "self", ")", ":", "app", "=", "self", ".", "config", ".", "get", "(", "\"application\"", ")", "if", "app", ":", "bef_init_cmds", "=", "app", ".", "get", "(", "\"cli_ready_trigger\"", ")", "if", "bef_init_cmds", ":", "self"...
Initialize EventMatcher to wait for certain cli_ready_trigger to arrive from this Dut. :return: None
[ "Initialize", "EventMatcher", "to", "wait", "for", "certain", "cli_ready_trigger", "to", "arrive", "from", "this", "Dut", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L362-L379
27,284
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.wait_init
def wait_init(self): """ Block until init_done flag is set or until init_wait_timeout happens. :return: value of init_done """ init_done = self.init_done.wait(timeout=self.init_wait_timeout) if not init_done: if hasattr(self, "peek"): app = self.config.get("application") if app: bef_init_cmds = app.get("cli_ready_trigger") if bef_init_cmds in self.peek(): # pylint: disable=no-member init_done = True return init_done
python
def wait_init(self): init_done = self.init_done.wait(timeout=self.init_wait_timeout) if not init_done: if hasattr(self, "peek"): app = self.config.get("application") if app: bef_init_cmds = app.get("cli_ready_trigger") if bef_init_cmds in self.peek(): # pylint: disable=no-member init_done = True return init_done
[ "def", "wait_init", "(", "self", ")", ":", "init_done", "=", "self", ".", "init_done", ".", "wait", "(", "timeout", "=", "self", ".", "init_wait_timeout", ")", "if", "not", "init_done", ":", "if", "hasattr", "(", "self", ",", "\"peek\"", ")", ":", "app...
Block until init_done flag is set or until init_wait_timeout happens. :return: value of init_done
[ "Block", "until", "init_done", "flag", "is", "set", "or", "until", "init_wait_timeout", "happens", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L381-L395
27,285
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.init_cli_human
def init_cli_human(self): """ Send post_cli_cmds to dut :return: Nothing """ if self.post_cli_cmds is None: self.post_cli_cmds = self.set_default_init_cli_human_cmds() for cli_cmd in self.post_cli_cmds: try: if isinstance(cli_cmd, list) and len(cli_cmd) >= 2: asynchronous = cli_cmd[1] if len(cli_cmd) > 2: wait = cli_cmd[2] else: wait = True self.execute_command(cli_cmd[0], wait=wait, asynchronous=asynchronous) else: self.execute_command(cli_cmd) except (TestStepFail, TestStepError, TestStepTimeout): continue
python
def init_cli_human(self): if self.post_cli_cmds is None: self.post_cli_cmds = self.set_default_init_cli_human_cmds() for cli_cmd in self.post_cli_cmds: try: if isinstance(cli_cmd, list) and len(cli_cmd) >= 2: asynchronous = cli_cmd[1] if len(cli_cmd) > 2: wait = cli_cmd[2] else: wait = True self.execute_command(cli_cmd[0], wait=wait, asynchronous=asynchronous) else: self.execute_command(cli_cmd) except (TestStepFail, TestStepError, TestStepTimeout): continue
[ "def", "init_cli_human", "(", "self", ")", ":", "if", "self", ".", "post_cli_cmds", "is", "None", ":", "self", ".", "post_cli_cmds", "=", "self", ".", "set_default_init_cli_human_cmds", "(", ")", "for", "cli_cmd", "in", "self", ".", "post_cli_cmds", ":", "tr...
Send post_cli_cmds to dut :return: Nothing
[ "Send", "post_cli_cmds", "to", "dut" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L397-L417
27,286
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.set_time_function
def set_time_function(self, function): """ Set time function to be used. :param function: callable function :return: Nothing :raises: ValueError if function is not types.FunctionType. """ if isinstance(function, types.FunctionType): self.get_time = function else: raise ValueError("Invalid value for DUT time function")
python
def set_time_function(self, function): if isinstance(function, types.FunctionType): self.get_time = function else: raise ValueError("Invalid value for DUT time function")
[ "def", "set_time_function", "(", "self", ",", "function", ")", ":", "if", "isinstance", "(", "function", ",", "types", ".", "FunctionType", ")", ":", "self", ".", "get_time", "=", "function", "else", ":", "raise", "ValueError", "(", "\"Invalid value for DUT ti...
Set time function to be used. :param function: callable function :return: Nothing :raises: ValueError if function is not types.FunctionType.
[ "Set", "time", "function", "to", "be", "used", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L419-L430
27,287
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.open_dut
def open_dut(self, port=None): """ Open connection to dut. :param port: com port to use. :return: """ if port is not None: self.comport = port try: self.open_connection() except (DutConnectionError, ValueError) as err: self.close_dut(use_prepare=False) raise DutConnectionError(str(err)) except KeyboardInterrupt: self.close_dut(use_prepare=False) self.close_connection() raise
python
def open_dut(self, port=None): if port is not None: self.comport = port try: self.open_connection() except (DutConnectionError, ValueError) as err: self.close_dut(use_prepare=False) raise DutConnectionError(str(err)) except KeyboardInterrupt: self.close_dut(use_prepare=False) self.close_connection() raise
[ "def", "open_dut", "(", "self", ",", "port", "=", "None", ")", ":", "if", "port", "is", "not", "None", ":", "self", ".", "comport", "=", "port", "try", ":", "self", ".", "open_connection", "(", ")", "except", "(", "DutConnectionError", ",", "ValueError...
Open connection to dut. :param port: com port to use. :return:
[ "Open", "connection", "to", "dut", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L432-L450
27,288
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut._wait_for_exec_ready
def _wait_for_exec_ready(self): """ Wait for response. :return: CliResponse object coming in :raises: TestStepTimeout, TestStepError """ while not self.response_received.wait(1) and self.query_timeout != 0: if self.query_timeout != 0 and self.query_timeout < self.get_time(): if self.prev: cmd = self.prev.cmd else: cmd = "???" self.logger.error("CMD timeout: "+ cmd) self.query_timeout = 0 raise TestStepTimeout(self.name + " CMD timeout: " + cmd) self.logger.debug("Waiting for response... " "timeout=%d", self.query_timeout - self.get_time()) self._dut_is_alive() if self.response_coming_in == -1: if self.query_async_response is not None: # fullfill the async response with a dummy response and clean the state self.query_async_response.set_response(CliResponse()) self.query_async_response = None # raise and log the error self.logger.error("No response received, DUT died") raise TestStepError("No response received, DUT "+self.name+" died") # if an async response is pending, fullfill it with the result if self.query_async_response is not None: self.query_async_response.set_response(self.response_coming_in) self.query_async_response = None self.query_timeout = 0 return self.response_coming_in
python
def _wait_for_exec_ready(self): while not self.response_received.wait(1) and self.query_timeout != 0: if self.query_timeout != 0 and self.query_timeout < self.get_time(): if self.prev: cmd = self.prev.cmd else: cmd = "???" self.logger.error("CMD timeout: "+ cmd) self.query_timeout = 0 raise TestStepTimeout(self.name + " CMD timeout: " + cmd) self.logger.debug("Waiting for response... " "timeout=%d", self.query_timeout - self.get_time()) self._dut_is_alive() if self.response_coming_in == -1: if self.query_async_response is not None: # fullfill the async response with a dummy response and clean the state self.query_async_response.set_response(CliResponse()) self.query_async_response = None # raise and log the error self.logger.error("No response received, DUT died") raise TestStepError("No response received, DUT "+self.name+" died") # if an async response is pending, fullfill it with the result if self.query_async_response is not None: self.query_async_response.set_response(self.response_coming_in) self.query_async_response = None self.query_timeout = 0 return self.response_coming_in
[ "def", "_wait_for_exec_ready", "(", "self", ")", ":", "while", "not", "self", ".", "response_received", ".", "wait", "(", "1", ")", "and", "self", ".", "query_timeout", "!=", "0", ":", "if", "self", ".", "query_timeout", "!=", "0", "and", "self", ".", ...
Wait for response. :return: CliResponse object coming in :raises: TestStepTimeout, TestStepError
[ "Wait", "for", "response", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L460-L495
27,289
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.execute_command
def execute_command(self, req, **kwargs): """ Execute command and return CliResponse :param req: String, command to be executed in DUT, or CliRequest, command class which contains all configurations like timeout. :param kwargs: Configurations (wait, timeout) which will be used when string mode is in use. :return: CliResponse, which contains all received data from Dut and parsed retcode. """ if isinstance(req, string_types): # backward compatible timeout = 50 # Use same default timeout as bench.py wait = True asynchronous = False for key in kwargs: if key == 'wait': wait = kwargs[key] elif key == 'timeout': timeout = kwargs[key] # [ms] elif key == 'asynchronous': asynchronous = kwargs[key] req = CliRequest(req, timestamp=self.get_time(), wait=wait, timeout=timeout, asynchronous=asynchronous) # wait for previous command ready if req.wait: response = self._wait_for_exec_ready() if response is not None and self.query_async_expected is not None: if response.retcode != self.query_async_expected: self.logger.error("Asynch call returned unexpected result, " "expected %d was %d", self.query_async_expected, response.retcode) raise TestStepFail("Asynch call returned unexpected result") self.query_async_expected = None # Tell Query to worker thread self.response_received.clear() self.query_timeout = self.get_time() + req.timeout if req.wait else 0 self.query = req msg = "Async CMD {}, " \ "timeout={}, time={}" if req.asynchronous else "CMD {}, timeout={}, time={}" msg = msg.format(req.cmd, int(self.query_timeout), int(self.get_time())) self.logger.debug(msg, extra={'type': '<->'}) Dut.process_dut(self) if req.asynchronous is True: self.query_async_expected = req.expected_retcode async_response = CliAsyncResponse(self) self.query_async_response = async_response return async_response if req.wait is False: self.query_async_expected = req.expected_retcode # if an async response was waiting, just discard the result # since the new command has already been sent... # This is not ideal but when a command has its flags "Wait == False" # the result of the previous command is already discarded in previous # stages if self.query_async_response is not None: self.query_async_response.set_response(CliResponse()) self.query_async_response = None return CliResponse() return self._wait_for_exec_ready()
python
def execute_command(self, req, **kwargs): if isinstance(req, string_types): # backward compatible timeout = 50 # Use same default timeout as bench.py wait = True asynchronous = False for key in kwargs: if key == 'wait': wait = kwargs[key] elif key == 'timeout': timeout = kwargs[key] # [ms] elif key == 'asynchronous': asynchronous = kwargs[key] req = CliRequest(req, timestamp=self.get_time(), wait=wait, timeout=timeout, asynchronous=asynchronous) # wait for previous command ready if req.wait: response = self._wait_for_exec_ready() if response is not None and self.query_async_expected is not None: if response.retcode != self.query_async_expected: self.logger.error("Asynch call returned unexpected result, " "expected %d was %d", self.query_async_expected, response.retcode) raise TestStepFail("Asynch call returned unexpected result") self.query_async_expected = None # Tell Query to worker thread self.response_received.clear() self.query_timeout = self.get_time() + req.timeout if req.wait else 0 self.query = req msg = "Async CMD {}, " \ "timeout={}, time={}" if req.asynchronous else "CMD {}, timeout={}, time={}" msg = msg.format(req.cmd, int(self.query_timeout), int(self.get_time())) self.logger.debug(msg, extra={'type': '<->'}) Dut.process_dut(self) if req.asynchronous is True: self.query_async_expected = req.expected_retcode async_response = CliAsyncResponse(self) self.query_async_response = async_response return async_response if req.wait is False: self.query_async_expected = req.expected_retcode # if an async response was waiting, just discard the result # since the new command has already been sent... # This is not ideal but when a command has its flags "Wait == False" # the result of the previous command is already discarded in previous # stages if self.query_async_response is not None: self.query_async_response.set_response(CliResponse()) self.query_async_response = None return CliResponse() return self._wait_for_exec_ready()
[ "def", "execute_command", "(", "self", ",", "req", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "req", ",", "string_types", ")", ":", "# backward compatible", "timeout", "=", "50", "# Use same default timeout as bench.py", "wait", "=", "True", "...
Execute command and return CliResponse :param req: String, command to be executed in DUT, or CliRequest, command class which contains all configurations like timeout. :param kwargs: Configurations (wait, timeout) which will be used when string mode is in use. :return: CliResponse, which contains all received data from Dut and parsed retcode.
[ "Execute", "command", "and", "return", "CliResponse" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L497-L565
27,290
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.close_dut
def close_dut(self, use_prepare=True): """ Close connection to dut. :param use_prepare: Boolean, default is True. Call prepare_connection_close before closing connection. :return: Nothing """ if not self.stopped: self.logger.debug("Close '%s' connection" % self.dut_name, extra={'type': '<->'}) if use_prepare: try: self.prepare_connection_close() except TestStepFail: # We can ignore this for dead Duts, just continue with cleanup pass self.stopped = True Dut._dutlist.remove(self) # Remove myself from signalled dut list, if I'm still there if Dut._signalled_duts and Dut._signalled_duts.count(self): try: Dut._signalled_duts.remove(self) except ValueError: pass try: if not Dut._dutlist: Dut._run = False Dut._sem.release() Dut._th.join() del Dut._th Dut._th = None except AttributeError: pass
python
def close_dut(self, use_prepare=True): if not self.stopped: self.logger.debug("Close '%s' connection" % self.dut_name, extra={'type': '<->'}) if use_prepare: try: self.prepare_connection_close() except TestStepFail: # We can ignore this for dead Duts, just continue with cleanup pass self.stopped = True Dut._dutlist.remove(self) # Remove myself from signalled dut list, if I'm still there if Dut._signalled_duts and Dut._signalled_duts.count(self): try: Dut._signalled_duts.remove(self) except ValueError: pass try: if not Dut._dutlist: Dut._run = False Dut._sem.release() Dut._th.join() del Dut._th Dut._th = None except AttributeError: pass
[ "def", "close_dut", "(", "self", ",", "use_prepare", "=", "True", ")", ":", "if", "not", "self", ".", "stopped", ":", "self", ".", "logger", ".", "debug", "(", "\"Close '%s' connection\"", "%", "self", ".", "dut_name", ",", "extra", "=", "{", "'type'", ...
Close connection to dut. :param use_prepare: Boolean, default is True. Call prepare_connection_close before closing connection. :return: Nothing
[ "Close", "connection", "to", "dut", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L567-L600
27,291
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.process_dut
def process_dut(dut): """ Signal worker thread that specified Dut needs processing """ if dut.finished(): return Dut._signalled_duts.appendleft(dut) Dut._sem.release()
python
def process_dut(dut): if dut.finished(): return Dut._signalled_duts.appendleft(dut) Dut._sem.release()
[ "def", "process_dut", "(", "dut", ")", ":", "if", "dut", ".", "finished", "(", ")", ":", "return", "Dut", ".", "_signalled_duts", ".", "appendleft", "(", "dut", ")", "Dut", ".", "_sem", ".", "release", "(", ")" ]
Signal worker thread that specified Dut needs processing
[ "Signal", "worker", "thread", "that", "specified", "Dut", "needs", "processing" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L621-L628
27,292
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.run
def run(): # pylint: disable=too-many-branches """ Main thread runner for all Duts. :return: Nothing """ Dut._logger.debug("Start DUT communication", extra={'type': '<->'}) while Dut._run: Dut._sem.acquire() try: dut = Dut._signalled_duts.pop() # Check for pending requests if dut.waiting_for_response is not None: item = dut.waiting_for_response # pylint: disable=protected-access dut.response_coming_in = dut._read_response() if dut.response_coming_in is None: # Continue to next node continue if isinstance(dut.response_coming_in, CliResponse): dut.response_coming_in.set_response_time(item.get_timedelta(dut.get_time())) dut.waiting_for_response = None dut.logger.debug("Got response", extra={'type': '<->'}) dut.response_received.set() continue # Check for new Request if dut.query is not None: item = dut.query dut.query = None dut.logger.info(item.cmd, extra={'type': '-->'}) try: dut.writeline(item.cmd) except RuntimeError: dut.response_coming_in = -1 dut.response_received.set() continue dut.prev = item # Save previous command for logging purposes if item.wait: # Only caller will care if this was asynchronous. dut.waiting_for_response = item else: dut.query_timeout = 0 dut.response_received.set() continue try: line = dut.readline() except RuntimeError: dut.response_coming_in = -1 dut.response_received.set() continue if line: if dut.store_traces: dut.traces.append(line) EventObject(EventTypes.DUT_LINE_RECEIVED, dut, line) retcode = dut.check_retcode(line) if retcode is not None: dut.logger.warning("unrequested retcode", extra={'type': '!<-'}) dut.logger.debug(line, extra={'type': '<<<'}) except IndexError: pass Dut._logger.debug("End DUT communication", extra={'type': '<->'})
python
def run(): # pylint: disable=too-many-branches Dut._logger.debug("Start DUT communication", extra={'type': '<->'}) while Dut._run: Dut._sem.acquire() try: dut = Dut._signalled_duts.pop() # Check for pending requests if dut.waiting_for_response is not None: item = dut.waiting_for_response # pylint: disable=protected-access dut.response_coming_in = dut._read_response() if dut.response_coming_in is None: # Continue to next node continue if isinstance(dut.response_coming_in, CliResponse): dut.response_coming_in.set_response_time(item.get_timedelta(dut.get_time())) dut.waiting_for_response = None dut.logger.debug("Got response", extra={'type': '<->'}) dut.response_received.set() continue # Check for new Request if dut.query is not None: item = dut.query dut.query = None dut.logger.info(item.cmd, extra={'type': '-->'}) try: dut.writeline(item.cmd) except RuntimeError: dut.response_coming_in = -1 dut.response_received.set() continue dut.prev = item # Save previous command for logging purposes if item.wait: # Only caller will care if this was asynchronous. dut.waiting_for_response = item else: dut.query_timeout = 0 dut.response_received.set() continue try: line = dut.readline() except RuntimeError: dut.response_coming_in = -1 dut.response_received.set() continue if line: if dut.store_traces: dut.traces.append(line) EventObject(EventTypes.DUT_LINE_RECEIVED, dut, line) retcode = dut.check_retcode(line) if retcode is not None: dut.logger.warning("unrequested retcode", extra={'type': '!<-'}) dut.logger.debug(line, extra={'type': '<<<'}) except IndexError: pass Dut._logger.debug("End DUT communication", extra={'type': '<->'})
[ "def", "run", "(", ")", ":", "# pylint: disable=too-many-branches", "Dut", ".", "_logger", ".", "debug", "(", "\"Start DUT communication\"", ",", "extra", "=", "{", "'type'", ":", "'<->'", "}", ")", "while", "Dut", ".", "_run", ":", "Dut", ".", "_sem", "."...
Main thread runner for all Duts. :return: Nothing
[ "Main", "thread", "runner", "for", "all", "Duts", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L632-L695
27,293
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut._read_response
def _read_response(self): """ Internal response reader. :return: CliResponse or None """ try: line = self.readline() except RuntimeError: Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'}) return -1 if line: if self.store_traces: self.traces.append(line) self.response_traces.append(line) EventObject(EventTypes.DUT_LINE_RECEIVED, self, line) match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line) if match: self.logger.debug(line, extra={'type': '<<<'}) else: self.logger.info(line, extra={'type': '<--'}) retcode = self.check_retcode(line) if retcode is not None: resp = CliResponse() resp.retcode = retcode resp.traces = self.response_traces resp.lines = self.response_traces self.response_traces = [] return resp return None
python
def _read_response(self): try: line = self.readline() except RuntimeError: Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'}) return -1 if line: if self.store_traces: self.traces.append(line) self.response_traces.append(line) EventObject(EventTypes.DUT_LINE_RECEIVED, self, line) match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line) if match: self.logger.debug(line, extra={'type': '<<<'}) else: self.logger.info(line, extra={'type': '<--'}) retcode = self.check_retcode(line) if retcode is not None: resp = CliResponse() resp.retcode = retcode resp.traces = self.response_traces resp.lines = self.response_traces self.response_traces = [] return resp return None
[ "def", "_read_response", "(", "self", ")", ":", "try", ":", "line", "=", "self", ".", "readline", "(", ")", "except", "RuntimeError", ":", "Dut", ".", "_logger", ".", "warning", "(", "\"Failed to read PIPE\"", ",", "extra", "=", "{", "'type'", ":", "'!<-...
Internal response reader. :return: CliResponse or None
[ "Internal", "response", "reader", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L697-L727
27,294
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.check_retcode
def check_retcode(self, line): """ Look for retcode on line line and return return code if found. :param line: Line to search from :return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd tasklet init not found. """ retcode = None match = re.search(r"retcode\: ([-\d]{1,})", line) if match: retcode = num(str(match.group(1))) match = re.search("cmd tasklet init", line) if match: self.logger.debug("Device Boot up", extra={'type': ' '}) return -1 return retcode
python
def check_retcode(self, line): retcode = None match = re.search(r"retcode\: ([-\d]{1,})", line) if match: retcode = num(str(match.group(1))) match = re.search("cmd tasklet init", line) if match: self.logger.debug("Device Boot up", extra={'type': ' '}) return -1 return retcode
[ "def", "check_retcode", "(", "self", ",", "line", ")", ":", "retcode", "=", "None", "match", "=", "re", ".", "search", "(", "r\"retcode\\: ([-\\d]{1,})\"", ",", "line", ")", "if", "match", ":", "retcode", "=", "num", "(", "str", "(", "match", ".", "gro...
Look for retcode on line line and return return code if found. :param line: Line to search from :return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd tasklet init not found.
[ "Look", "for", "retcode", "on", "line", "line", "and", "return", "return", "code", "if", "found", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L730-L747
27,295
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
Dut.start_dut_thread
def start_dut_thread(self): # pylint: disable=no-self-use """ Start Dut thread. :return: Nothing """ if Dut._th is None: Dut._run = True Dut._sem = Semaphore(0) Dut._signalled_duts = deque() Dut._logger = LogManager.get_bench_logger('Dut') Dut._th = Thread(target=Dut.run, name='DutThread') Dut._th.daemon = True Dut._th.start()
python
def start_dut_thread(self): # pylint: disable=no-self-use if Dut._th is None: Dut._run = True Dut._sem = Semaphore(0) Dut._signalled_duts = deque() Dut._logger = LogManager.get_bench_logger('Dut') Dut._th = Thread(target=Dut.run, name='DutThread') Dut._th.daemon = True Dut._th.start()
[ "def", "start_dut_thread", "(", "self", ")", ":", "# pylint: disable=no-self-use", "if", "Dut", ".", "_th", "is", "None", ":", "Dut", ".", "_run", "=", "True", "Dut", ".", "_sem", "=", "Semaphore", "(", "0", ")", "Dut", ".", "_signalled_duts", "=", "dequ...
Start Dut thread. :return: Nothing
[ "Start", "Dut", "thread", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L757-L771
27,296
ARMmbed/icetea
icetea_lib/Events/EventMatcher.py
EventMatcher._event_received
def _event_received(self, ref, data): """ Handle received event. :param ref: ref is the object that generated the event. :param data: event data. :return: Nothing. """ match = self._resolve_match_data(ref, data) if match: if self.flag_to_set: self.flag_to_set.set() if self.callback: self.callback(EventMatch(ref, data, match)) if self.__forget: self.forget()
python
def _event_received(self, ref, data): match = self._resolve_match_data(ref, data) if match: if self.flag_to_set: self.flag_to_set.set() if self.callback: self.callback(EventMatch(ref, data, match)) if self.__forget: self.forget()
[ "def", "_event_received", "(", "self", ",", "ref", ",", "data", ")", ":", "match", "=", "self", ".", "_resolve_match_data", "(", "ref", ",", "data", ")", "if", "match", ":", "if", "self", ".", "flag_to_set", ":", "self", ".", "flag_to_set", ".", "set",...
Handle received event. :param ref: ref is the object that generated the event. :param data: event data. :return: Nothing.
[ "Handle", "received", "event", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Events/EventMatcher.py#L39-L54
27,297
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile.write_file
def write_file(self, content, filepath=None, filename=None, indent=None, keys_to_write=None): ''' Write a Python dictionary as JSON to a file. :param content: Dictionary of key-value pairs to save to a file :param filepath: Path where the file is to be created :param filename: Name of the file to be created :param indent: You can use this to specify indent level for pretty printing the file :param keys_to_write: array of keys that are to be picked from data and written to file. Default is None, when all data is written to file. :return: Path of file used :raises OSError, EnvironmentError, ValueError ''' path = filepath if filepath else self.filepath name = filename if filename else self.filename if not os.path.exists(path): try: os.makedirs(path) except OSError as error: self.logger.error("Error while creating directory: {}".format(error)) raise name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) if keys_to_write: data_to_write = {} for key in keys_to_write: data_to_write[key] = content[key] else: data_to_write = content try: indent = indent if indent else 2 self._write_json(path, name, 'w', data_to_write, indent) return os.path.join(path, name) except EnvironmentError as error: self.logger.error("Error while opening or writing to file: {}".format(error)) raise except ValueError: raise
python
def write_file(self, content, filepath=None, filename=None, indent=None, keys_to_write=None): ''' Write a Python dictionary as JSON to a file. :param content: Dictionary of key-value pairs to save to a file :param filepath: Path where the file is to be created :param filename: Name of the file to be created :param indent: You can use this to specify indent level for pretty printing the file :param keys_to_write: array of keys that are to be picked from data and written to file. Default is None, when all data is written to file. :return: Path of file used :raises OSError, EnvironmentError, ValueError ''' path = filepath if filepath else self.filepath name = filename if filename else self.filename if not os.path.exists(path): try: os.makedirs(path) except OSError as error: self.logger.error("Error while creating directory: {}".format(error)) raise name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) if keys_to_write: data_to_write = {} for key in keys_to_write: data_to_write[key] = content[key] else: data_to_write = content try: indent = indent if indent else 2 self._write_json(path, name, 'w', data_to_write, indent) return os.path.join(path, name) except EnvironmentError as error: self.logger.error("Error while opening or writing to file: {}".format(error)) raise except ValueError: raise
[ "def", "write_file", "(", "self", ",", "content", ",", "filepath", "=", "None", ",", "filename", "=", "None", ",", "indent", "=", "None", ",", "keys_to_write", "=", "None", ")", ":", "path", "=", "filepath", "if", "filepath", "else", "self", ".", "file...
Write a Python dictionary as JSON to a file. :param content: Dictionary of key-value pairs to save to a file :param filepath: Path where the file is to be created :param filename: Name of the file to be created :param indent: You can use this to specify indent level for pretty printing the file :param keys_to_write: array of keys that are to be picked from data and written to file. Default is None, when all data is written to file. :return: Path of file used :raises OSError, EnvironmentError, ValueError
[ "Write", "a", "Python", "dictionary", "as", "JSON", "to", "a", "file", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L33-L73
27,298
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile.read_file
def read_file(self, filepath=None, filename=None): """ Tries to read JSON content from filename and convert it to a dict. :param filepath: Path where the file is :param filename: File name :return: Dictionary read from the file :raises EnvironmentError, ValueError """ name = filename if filename else self.filename path = filepath if filepath else self.filepath name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) try: return self._read_json(path, name) except EnvironmentError as error: self.logger.error("Error while opening or reading the file: {}".format(error)) raise except ValueError as error: self.logger.error("File contents cannot be decoded to JSON: {}".format(error)) raise
python
def read_file(self, filepath=None, filename=None): name = filename if filename else self.filename path = filepath if filepath else self.filepath name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) try: return self._read_json(path, name) except EnvironmentError as error: self.logger.error("Error while opening or reading the file: {}".format(error)) raise except ValueError as error: self.logger.error("File contents cannot be decoded to JSON: {}".format(error)) raise
[ "def", "read_file", "(", "self", ",", "filepath", "=", "None", ",", "filename", "=", "None", ")", ":", "name", "=", "filename", "if", "filename", "else", "self", ".", "filename", "path", "=", "filepath", "if", "filepath", "else", "self", ".", "filepath",...
Tries to read JSON content from filename and convert it to a dict. :param filepath: Path where the file is :param filename: File name :return: Dictionary read from the file :raises EnvironmentError, ValueError
[ "Tries", "to", "read", "JSON", "content", "from", "filename", "and", "convert", "it", "to", "a", "dict", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L75-L96
27,299
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile.read_value
def read_value(self, key, filepath=None, filename=None): """ Tries to read the value of given key from JSON file filename. :param filepath: Path to file :param filename: Name of file :param key: Key to search for :return: Value corresponding to given key :raises OSError, EnvironmentError, KeyError """ path = filepath if filepath else self.filepath name = filename if filename else self.filename name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) try: output = self._read_json(path, name) if key not in output: raise KeyError("Key '{}' not found in file {}".format(key, filename)) else: return output[key] except EnvironmentError as error: self.logger.error("Error while opening or reading the file: {}".format(error)) raise
python
def read_value(self, key, filepath=None, filename=None): path = filepath if filepath else self.filepath name = filename if filename else self.filename name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) try: output = self._read_json(path, name) if key not in output: raise KeyError("Key '{}' not found in file {}".format(key, filename)) else: return output[key] except EnvironmentError as error: self.logger.error("Error while opening or reading the file: {}".format(error)) raise
[ "def", "read_value", "(", "self", ",", "key", ",", "filepath", "=", "None", ",", "filename", "=", "None", ")", ":", "path", "=", "filepath", "if", "filepath", "else", "self", ".", "filepath", "name", "=", "filename", "if", "filename", "else", "self", "...
Tries to read the value of given key from JSON file filename. :param filepath: Path to file :param filename: Name of file :param key: Key to search for :return: Value corresponding to given key :raises OSError, EnvironmentError, KeyError
[ "Tries", "to", "read", "the", "value", "of", "given", "key", "from", "JSON", "file", "filename", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L98-L121