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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
klen/graphite-beacon
graphite_beacon/units.py
TimeUnit._normalize_unit
def _normalize_unit(cls, unit): """Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str] """ if unit in cls.UNITS_IN_SECONDS: return unit return cls.UNIT_ALIASES_REVERSE.get(unit, None)
python
def _normalize_unit(cls, unit): """Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str] """ if unit in cls.UNITS_IN_SECONDS: return unit return cls.UNIT_ALIASES_REVERSE.get(unit, None)
[ "def", "_normalize_unit", "(", "cls", ",", "unit", ")", ":", "if", "unit", "in", "cls", ".", "UNITS_IN_SECONDS", ":", "return", "unit", "return", "cls", ".", "UNIT_ALIASES_REVERSE", ".", "get", "(", "unit", ",", "None", ")" ]
Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str]
[ "Resolve", "a", "unit", "to", "its", "real", "name", "if", "it", "s", "an", "alias", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L121-L130
train
25,700
klen/graphite-beacon
graphite_beacon/units.py
TimeUnit.convert
def convert(cls, value, from_unit, to_unit): """Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float """ value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]
python
def convert(cls, value, from_unit, to_unit): """Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float """ value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]
[ "def", "convert", "(", "cls", ",", "value", ",", "from_unit", ",", "to_unit", ")", ":", "value_ms", "=", "value", "*", "cls", ".", "UNITS_IN_MILLISECONDS", "[", "from_unit", "]", "return", "value_ms", "/", "cls", ".", "UNITS_IN_MILLISECONDS", "[", "to_unit",...
Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float
[ "Convert", "a", "value", "from", "one", "time", "unit", "to", "another", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L148-L155
train
25,701
klen/graphite-beacon
graphite_beacon/handlers/smtp.py
SMTPHandler.init_handler
def init_handler(self): """ Check self options. """ assert self.options.get('host') and self.options.get('port'), "Invalid options" assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.' if not isinstance(self.options['to'], (list, tuple)): self.options['to'] = [self.options['to']]
python
def init_handler(self): """ Check self options. """ assert self.options.get('host') and self.options.get('port'), "Invalid options" assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.' if not isinstance(self.options['to'], (list, tuple)): self.options['to'] = [self.options['to']]
[ "def", "init_handler", "(", "self", ")", ":", "assert", "self", ".", "options", ".", "get", "(", "'host'", ")", "and", "self", ".", "options", ".", "get", "(", "'port'", ")", ",", "\"Invalid options\"", "assert", "self", ".", "options", ".", "get", "("...
Check self options.
[ "Check", "self", "options", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/smtp.py#L28-L33
train
25,702
alexprengere/FormalSystems
formalsystems/formalsystems.py
iterator_mix
def iterator_mix(*iterators): """ Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty. """ while True: one_left = False for it in iterators: try: yield it.next() except StopIteration: pass else: one_left = True if not one_left: break
python
def iterator_mix(*iterators): """ Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty. """ while True: one_left = False for it in iterators: try: yield it.next() except StopIteration: pass else: one_left = True if not one_left: break
[ "def", "iterator_mix", "(", "*", "iterators", ")", ":", "while", "True", ":", "one_left", "=", "False", "for", "it", "in", "iterators", ":", "try", ":", "yield", "it", ".", "next", "(", ")", "except", "StopIteration", ":", "pass", "else", ":", "one_lef...
Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty.
[ "Iterating", "over", "list", "of", "iterators", ".", "Bit", "like", "zip", "but", "zip", "stops", "after", "the", "shortest", "iterator", "is", "empty", "abd", "here", "we", "go", "one", "until", "all", "iterators", "are", "empty", "." ]
e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e
https://github.com/alexprengere/FormalSystems/blob/e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e/formalsystems/formalsystems.py#L309-L328
train
25,703
grantmcconnaughey/Lintly
lintly/parsers.py
BaseLintParser._normalize_path
def _normalize_path(self, path): """ Normalizes a file path so that it returns a path relative to the root repo directory. """ norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
python
def _normalize_path(self, path): """ Normalizes a file path so that it returns a path relative to the root repo directory. """ norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
[ "def", "_normalize_path", "(", "self", ",", "path", ")", ":", "norm_path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "return", "os", ".", "path", ".", "relpath", "(", "norm_path", ",", "start", "=", "self", ".", "_get_working_dir", "("...
Normalizes a file path so that it returns a path relative to the root repo directory.
[ "Normalizes", "a", "file", "path", "so", "that", "it", "returns", "a", "path", "relative", "to", "the", "root", "repo", "directory", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/parsers.py#L21-L26
train
25,704
grantmcconnaughey/Lintly
lintly/backends/github.py
translate_github_exception
def translate_github_exception(func): """ Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnknownObjectException as e: logger.exception('GitHub API 404 Exception') raise NotFoundError(str(e)) except GithubException as e: logger.exception('GitHub API Exception') raise GitClientError(str(e)) return _wrapper
python
def translate_github_exception(func): """ Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnknownObjectException as e: logger.exception('GitHub API 404 Exception') raise NotFoundError(str(e)) except GithubException as e: logger.exception('GitHub API Exception') raise GitClientError(str(e)) return _wrapper
[ "def", "translate_github_exception", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kw...
Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions.
[ "Decorator", "to", "catch", "GitHub", "-", "specific", "exceptions", "and", "raise", "them", "as", "GitClientError", "exceptions", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/backends/github.py#L29-L45
train
25,705
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.violations
def violations(self): """ Returns either the diff violations or all violations depending on configuration. """ return self._all_violations if self.config.fail_on == FAIL_ON_ANY else self._diff_violations
python
def violations(self): """ Returns either the diff violations or all violations depending on configuration. """ return self._all_violations if self.config.fail_on == FAIL_ON_ANY else self._diff_violations
[ "def", "violations", "(", "self", ")", ":", "return", "self", ".", "_all_violations", "if", "self", ".", "config", ".", "fail_on", "==", "FAIL_ON_ANY", "else", "self", ".", "_diff_violations" ]
Returns either the diff violations or all violations depending on configuration.
[ "Returns", "either", "the", "diff", "violations", "or", "all", "violations", "depending", "on", "configuration", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L35-L39
train
25,706
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.execute
def execute(self): """ Executes a new build on a project. """ if not self.config.pr: raise NotPullRequestException logger.debug('Using the following configuration:') for name, value in self.config.as_dict().items(): logger.debug(' - {}={}'.format(name, repr(value))) logger.info('Running Lintly against PR #{} for repo {}'.format(self.config.pr, self.project)) parser = PARSERS.get(self.config.format) self._all_violations = parser.parse_violations(self.linter_output) logger.info('Lintly found violations in {} files'.format(len(self._all_violations))) diff = self.get_pr_diff() patch = self.get_pr_patch(diff) self._diff_violations = self.find_diff_violations(patch) logger.info('Lintly found diff violations in {} files'.format(len(self._diff_violations))) self.post_pr_comment(patch) self.post_commit_status()
python
def execute(self): """ Executes a new build on a project. """ if not self.config.pr: raise NotPullRequestException logger.debug('Using the following configuration:') for name, value in self.config.as_dict().items(): logger.debug(' - {}={}'.format(name, repr(value))) logger.info('Running Lintly against PR #{} for repo {}'.format(self.config.pr, self.project)) parser = PARSERS.get(self.config.format) self._all_violations = parser.parse_violations(self.linter_output) logger.info('Lintly found violations in {} files'.format(len(self._all_violations))) diff = self.get_pr_diff() patch = self.get_pr_patch(diff) self._diff_violations = self.find_diff_violations(patch) logger.info('Lintly found diff violations in {} files'.format(len(self._diff_violations))) self.post_pr_comment(patch) self.post_commit_status()
[ "def", "execute", "(", "self", ")", ":", "if", "not", "self", ".", "config", ".", "pr", ":", "raise", "NotPullRequestException", "logger", ".", "debug", "(", "'Using the following configuration:'", ")", "for", "name", ",", "value", "in", "self", ".", "config...
Executes a new build on a project.
[ "Executes", "a", "new", "build", "on", "a", "project", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L51-L74
train
25,707
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.find_diff_violations
def find_diff_violations(self, patch): """ Uses the diff for this build to find changed lines that also have violations. """ violations = collections.defaultdict(list) for line in patch.changed_lines: file_violations = self._all_violations.get(line['file_name']) if not file_violations: continue line_violations = [v for v in file_violations if v.line == line['line_number']] for v in line_violations: violations[line['file_name']].append(v) return violations
python
def find_diff_violations(self, patch): """ Uses the diff for this build to find changed lines that also have violations. """ violations = collections.defaultdict(list) for line in patch.changed_lines: file_violations = self._all_violations.get(line['file_name']) if not file_violations: continue line_violations = [v for v in file_violations if v.line == line['line_number']] for v in line_violations: violations[line['file_name']].append(v) return violations
[ "def", "find_diff_violations", "(", "self", ",", "patch", ")", ":", "violations", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "line", "in", "patch", ".", "changed_lines", ":", "file_violations", "=", "self", ".", "_all_violations", ".", ...
Uses the diff for this build to find changed lines that also have violations.
[ "Uses", "the", "diff", "for", "this", "build", "to", "find", "changed", "lines", "that", "also", "have", "violations", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L82-L97
train
25,708
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.post_pr_comment
def post_pr_comment(self, patch): """ Posts a comment to the GitHub PR if the diff results have issues. """ if self.has_violations: post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not have permission to review the PR then simply revert to posting a regular PR # comment. try: logger.info('Deleting old PR review comments') self.git_client.delete_pull_request_review_comments(self.config.pr) logger.info('Creating PR review') self.git_client.create_pull_request_review(self.config.pr, patch, self._diff_violations) post_pr_comment = False except GitClientError as e: # TODO: Make `create_pull_request_review` raise an `UnauthorizedError` # so that we don't have to check for a specific message in the exception if 'Viewer does not have permission to review this pull request' in str(e): logger.warning("Could not post PR review (the account didn't have permission)") pass else: raise if post_pr_comment: logger.info('Deleting old PR comment') self.git_client.delete_pull_request_comments(self.config.pr) logger.info('Creating PR comment') comment = build_pr_comment(self.config, self.violations) self.git_client.create_pull_request_comment(self.config.pr, comment)
python
def post_pr_comment(self, patch): """ Posts a comment to the GitHub PR if the diff results have issues. """ if self.has_violations: post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not have permission to review the PR then simply revert to posting a regular PR # comment. try: logger.info('Deleting old PR review comments') self.git_client.delete_pull_request_review_comments(self.config.pr) logger.info('Creating PR review') self.git_client.create_pull_request_review(self.config.pr, patch, self._diff_violations) post_pr_comment = False except GitClientError as e: # TODO: Make `create_pull_request_review` raise an `UnauthorizedError` # so that we don't have to check for a specific message in the exception if 'Viewer does not have permission to review this pull request' in str(e): logger.warning("Could not post PR review (the account didn't have permission)") pass else: raise if post_pr_comment: logger.info('Deleting old PR comment') self.git_client.delete_pull_request_comments(self.config.pr) logger.info('Creating PR comment') comment = build_pr_comment(self.config, self.violations) self.git_client.create_pull_request_comment(self.config.pr, comment)
[ "def", "post_pr_comment", "(", "self", ",", "patch", ")", ":", "if", "self", ".", "has_violations", ":", "post_pr_comment", "=", "True", "# Attempt to post a PR review. If posting the PR review fails because the bot account", "# does not have permission to review the PR then simply...
Posts a comment to the GitHub PR if the diff results have issues.
[ "Posts", "a", "comment", "to", "the", "GitHub", "PR", "if", "the", "diff", "results", "have", "issues", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L99-L131
train
25,709
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.post_commit_status
def post_commit_status(self): """ Posts results to a commit status in GitHub if this build is for a pull request. """ if self.violations: plural = '' if self.introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}'.format( self.introduced_issues_count, plural) self._post_status('failure', description) else: self._post_status('success', 'Linting detected no new issues.')
python
def post_commit_status(self): """ Posts results to a commit status in GitHub if this build is for a pull request. """ if self.violations: plural = '' if self.introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}'.format( self.introduced_issues_count, plural) self._post_status('failure', description) else: self._post_status('success', 'Linting detected no new issues.')
[ "def", "post_commit_status", "(", "self", ")", ":", "if", "self", ".", "violations", ":", "plural", "=", "''", "if", "self", ".", "introduced_issues_count", "==", "1", "else", "'s'", "description", "=", "'Pull Request introduced {} linting violation{}'", ".", "for...
Posts results to a commit status in GitHub if this build is for a pull request.
[ "Posts", "results", "to", "a", "commit", "status", "in", "GitHub", "if", "this", "build", "is", "for", "a", "pull", "request", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L133-L143
train
25,710
alexprengere/FormalSystems
formalsystems/leplparsing.py
reg_to_lex
def reg_to_lex(conditions, wildcards): """Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values for all aliases like x_0, x_1 are the same. """ aliases = defaultdict(set) n_conds = [] # All conditions for i, _ in enumerate(conditions): n_cond = [] for char in conditions[i]: if char in wildcards: alias = '%s_%s' % (char, len(aliases[char])) aliases[char].add(alias) n_cond.append(make_token(alias, reg=wildcards[char])) else: n_cond.append(~Literal(char)) n_cond.append(Eos()) n_conds.append(reduce(operator.and_, n_cond) > make_dict) return tuple(n_conds), aliases
python
def reg_to_lex(conditions, wildcards): """Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values for all aliases like x_0, x_1 are the same. """ aliases = defaultdict(set) n_conds = [] # All conditions for i, _ in enumerate(conditions): n_cond = [] for char in conditions[i]: if char in wildcards: alias = '%s_%s' % (char, len(aliases[char])) aliases[char].add(alias) n_cond.append(make_token(alias, reg=wildcards[char])) else: n_cond.append(~Literal(char)) n_cond.append(Eos()) n_conds.append(reduce(operator.and_, n_cond) > make_dict) return tuple(n_conds), aliases
[ "def", "reg_to_lex", "(", "conditions", ",", "wildcards", ")", ":", "aliases", "=", "defaultdict", "(", "set", ")", "n_conds", "=", "[", "]", "# All conditions", "for", "i", ",", "_", "in", "enumerate", "(", "conditions", ")", ":", "n_cond", "=", "[", ...
Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values for all aliases like x_0, x_1 are the same.
[ "Transform", "a", "regular", "expression", "into", "a", "LEPL", "object", "." ]
e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e
https://github.com/alexprengere/FormalSystems/blob/e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e/formalsystems/leplparsing.py#L11-L39
train
25,711
grantmcconnaughey/Lintly
lintly/cli.py
main
def main(**options): """Slurp up linter output and send it to a GitHub PR review.""" configure_logging(log_all=options.get('log')) stdin_stream = click.get_text_stream('stdin') stdin_text = stdin_stream.read() click.echo(stdin_text) ci = find_ci_provider() config = Config(options, ci=ci) build = LintlyBuild(config, stdin_text) try: build.execute() except NotPullRequestException: logger.info('Not a PR. Lintly is exiting.') sys.exit(0) # Exit with the number of files that have violations sys.exit(len(build.violations))
python
def main(**options): """Slurp up linter output and send it to a GitHub PR review.""" configure_logging(log_all=options.get('log')) stdin_stream = click.get_text_stream('stdin') stdin_text = stdin_stream.read() click.echo(stdin_text) ci = find_ci_provider() config = Config(options, ci=ci) build = LintlyBuild(config, stdin_text) try: build.execute() except NotPullRequestException: logger.info('Not a PR. Lintly is exiting.') sys.exit(0) # Exit with the number of files that have violations sys.exit(len(build.violations))
[ "def", "main", "(", "*", "*", "options", ")", ":", "configure_logging", "(", "log_all", "=", "options", ".", "get", "(", "'log'", ")", ")", "stdin_stream", "=", "click", ".", "get_text_stream", "(", "'stdin'", ")", "stdin_text", "=", "stdin_stream", ".", ...
Slurp up linter output and send it to a GitHub PR review.
[ "Slurp", "up", "linter", "output", "and", "send", "it", "to", "a", "GitHub", "PR", "review", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/cli.py#L53-L73
train
25,712
grantmcconnaughey/Lintly
lintly/backends/gitlab.py
translate_gitlab_exception
def translate_gitlab_exception(func): """ Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: status_to_exception = { 401: UnauthorizedError, 404: NotFoundError, } exc_class = status_to_exception.get(e.response_code, GitClientError) raise exc_class(str(e), status_code=e.response_code) return _wrapper
python
def translate_gitlab_exception(func): """ Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: status_to_exception = { 401: UnauthorizedError, 404: NotFoundError, } exc_class = status_to_exception.get(e.response_code, GitClientError) raise exc_class(str(e), status_code=e.response_code) return _wrapper
[ "def", "translate_gitlab_exception", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kw...
Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions.
[ "Decorator", "to", "catch", "GitLab", "-", "specific", "exceptions", "and", "raise", "them", "as", "GitClientError", "exceptions", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/backends/gitlab.py#L29-L47
train
25,713
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
init_process_dut
def init_process_dut(contextlist, conf, index, args): """ Initialize process type Dut as DutProcess or DutConsole. """ if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(conf["subtype"])) raise ResourceInitError("Unrecognized process subtype: {}") # This is a specialized 'console' process config = None if "application" in conf: config = conf["application"] contextlist.logger.debug("Starting a remote console") dut = DutConsole(name="D%d" % index, conf=config, params=args) dut.index = index else: binary = conf["application"]['bin'] app_config = conf["application"] init_cli_cmds = app_config.get("init_cli_cmds", None) post_cli_cmds = app_config.get("post_cli_cmds", None) contextlist.logger.debug("Starting process '%s'" % binary) dut = DutProcess(name="D%d" % index, config=conf, params=args) dut.index = index dut.command = binary if args.valgrind: dut.use_valgrind(args.valgrind_tool, not args.valgrind_text, args.valgrind_console, args.valgrind_track_origins, args.valgrind_extra_params) if args.gdb == index: dut.use_gdb() contextlist.logger.info("GDB is activated for node %i" % index) if args.gdbs == index: dut.use_gdbs(True, args.gdbs_port) contextlist.logger.info("GDBserver is activated for node %i" % index) if args.vgdb == index: dut.use_vgdb() contextlist.logger.info("VGDB is activated for node %i" % index) if args.nobuf: dut.no_std_buf() if init_cli_cmds is not None: dut.set_init_cli_cmds(init_cli_cmds) if post_cli_cmds is not None: dut.set_post_cli_cmds(post_cli_cmds) contextlist.duts.append(dut) contextlist.dutinformations.append(dut.get_info())
python
def init_process_dut(contextlist, conf, index, args): """ Initialize process type Dut as DutProcess or DutConsole. """ if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(conf["subtype"])) raise ResourceInitError("Unrecognized process subtype: {}") # This is a specialized 'console' process config = None if "application" in conf: config = conf["application"] contextlist.logger.debug("Starting a remote console") dut = DutConsole(name="D%d" % index, conf=config, params=args) dut.index = index else: binary = conf["application"]['bin'] app_config = conf["application"] init_cli_cmds = app_config.get("init_cli_cmds", None) post_cli_cmds = app_config.get("post_cli_cmds", None) contextlist.logger.debug("Starting process '%s'" % binary) dut = DutProcess(name="D%d" % index, config=conf, params=args) dut.index = index dut.command = binary if args.valgrind: dut.use_valgrind(args.valgrind_tool, not args.valgrind_text, args.valgrind_console, args.valgrind_track_origins, args.valgrind_extra_params) if args.gdb == index: dut.use_gdb() contextlist.logger.info("GDB is activated for node %i" % index) if args.gdbs == index: dut.use_gdbs(True, args.gdbs_port) contextlist.logger.info("GDBserver is activated for node %i" % index) if args.vgdb == index: dut.use_vgdb() contextlist.logger.info("VGDB is activated for node %i" % index) if args.nobuf: dut.no_std_buf() if init_cli_cmds is not None: dut.set_init_cli_cmds(init_cli_cmds) if post_cli_cmds is not None: dut.set_post_cli_cmds(post_cli_cmds) contextlist.duts.append(dut) contextlist.dutinformations.append(dut.get_info())
[ "def", "init_process_dut", "(", "contextlist", ",", "conf", ",", "index", ",", "args", ")", ":", "if", "\"subtype\"", "in", "conf", "and", "conf", "[", "\"subtype\"", "]", ":", "if", "conf", "[", "\"subtype\"", "]", "!=", "\"console\"", ":", "msg", "=", ...
Initialize process type Dut as DutProcess or DutConsole.
[ "Initialize", "process", "type", "Dut", "as", "DutProcess", "or", "DutConsole", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L140-L189
train
25,714
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
LocalAllocator.allocate
def allocate(self, dut_configuration_list, args=None): """ Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources """ dut_config_list = dut_configuration_list.get_dut_configuration() # if we need one or more local hardware duts let's search attached # devices using DutDetection if not isinstance(dut_config_list, list): raise AllocationError("Invalid dut configuration format!") if next((item for item in dut_config_list if item.get("type") == "hardware"), False): self._available_devices = DutDetection().get_available_devices() if len(self._available_devices) < len(dut_config_list): raise AllocationError("Required amount of devices not available.") # Enumerate all required DUT's try: for dut_config in dut_config_list: if not self.can_allocate(dut_config.get_requirements()): raise AllocationError("Resource type is not supported") self._allocate(dut_config) except AllocationError: # Locally allocated don't need to be released any way for # now, so just re-raise the error raise alloc_list = AllocationContextList() res_id = None for conf in dut_config_list: if conf.get("type") == "mbed": res_id = conf.get("allocated").get("target_id") context = AllocationContext(resource_id=res_id, alloc_data=conf) alloc_list.append(context) alloc_list.set_dut_init_function("serial", init_generic_serial_dut) alloc_list.set_dut_init_function("process", init_process_dut) alloc_list.set_dut_init_function("mbed", init_mbed_dut) return alloc_list
python
def allocate(self, dut_configuration_list, args=None): """ Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources """ dut_config_list = dut_configuration_list.get_dut_configuration() # if we need one or more local hardware duts let's search attached # devices using DutDetection if not isinstance(dut_config_list, list): raise AllocationError("Invalid dut configuration format!") if next((item for item in dut_config_list if item.get("type") == "hardware"), False): self._available_devices = DutDetection().get_available_devices() if len(self._available_devices) < len(dut_config_list): raise AllocationError("Required amount of devices not available.") # Enumerate all required DUT's try: for dut_config in dut_config_list: if not self.can_allocate(dut_config.get_requirements()): raise AllocationError("Resource type is not supported") self._allocate(dut_config) except AllocationError: # Locally allocated don't need to be released any way for # now, so just re-raise the error raise alloc_list = AllocationContextList() res_id = None for conf in dut_config_list: if conf.get("type") == "mbed": res_id = conf.get("allocated").get("target_id") context = AllocationContext(resource_id=res_id, alloc_data=conf) alloc_list.append(context) alloc_list.set_dut_init_function("serial", init_generic_serial_dut) alloc_list.set_dut_init_function("process", init_process_dut) alloc_list.set_dut_init_function("mbed", init_mbed_dut) return alloc_list
[ "def", "allocate", "(", "self", ",", "dut_configuration_list", ",", "args", "=", "None", ")", ":", "dut_config_list", "=", "dut_configuration_list", ".", "get_dut_configuration", "(", ")", "# if we need one or more local hardware duts let's search attached", "# devices using ...
Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources
[ "Allocates", "resources", "from", "available", "local", "devices", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L225-L266
train
25,715
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
LocalAllocator._allocate
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches """ Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises: AllocationError if suitable resource was not found or if the platform was not allowed to be used. """ if dut_configuration["type"] == "hardware": dut_configuration.set("type", "mbed") if dut_configuration["type"] == "mbed": if not self._available_devices: raise AllocationError("No available devices to allocate from") dut_reqs = dut_configuration.get_requirements() platforms = None if 'allowed_platforms' not in dut_reqs else dut_reqs[ 'allowed_platforms'] platform_name = None if 'platform_name' not in dut_reqs else dut_reqs[ "platform_name"] if platform_name is None and platforms: platform_name = platforms[0] if platform_name and platforms: if platform_name not in platforms: raise AllocationError("Platform name not in allowed platforms.") # Enumerate through all available devices for dev in self._available_devices: if platform_name and dev["platform_name"] != platform_name: self.logger.debug("Skipping device %s because of mismatching platform. " "Required %s but device was %s", dev['target_id'], platform_name, dev['platform_name']) continue if dev['state'] == 'allocated': self.logger.debug("Skipping device %s because it was " "already allocated", dev['target_id']) continue if DutDetection.is_port_usable(dev['serial_port']): dev['state'] = "allocated" dut_reqs['allocated'] = dev self.logger.info("Allocated device %s", dev['target_id']) return True else: self.logger.info("Could not open serial port (%s) of " "allocated device %s", dev['serial_port'], dev['target_id']) # Didn't find a matching device to allocate so allocation failed raise AllocationError("No suitable local device available") elif dut_configuration["type"] == "serial": dut_reqs = dut_configuration.get_requirements() if not dut_reqs.get("serial_port"): raise AllocationError("Serial port not defined for requirement {}".format(dut_reqs)) if not DutDetection.is_port_usable(dut_reqs['serial_port']): raise AllocationError("Serial port {} not usable".format(dut_reqs['serial_port'])) # Successful allocation, return True return True
python
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches """ Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises: AllocationError if suitable resource was not found or if the platform was not allowed to be used. """ if dut_configuration["type"] == "hardware": dut_configuration.set("type", "mbed") if dut_configuration["type"] == "mbed": if not self._available_devices: raise AllocationError("No available devices to allocate from") dut_reqs = dut_configuration.get_requirements() platforms = None if 'allowed_platforms' not in dut_reqs else dut_reqs[ 'allowed_platforms'] platform_name = None if 'platform_name' not in dut_reqs else dut_reqs[ "platform_name"] if platform_name is None and platforms: platform_name = platforms[0] if platform_name and platforms: if platform_name not in platforms: raise AllocationError("Platform name not in allowed platforms.") # Enumerate through all available devices for dev in self._available_devices: if platform_name and dev["platform_name"] != platform_name: self.logger.debug("Skipping device %s because of mismatching platform. " "Required %s but device was %s", dev['target_id'], platform_name, dev['platform_name']) continue if dev['state'] == 'allocated': self.logger.debug("Skipping device %s because it was " "already allocated", dev['target_id']) continue if DutDetection.is_port_usable(dev['serial_port']): dev['state'] = "allocated" dut_reqs['allocated'] = dev self.logger.info("Allocated device %s", dev['target_id']) return True else: self.logger.info("Could not open serial port (%s) of " "allocated device %s", dev['serial_port'], dev['target_id']) # Didn't find a matching device to allocate so allocation failed raise AllocationError("No suitable local device available") elif dut_configuration["type"] == "serial": dut_reqs = dut_configuration.get_requirements() if not dut_reqs.get("serial_port"): raise AllocationError("Serial port not defined for requirement {}".format(dut_reqs)) if not DutDetection.is_port_usable(dut_reqs['serial_port']): raise AllocationError("Serial port {} not usable".format(dut_reqs['serial_port'])) # Successful allocation, return True return True
[ "def", "_allocate", "(", "self", ",", "dut_configuration", ")", ":", "# pylint: disable=too-many-branches", "if", "dut_configuration", "[", "\"type\"", "]", "==", "\"hardware\"", ":", "dut_configuration", ".", "set", "(", "\"type\"", ",", "\"mbed\"", ")", "if", "d...
Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises: AllocationError if suitable resource was not found or if the platform was not allowed to be used.
[ "Internal", "allocation", "function", ".", "Allocates", "a", "single", "resource", "based", "on", "dut_configuration", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L277-L331
train
25,716
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.register_tc_plugins
def register_tc_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! Duplicate " "plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) plugin_class.init(bench=self.bench) if plugin_class.get_bench_api() is not None: register_func = self.plugin_types[PluginTypes.BENCH] register_func(plugin_name, plugin_class) if plugin_class.get_parsers() is not None: register_func = self.plugin_types[PluginTypes.PARSER] register_func(plugin_name, plugin_class) if plugin_class.get_external_services() is not None: register_func = self.plugin_types[PluginTypes.EXTSERVICE] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
python
def register_tc_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! Duplicate " "plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) plugin_class.init(bench=self.bench) if plugin_class.get_bench_api() is not None: register_func = self.plugin_types[PluginTypes.BENCH] register_func(plugin_name, plugin_class) if plugin_class.get_parsers() is not None: register_func = self.plugin_types[PluginTypes.PARSER] register_func(plugin_name, plugin_class) if plugin_class.get_external_services() is not None: register_func = self.plugin_types[PluginTypes.EXTSERVICE] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
[ "def", "register_tc_plugins", "(", "self", ",", "plugin_name", ",", "plugin_class", ")", ":", "if", "plugin_name", "in", "self", ".", "registered_plugins", ":", "raise", "PluginException", "(", "\"Plugin {} already registered! Duplicate \"", "\"plugins?\"", ".", "format...
Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing
[ "Loads", "a", "plugin", "as", "a", "dictionary", "and", "attaches", "needed", "parts", "to", "correct", "areas", "for", "testing", "parts", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L64-L88
train
25,717
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.register_run_plugins
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! " "Duplicate plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) if plugin_class.get_allocators(): register_func = self.plugin_types[PluginTypes.ALLOCATOR] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
python
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! " "Duplicate plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) if plugin_class.get_allocators(): register_func = self.plugin_types[PluginTypes.ALLOCATOR] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
[ "def", "register_run_plugins", "(", "self", ",", "plugin_name", ",", "plugin_class", ")", ":", "if", "plugin_name", "in", "self", ".", "registered_plugins", ":", "raise", "PluginException", "(", "\"Plugin {} already registered! \"", "\"Duplicate plugins?\"", ".", "forma...
Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing
[ "Loads", "a", "plugin", "as", "a", "dictionary", "and", "attaches", "needed", "parts", "to", "correct", "Icetea", "run", "global", "parts", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L90-L106
train
25,718
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_default_tc_plugins
def load_default_tc_plugins(self): """ Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_default_tc_plugins(self): """ Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_default_tc_plugins", "(", "self", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "default_plugins", ".", "items", "(", ")", ":", "if", "issubclass", "(", "plugin_class", ",", "PluginBase", ")", ":", "try", ":", "self", ".", "register...
Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing
[ "Load", "default", "test", "case", "level", "plugins", "from", "icetea_lib", ".", "Plugin", ".", "plugins", ".", "default_plugins", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L119-L131
train
25,719
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_custom_tc_plugins
def load_custom_tc_plugins(self, plugin_path=None): """ Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those. """ if not plugin_path: return directory = os.path.dirname(plugin_path) sys.path.append(directory) modulename = os.path.split(plugin_path)[1] # Strip of file extension. if "." in modulename: modulename = modulename[:modulename.rindex(".")] try: module = importlib.import_module(modulename) except ImportError: raise PluginException("Unable to import custom plugin information from {}.".format( plugin_path)) for plugin_name, plugin_class in module.plugins_to_load.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_custom_tc_plugins(self, plugin_path=None): """ Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those. """ if not plugin_path: return directory = os.path.dirname(plugin_path) sys.path.append(directory) modulename = os.path.split(plugin_path)[1] # Strip of file extension. if "." in modulename: modulename = modulename[:modulename.rindex(".")] try: module = importlib.import_module(modulename) except ImportError: raise PluginException("Unable to import custom plugin information from {}.".format( plugin_path)) for plugin_name, plugin_class in module.plugins_to_load.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_custom_tc_plugins", "(", "self", ",", "plugin_path", "=", "None", ")", ":", "if", "not", "plugin_path", ":", "return", "directory", "=", "os", ".", "path", ".", "dirname", "(", "plugin_path", ")", "sys", ".", "path", ".", "append", "(", "dir...
Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those.
[ "Load", "custom", "test", "case", "level", "plugins", "from", "plugin_path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L133-L159
train
25,720
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_default_run_plugins
def load_default_run_plugins(self): """ Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: self.register_run_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_default_run_plugins(self): """ Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: self.register_run_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_default_run_plugins", "(", "self", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "default_plugins", ".", "items", "(", ")", ":", "if", "issubclass", "(", "plugin_class", ",", "RunPluginBase", ")", ":", "try", ":", "self", ".", "regi...
Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing
[ "Load", "default", "run", "level", "plugins", "from", "icetea_lib", ".", "Plugin", ".", "plugins", ".", "default_plugins", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L161-L173
train
25,721
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.start_external_service
def start_external_service(self, service_name, conf=None): """ Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing """ if service_name in self._external_services: ser = self._external_services[service_name] service = ser(service_name, conf=conf, bench=self.bench) try: service.start() except PluginException: self.logger.exception("Starting service %s caused an exception!", service_name) raise PluginException("Failed to start external service {}".format(service_name)) self._started_services.append(service) setattr(self.bench, service_name, service) else: self.logger.warning("Service %s not found. Check your plugins.", service_name)
python
def start_external_service(self, service_name, conf=None): """ Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing """ if service_name in self._external_services: ser = self._external_services[service_name] service = ser(service_name, conf=conf, bench=self.bench) try: service.start() except PluginException: self.logger.exception("Starting service %s caused an exception!", service_name) raise PluginException("Failed to start external service {}".format(service_name)) self._started_services.append(service) setattr(self.bench, service_name, service) else: self.logger.warning("Service %s not found. Check your plugins.", service_name)
[ "def", "start_external_service", "(", "self", ",", "service_name", ",", "conf", "=", "None", ")", ":", "if", "service_name", "in", "self", ".", "_external_services", ":", "ser", "=", "self", ".", "_external_services", "[", "service_name", "]", "service", "=", ...
Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing
[ "Start", "external", "service", "service_name", "with", "configuration", "conf", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L203-L222
train
25,722
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.stop_external_services
def stop_external_services(self): """ Stop all external services. :return: Nothing """ for service in self._started_services: self.logger.debug("Stopping application %s", service.name) try: service.stop() except PluginException: self.logger.exception("Stopping external service %s caused and exception!", service.name) self._started_services = []
python
def stop_external_services(self): """ Stop all external services. :return: Nothing """ for service in self._started_services: self.logger.debug("Stopping application %s", service.name) try: service.stop() except PluginException: self.logger.exception("Stopping external service %s caused and exception!", service.name) self._started_services = []
[ "def", "stop_external_services", "(", "self", ")", ":", "for", "service", "in", "self", ".", "_started_services", ":", "self", ".", "logger", ".", "debug", "(", "\"Stopping application %s\"", ",", "service", ".", "name", ")", "try", ":", "service", ".", "sto...
Stop all external services. :return: Nothing
[ "Stop", "all", "external", "services", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L224-L237
train
25,723
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_bench_extension
def _register_bench_extension(self, plugin_name, plugin_instance): """ Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing """ for attr in plugin_instance.get_bench_api().keys(): if hasattr(self.bench, attr): raise PluginException("Attribute {} already exists in bench! Unable to add " "plugin {}.".format(attr, plugin_name)) setattr(self.bench, attr, plugin_instance.get_bench_api().get(attr))
python
def _register_bench_extension(self, plugin_name, plugin_instance): """ Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing """ for attr in plugin_instance.get_bench_api().keys(): if hasattr(self.bench, attr): raise PluginException("Attribute {} already exists in bench! Unable to add " "plugin {}.".format(attr, plugin_name)) setattr(self.bench, attr, plugin_instance.get_bench_api().get(attr))
[ "def", "_register_bench_extension", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "attr", "in", "plugin_instance", ".", "get_bench_api", "(", ")", ".", "keys", "(", ")", ":", "if", "hasattr", "(", "self", ".", "bench", ",", "att...
Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing
[ "Register", "a", "bench", "extension", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L239-L251
train
25,724
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_dataparser
def _register_dataparser(self, plugin_name, plugin_instance): """ Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing """ for parser in plugin_instance.get_parsers().keys(): if self.responseparser.has_parser(parser): raise PluginException("Parser {} already registered to parsers! Unable to " "add parsers from {}.".format(parser, plugin_name)) self.responseparser.add_parser(parser, plugin_instance.get_parsers().get(parser))
python
def _register_dataparser(self, plugin_name, plugin_instance): """ Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing """ for parser in plugin_instance.get_parsers().keys(): if self.responseparser.has_parser(parser): raise PluginException("Parser {} already registered to parsers! Unable to " "add parsers from {}.".format(parser, plugin_name)) self.responseparser.add_parser(parser, plugin_instance.get_parsers().get(parser))
[ "def", "_register_dataparser", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "parser", "in", "plugin_instance", ".", "get_parsers", "(", ")", ".", "keys", "(", ")", ":", "if", "self", ".", "responseparser", ".", "has_parser", "(",...
Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing
[ "Register", "a", "parser", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L253-L265
train
25,725
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_external_service
def _register_external_service(self, plugin_name, plugin_instance): """ Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return: """ for attr in plugin_instance.get_external_services().keys(): if attr in self._external_services: raise PluginException("External service with name {} already exists! Unable to add " "services from plugin {}.".format(attr, plugin_name)) self._external_services[attr] = plugin_instance.get_external_services().get(attr)
python
def _register_external_service(self, plugin_name, plugin_instance): """ Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return: """ for attr in plugin_instance.get_external_services().keys(): if attr in self._external_services: raise PluginException("External service with name {} already exists! Unable to add " "services from plugin {}.".format(attr, plugin_name)) self._external_services[attr] = plugin_instance.get_external_services().get(attr)
[ "def", "_register_external_service", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "attr", "in", "plugin_instance", ".", "get_external_services", "(", ")", ".", "keys", "(", ")", ":", "if", "attr", "in", "self", ".", "_external_serv...
Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return:
[ "Register", "an", "external", "service", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L267-L279
train
25,726
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_allocator
def _register_allocator(self, plugin_name, plugin_instance): """ Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return: """ for allocator in plugin_instance.get_allocators().keys(): if allocator in self._allocators: raise PluginException("Allocator with name {} already exists! unable to add " "allocators from plugin {}".format(allocator, plugin_name)) self._allocators[allocator] = plugin_instance.get_allocators().get(allocator)
python
def _register_allocator(self, plugin_name, plugin_instance): """ Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return: """ for allocator in plugin_instance.get_allocators().keys(): if allocator in self._allocators: raise PluginException("Allocator with name {} already exists! unable to add " "allocators from plugin {}".format(allocator, plugin_name)) self._allocators[allocator] = plugin_instance.get_allocators().get(allocator)
[ "def", "_register_allocator", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "allocator", "in", "plugin_instance", ".", "get_allocators", "(", ")", ".", "keys", "(", ")", ":", "if", "allocator", "in", "self", ".", "_allocators", ":...
Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return:
[ "Register", "an", "allocator", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L281-L293
train
25,727
ARMmbed/icetea
examples/sample_cloud.py
create
def create(host, port, result_converter=None, testcase_converter=None, args=None): """ Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise. """ return SampleClient(host, port, result_converter, testcase_converter, args)
python
def create(host, port, result_converter=None, testcase_converter=None, args=None): """ Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise. """ return SampleClient(host, port, result_converter, testcase_converter, args)
[ "def", "create", "(", "host", ",", "port", ",", "result_converter", "=", "None", ",", "testcase_converter", "=", "None", ",", "args", "=", "None", ")", ":", "return", "SampleClient", "(", "host", ",", "port", ",", "result_converter", ",", "testcase_converter...
Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise.
[ "Function", "which", "is", "called", "by", "Icetea", "to", "create", "an", "instance", "of", "the", "cloud", "client", ".", "This", "function", "must", "exists", ".", "This", "function", "myust", "not", "return", "None", ".", "Either", "return", "an", "ins...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/examples/sample_cloud.py#L24-L30
train
25,728
ARMmbed/icetea
examples/sample_cloud.py
SampleClient.send_results
def send_results(self, result): """ Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns new result entry as a dictionary or None. """ if self.result_converter: print(self.result_converter(result)) else: print(result)
python
def send_results(self, result): """ Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns new result entry as a dictionary or None. """ if self.result_converter: print(self.result_converter(result)) else: print(result)
[ "def", "send_results", "(", "self", ",", "result", ")", ":", "if", "self", ".", "result_converter", ":", "print", "(", "self", ".", "result_converter", "(", "result", ")", ")", "else", ":", "print", "(", "result", ")" ]
Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns new result entry as a dictionary or None.
[ "Upload", "a", "result", "object", "to", "server", ".", "If", "resultConverter", "has", "been", "provided", "use", "it", "to", "convert", "result", "object", "to", "format", "accepted", "by", "the", "server", ".", "If", "needed", "use", "testcase_converter", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/examples/sample_cloud.py#L93-L105
train
25,729
ARMmbed/icetea
icetea_lib/Plugin/plugins/HttpApi.py
HttpApiPlugin.get_tc_api
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception. ''' if logger is None and self.logger: logger = self.logger return Api(host, headers, cert, logger)
python
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception. ''' if logger is None and self.logger: logger = self.logger return Api(host, headers, cert, logger)
[ "def", "get_tc_api", "(", "self", ",", "host", ",", "headers", "=", "None", ",", "cert", "=", "None", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "None", "and", "self", ".", "logger", ":", "logger", "=", "self", ".", "logger", "retu...
Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception.
[ "Gets", "HttpApi", "wrapped", "into", "a", "neat", "little", "package", "that", "raises", "TestStepFail", "if", "expected", "status", "code", "is", "not", "returned", "by", "the", "server", ".", "Default", "setting", "for", "expected", "status", "code", "is", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/HttpApi.py#L43-L53
train
25,730
ARMmbed/icetea
icetea_lib/Plugin/plugins/HttpApi.py
Api._raise_fail
def _raise_fail(self, response, expected): """ Raise a TestStepFail with neatly formatted error message """ try: if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, response.content)) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected)) except TestStepFail: raise except: # pylint: disable=bare-except if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, "Unable to parse payload")) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
python
def _raise_fail(self, response, expected): """ Raise a TestStepFail with neatly formatted error message """ try: if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, response.content)) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected)) except TestStepFail: raise except: # pylint: disable=bare-except if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, "Unable to parse payload")) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
[ "def", "_raise_fail", "(", "self", ",", "response", ",", "expected", ")", ":", "try", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "error", "(", "\"Status code \"", "\"{} != {}. \\n\\n \"", "\"Payload: {}\"", ".", "format", "(", "respon...
Raise a TestStepFail with neatly formatted error message
[ "Raise", "a", "TestStepFail", "with", "neatly", "formatted", "error", "message" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/HttpApi.py#L63-L84
train
25,731
ARMmbed/icetea
icetea_lib/Reports/ReportJunit.py
ReportJunit.generate
def generate(self, *args, **kwargs): """ Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing """ xmlstr = str(self) filename = args[0] with open(filename, 'w') as fil: fil.write(xmlstr) with open(self.get_latest_filename('junit.xml'), "w") as latest_report: latest_report.write(xmlstr)
python
def generate(self, *args, **kwargs): """ Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing """ xmlstr = str(self) filename = args[0] with open(filename, 'w') as fil: fil.write(xmlstr) with open(self.get_latest_filename('junit.xml'), "w") as latest_report: latest_report.write(xmlstr)
[ "def", "generate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xmlstr", "=", "str", "(", "self", ")", "filename", "=", "args", "[", "0", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fil", ":", "fil", ".",...
Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing
[ "Implementation", "for", "generate", "method", "from", "ReportBase", ".", "Generates", "the", "xml", "and", "saves", "the", "report", "in", "Junit", "xml", "format", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportJunit.py#L71-L86
train
25,732
ARMmbed/icetea
icetea_lib/Reports/ReportJunit.py
ReportJunit.__generate
def __generate(results): """ Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. """ doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 fails = 0 errors = 0 skips = 0 for result in results: # Loop through all results and count the ones that were not later retried. if result.passed() is False: if result.retries_left > 0: # This will appear in the list again, move on continue count += 1 if result.passed(): # Passed, no need to increment anything else continue elif result.skipped(): skips += 1 elif result.was_inconclusive(): errors += 1 else: fails += 1 with tag('testsuite', tests=str(count), failures=str(fails), errors=str(errors), skipped=str(skips)): for result in results: if result.passed() is False and result.retries_left > 0: continue class_name = result.get_tc_name() models = result.get_dut_models() if models: class_name = class_name + "." + models name = result.get_toolchain() with tag('testcase', classname=class_name, name=name, time=result.get_duration(seconds=True)): if result.stdout: with tag('system-out'): text(result.stdout) if result.passed(): continue elif result.skipped(): with tag('skipped'): text(result.skip_reason) elif result.was_inconclusive(): with tag('error', message=hex_escape_str(result.fail_reason)): text(result.stderr) else: with tag('failure', message=hex_escape_str(result.fail_reason)): text(result.stderr) return indent( doc.getvalue(), indentation=' '*4 )
python
def __generate(results): """ Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. """ doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 fails = 0 errors = 0 skips = 0 for result in results: # Loop through all results and count the ones that were not later retried. if result.passed() is False: if result.retries_left > 0: # This will appear in the list again, move on continue count += 1 if result.passed(): # Passed, no need to increment anything else continue elif result.skipped(): skips += 1 elif result.was_inconclusive(): errors += 1 else: fails += 1 with tag('testsuite', tests=str(count), failures=str(fails), errors=str(errors), skipped=str(skips)): for result in results: if result.passed() is False and result.retries_left > 0: continue class_name = result.get_tc_name() models = result.get_dut_models() if models: class_name = class_name + "." + models name = result.get_toolchain() with tag('testcase', classname=class_name, name=name, time=result.get_duration(seconds=True)): if result.stdout: with tag('system-out'): text(result.stdout) if result.passed(): continue elif result.skipped(): with tag('skipped'): text(result.skip_reason) elif result.was_inconclusive(): with tag('error', message=hex_escape_str(result.fail_reason)): text(result.stderr) else: with tag('failure', message=hex_escape_str(result.fail_reason)): text(result.stderr) return indent( doc.getvalue(), indentation=' '*4 )
[ "def", "__generate", "(", "results", ")", ":", "doc", ",", "tag", ",", "text", "=", "Doc", "(", ")", ".", "tagtext", "(", ")", "# Counters for testsuite tag info", "count", "=", "0", "fails", "=", "0", "errors", "=", "0", "skips", "=", "0", "for", "r...
Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string.
[ "Static", "method", "which", "generates", "the", "Junit", "xml", "string", "from", "results" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportJunit.py#L106-L170
train
25,733
ARMmbed/icetea
icetea_lib/AllocationContext.py
AllocationContextList.open_dut_connections
def open_dut_connections(self): """ Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection. """ for dut in self.duts: try: dut.start_dut_thread() if hasattr(dut, "command"): dut.open_dut(dut.command) else: dut.open_dut() except DutConnectionError: self.logger.exception("Failed when opening dut connection") dut.close_dut(False) dut.close_connection() dut = None raise
python
def open_dut_connections(self): """ Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection. """ for dut in self.duts: try: dut.start_dut_thread() if hasattr(dut, "command"): dut.open_dut(dut.command) else: dut.open_dut() except DutConnectionError: self.logger.exception("Failed when opening dut connection") dut.close_dut(False) dut.close_connection() dut = None raise
[ "def", "open_dut_connections", "(", "self", ")", ":", "for", "dut", "in", "self", ".", "duts", ":", "try", ":", "dut", ".", "start_dut_thread", "(", ")", "if", "hasattr", "(", "dut", ",", "\"command\"", ")", ":", "dut", ".", "open_dut", "(", "dut", "...
Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection.
[ "Opens", "connections", "to", "Duts", ".", "Starts", "Dut", "read", "threads", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/AllocationContext.py#L352-L371
train
25,734
ARMmbed/icetea
icetea_lib/AllocationContext.py
AllocationContextList.check_flashing_need
def check_flashing_need(self, execution_type, build_id, force): """ Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean """ binary_file_name = AllocationContextList.get_build(build_id) if binary_file_name: if execution_type == 'hardware' and os.path.isfile(binary_file_name): if not force: #@todo: Make a better check for binary compatibility extension_split = os.path.splitext(binary_file_name) extension = extension_split[-1].lower() if extension != '.bin' and extension != '.hex': self.logger.debug("File ('%s') is not supported to flash, skip it" %( build_id)) return False return True return True else: raise ResourceInitError("Given binary %s does not exist" % build_id) else: raise ResourceInitError("Given binary %s does not exist" % build_id)
python
def check_flashing_need(self, execution_type, build_id, force): """ Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean """ binary_file_name = AllocationContextList.get_build(build_id) if binary_file_name: if execution_type == 'hardware' and os.path.isfile(binary_file_name): if not force: #@todo: Make a better check for binary compatibility extension_split = os.path.splitext(binary_file_name) extension = extension_split[-1].lower() if extension != '.bin' and extension != '.hex': self.logger.debug("File ('%s') is not supported to flash, skip it" %( build_id)) return False return True return True else: raise ResourceInitError("Given binary %s does not exist" % build_id) else: raise ResourceInitError("Given binary %s does not exist" % build_id)
[ "def", "check_flashing_need", "(", "self", ",", "execution_type", ",", "build_id", ",", "force", ")", ":", "binary_file_name", "=", "AllocationContextList", ".", "get_build", "(", "build_id", ")", "if", "binary_file_name", ":", "if", "execution_type", "==", "'hard...
Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean
[ "Check", "if", "flashing", "of", "local", "device", "is", "required", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/AllocationContext.py#L373-L398
train
25,735
ARMmbed/icetea
icetea_lib/LogManager.py
remove_handlers
def remove_handlers(logger): # TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below # required as a workaround """ Remove handlers from logger. :param logger: Logger whose handlers to remove """ if hasattr(logger, "handlers"): for handler in logger.handlers[::-1]: try: if isinstance(handler, logging.FileHandler): handler.close() logger.removeHandler(handler) except: # pylint: disable=bare-except import traceback traceback.print_exc() break
python
def remove_handlers(logger): # TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below # required as a workaround """ Remove handlers from logger. :param logger: Logger whose handlers to remove """ if hasattr(logger, "handlers"): for handler in logger.handlers[::-1]: try: if isinstance(handler, logging.FileHandler): handler.close() logger.removeHandler(handler) except: # pylint: disable=bare-except import traceback traceback.print_exc() break
[ "def", "remove_handlers", "(", "logger", ")", ":", "# TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below", "# required as a workaround", "if", "hasattr", "(", "logger", ",", "\"handlers\"", ")", ":", "for", "handler", "in", "logger", "...
Remove handlers from logger. :param logger: Logger whose handlers to remove
[ "Remove", "handlers", "from", "logger", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L184-L201
train
25,736
ARMmbed/icetea
icetea_lib/LogManager.py
get_base_logfilename
def get_base_logfilename(logname): """ Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log") """ logdir = get_base_dir() fname = os.path.join(logdir, logname) GLOBAL_LOGFILES.append(fname) return fname
python
def get_base_logfilename(logname): """ Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log") """ logdir = get_base_dir() fname = os.path.join(logdir, logname) GLOBAL_LOGFILES.append(fname) return fname
[ "def", "get_base_logfilename", "(", "logname", ")", ":", "logdir", "=", "get_base_dir", "(", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "logdir", ",", "logname", ")", "GLOBAL_LOGFILES", ".", "append", "(", "fname", ")", "return", "fname" ]
Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log")
[ "Return", "filename", "for", "a", "logfile", "filename", "will", "contain", "the", "actual", "path", "+", "filename" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L236-L246
train
25,737
ARMmbed/icetea
icetea_lib/LogManager.py
get_file_logger
def get_file_logger(name, formatter=None): """ Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: Formatter to use """ if name is None or name == "": raise ValueError("Can't make a logger without name") logger = logging.getLogger(name) remove_handlers(logger) logger.setLevel(logging.INFO) if formatter is None: config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) formatter = BenchFormatter(config.get("level", "DEBUG"), config.get("dateformat")) func = get_testcase_logfilename(name + ".log") handler = _get_filehandler_with_formatter(func, formatter) logger.addHandler(handler) return logger
python
def get_file_logger(name, formatter=None): """ Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: Formatter to use """ if name is None or name == "": raise ValueError("Can't make a logger without name") logger = logging.getLogger(name) remove_handlers(logger) logger.setLevel(logging.INFO) if formatter is None: config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) formatter = BenchFormatter(config.get("level", "DEBUG"), config.get("dateformat")) func = get_testcase_logfilename(name + ".log") handler = _get_filehandler_with_formatter(func, formatter) logger.addHandler(handler) return logger
[ "def", "get_file_logger", "(", "name", ",", "formatter", "=", "None", ")", ":", "if", "name", "is", "None", "or", "name", "==", "\"\"", ":", "raise", "ValueError", "(", "\"Can't make a logger without name\"", ")", "logger", "=", "logging", ".", "getLogger", ...
Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: Formatter to use
[ "Return", "a", "file", "logger", "that", "will", "log", "into", "a", "file", "located", "in", "the", "testcase", "log", "directory", ".", "Anything", "logged", "with", "a", "file", "logger", "won", "t", "be", "visible", "in", "the", "console", "or", "any...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L256-L278
train
25,738
ARMmbed/icetea
icetea_lib/LogManager.py
_check_existing_logger
def _check_existing_logger(loggername, short_name): """ Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None """ if loggername in LOGGERS: # Check if short_name matches the existing one, if not update it if isinstance(LOGGERS[loggername], BenchLoggerAdapter): if ("source" not in LOGGERS[loggername].extra or LOGGERS[loggername].extra["source"] != short_name): LOGGERS[loggername].extra["source"] = short_name return LOGGERS[loggername] return None
python
def _check_existing_logger(loggername, short_name): """ Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None """ if loggername in LOGGERS: # Check if short_name matches the existing one, if not update it if isinstance(LOGGERS[loggername], BenchLoggerAdapter): if ("source" not in LOGGERS[loggername].extra or LOGGERS[loggername].extra["source"] != short_name): LOGGERS[loggername].extra["source"] = short_name return LOGGERS[loggername] return None
[ "def", "_check_existing_logger", "(", "loggername", ",", "short_name", ")", ":", "if", "loggername", "in", "LOGGERS", ":", "# Check if short_name matches the existing one, if not update it", "if", "isinstance", "(", "LOGGERS", "[", "loggername", "]", ",", "BenchLoggerAdap...
Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None
[ "Check", "if", "logger", "with", "name", "loggername", "exists", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L281-L296
train
25,739
ARMmbed/icetea
icetea_lib/LogManager.py
_add_filehandler
def _add_filehandler(logger, logpath, formatter=None, name="Bench"): """ Adds a FileHandler to logger. :param logger: Logger. :param logpath: Path to file. :param formatter: Formatter to be used :param name: Name for logger :return: Logger """ formatter = formatter if formatter else BenchFormatterWithType(loggername=name) handler = _get_filehandler_with_formatter(logpath, formatter) config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) handler.setLevel(getattr(logging, config.get("level", "DEBUG"))) logger.addHandler(handler) return logger
python
def _add_filehandler(logger, logpath, formatter=None, name="Bench"): """ Adds a FileHandler to logger. :param logger: Logger. :param logpath: Path to file. :param formatter: Formatter to be used :param name: Name for logger :return: Logger """ formatter = formatter if formatter else BenchFormatterWithType(loggername=name) handler = _get_filehandler_with_formatter(logpath, formatter) config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) handler.setLevel(getattr(logging, config.get("level", "DEBUG"))) logger.addHandler(handler) return logger
[ "def", "_add_filehandler", "(", "logger", ",", "logpath", ",", "formatter", "=", "None", ",", "name", "=", "\"Bench\"", ")", ":", "formatter", "=", "formatter", "if", "formatter", "else", "BenchFormatterWithType", "(", "loggername", "=", "name", ")", "handler"...
Adds a FileHandler to logger. :param logger: Logger. :param logpath: Path to file. :param formatter: Formatter to be used :param name: Name for logger :return: Logger
[ "Adds", "a", "FileHandler", "to", "logger", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L299-L314
train
25,740
ARMmbed/icetea
icetea_lib/LogManager.py
_get_basic_logger
def _get_basic_logger(loggername, log_to_file, logpath): """ Get a logger with our basic configuration done. :param loggername: Name of logger. :param log_to_file: Boolean, True if this logger should write a file. :return: Logger """ logger = logging.getLogger(loggername) logger.propagate = False remove_handlers(logger) logger.setLevel(logging.DEBUG) logger_config = LOGGING_CONFIG.get(loggername, DEFAULT_LOGGING_CONFIG) if TRUNCATE_LOG or logger_config.get("truncate_logs").get("truncate"): cfilter = ContextFilter() trunc_logs = logger_config.get("truncate_logs") # pylint: disable=invalid-name cfilter.MAXIMUM_LENGTH = trunc_logs.get("max_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("max_len")) cfilter.REVEAL_LENGTH = trunc_logs.get("reveal_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("reveal_len")) logger.addFilter(cfilter) # Filehandler for logger if log_to_file: _add_filehandler(logger, logpath, name=loggername) return logger
python
def _get_basic_logger(loggername, log_to_file, logpath): """ Get a logger with our basic configuration done. :param loggername: Name of logger. :param log_to_file: Boolean, True if this logger should write a file. :return: Logger """ logger = logging.getLogger(loggername) logger.propagate = False remove_handlers(logger) logger.setLevel(logging.DEBUG) logger_config = LOGGING_CONFIG.get(loggername, DEFAULT_LOGGING_CONFIG) if TRUNCATE_LOG or logger_config.get("truncate_logs").get("truncate"): cfilter = ContextFilter() trunc_logs = logger_config.get("truncate_logs") # pylint: disable=invalid-name cfilter.MAXIMUM_LENGTH = trunc_logs.get("max_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("max_len")) cfilter.REVEAL_LENGTH = trunc_logs.get("reveal_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("reveal_len")) logger.addFilter(cfilter) # Filehandler for logger if log_to_file: _add_filehandler(logger, logpath, name=loggername) return logger
[ "def", "_get_basic_logger", "(", "loggername", ",", "log_to_file", ",", "logpath", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "loggername", ")", "logger", ".", "propagate", "=", "False", "remove_handlers", "(", "logger", ")", "logger", ".", "...
Get a logger with our basic configuration done. :param loggername: Name of logger. :param log_to_file: Boolean, True if this logger should write a file. :return: Logger
[ "Get", "a", "logger", "with", "our", "basic", "configuration", "done", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L317-L346
train
25,741
ARMmbed/icetea
icetea_lib/LogManager.py
get_resourceprovider_logger
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): """ Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the 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 logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG) logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(loggername + ".log")) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL > 0 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.WARN) else: cbh.setLevel(getattr(logging, logger_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
python
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): """ Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the 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 logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG) logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(loggername + ".log")) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL > 0 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.WARN) else: cbh.setLevel(getattr(logging, logger_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
[ "def", "get_resourceprovider_logger", "(", "name", "=", "None", ",", "short_name", "=", "\" \"", ",", "log_to_file", "=", "True", ")", ":", "global", "LOGGERS", "loggername", "=", "name", "logger", "=", "_check_existing_logger", "(", "loggername", ",", "short_na...
Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger
[ "Get", "a", "logger", "for", "ResourceProvider", "and", "it", "s", "components", "such", "as", "Allocators", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L349-L379
train
25,742
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): """ 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]
[ "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
train
25,743
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): """ 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]
[ "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
train
25,744
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): """ 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
[ "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
train
25,745
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): """ 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
[ "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
train
25,746
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): """ Format record with formatter. :param record: Record to format :return: Formatted 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
train
25,747
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): """ 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)
[ "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
train
25,748
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): """ 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)
[ "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
train
25,749
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): """ 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)
[ "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
train
25,750
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): """ 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)
[ "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
train
25,751
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): """ 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))
[ "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
train
25,752
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): """ 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))
[ "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
train
25,753
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): """ 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)))
[ "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
train
25,754
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): """ 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)))
[ "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
train
25,755
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): """ 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")
[ "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
train
25,756
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): """ Get absolute path for filename. :param filename: file :return: path """ 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
train
25,757
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): """ 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 ''
[ "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
train
25,758
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): """ 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
[ "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
train
25,759
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(): """ 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
[ "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
train
25,760
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): """ 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
[ "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
train
25,761
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): """ 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
[ "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
train
25,762
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): """ 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
[ "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
train
25,763
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): """ 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
[ "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
train
25,764
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): """ 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
[ "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
train
25,765
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): """ 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
[ "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
train
25,766
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): """ 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
[ "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
train
25,767
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): """ 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
[ "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
train
25,768
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): """ 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")
[ "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
train
25,769
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): """ 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
[ "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
train
25,770
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): """ 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)
[ "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
train
25,771
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): """ 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
[ "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
train
25,772
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): """ 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))
[ "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
train
25,773
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 """ Write data to process. :param data: data to write :param crlf: line end character :return: Nothing """ 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
train
25,774
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): """ 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)
[ "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
train
25,775
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): """ 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
[ "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
train
25,776
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): """ 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
[ "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
train
25,777
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): """ 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
[ "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
train
25,778
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): """ 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
[ "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
train
25,779
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): """ Set gdbs use for process. :param gdbs: Boolean, default is True :param port: Port number for gdbserver """ 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
train
25,780
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): """ 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)
[ "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
train
25,781
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): """ 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
[ "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
train
25,782
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"): """ 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()
[ "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
train
25,783
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): """ 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"])
[ "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
train
25,784
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): """! 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
[ "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
train
25,785
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): """ 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
[ "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
train
25,786
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): """ 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
[ "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
train
25,787
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): """ 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
[ "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
train
25,788
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): """ 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
[ "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
train
25,789
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(): """ 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)
[ "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
train
25,790
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"): """ 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
[ "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
train
25,791
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): """ 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")
[ "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
train
25,792
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): """ 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
[ "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
train
25,793
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"): """ 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)
[ "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
train
25,794
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): """ 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
[ "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
train
25,795
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(): """ 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
[ "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
train
25,796
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): """ 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
[ "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
train
25,797
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): """ 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.")
[ "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
train
25,798
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): """ 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
[ "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
train
25,799