patchtest: cleanups and fixes, part 1
v2 cover patchtest: cleanups and fixes, part 1
This is the first split of patches coming from a previous series[1] I submitted. Compared to that version, the changes here are refactors limited to the core scripts/patchtest script itself, and do the following:
- Make sure that the user has enabled the meta-selftest layer before running patchtest, as otherwise selftest results can be misleading
- Avoid duplicating code for test results generation
- Remove excess whitespace, unused variables, redundant function calls, and unreachable code
Note that this was driven partially by Claude Code (Sonnet 4.6 and 4.7), but I've gone back and reworked some of its changes before submission.
Selftests look OK after these changes:
|============================================================================ |Testsuite summary for patchtest |============================================================================ |# TOTAL: 38 |# XPASS: 18 |# XFAIL: 18 |# XSKIP: 2 |# PASS: 0 |# FAIL: 0 |# SKIP: 0 |# ERROR: 0 |============================================================================
[1]: https://lists.openembedded.org/g/openembedded-core/message/237047
Trevor Gamblin (7):
scripts/patchtest: refactor results methods scripts/patchtest: clean up startTestRun() scripts/patchtest: simplify _runner() scripts/patchtest: simplify traceback logging, remove whitespace scripts/patchtest: simplify run()
scripts/patchtest: clean up main()
scripts/patchtest: check for meta-selftest
scripts/patchtest | 147 ++++++++++++++++++++-------------------------- 1 file changed, 65 insertions(+), 82 deletions(-)
Signature · 1 line
2.54.0
PATCH v2 1/7 scripts/patchtest: refactor results methods
The add{Error,Failure,Success,Skip} methods used by the inner PatchTestResult class re-use a lot of nearly-identical code. Encapsulate the logic used into two new functions:
1. _format_test_description(), which includes all of the original syntax/tag cleanup logic
2. _write_patchtest_result(), which formats the actual result lines that patchtest ultimately emits (to console and/or file)
selftest:
|============================================================================ |Testsuite summary for patchtest |============================================================================ |# TOTAL: 38 |# XPASS: 18 |# XFAIL: 18 |# XSKIP: 2 |# PASS: 0 |# FAIL: 0 |# SKIP: 0 |# ERROR: 0 |============================================================================
--- scripts/patchtest | 56 ++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 32 deletions(-)
scripts/patchtest +24 -32
@@ -33,6 +33,22 @@ logger.setLevel(logging.INFO) info = logger.info error = logger.error +def _format_test_description(test): + return (test.id().split('.')[-1] + .replace('_', ' ') + .replace("cve", "CVE") + .replace("signed off by", "Signed-off-by") + .replace("upstream status", "Upstream-Status") + .replace("non auh", "non-AUH") + .replace("presence format", "presence")) + + +def _write_patchtest_result(line, logfile=None): + print(line) + if logfile: + with open(logfile, "a") as f: + f.write(line + "\n") + def getResult(patch, mergepatch, logfile=None): class PatchTestResult(unittest.TextTestResult):
@@ -74,43 +90,19 @@ def getResult(patch, mergepatch, logfile=None): logger.error(traceback.print_exc()) def addFailure(self, test, err): - test_description = test.id().split('.')[-1].replace('_', ' ').replace("cve", "CVE").replace("signed off by", - "Signed-off-by").replace("upstream status", - "Upstream-Status").replace("non auh", - "non-AUH").replace("presence format", "presence") self.test_failure = True - fail_str = '{}: {}: {} ({})'.format(self.fail, - test_description, json.loads(str(err[1]))["issue"], - test.id()) - print(fail_str) - if logfile: - with open(logfile, "a") as f: - f.write(fail_str + "\n") + desc = _format_test_description(test) + issue = json.loads(str(err[1]))["issue"] + _write_patchtest_result('{}: {}: {} ({})'.format(self.fail, desc, issue, test.id()), logfile) def addSuccess(self, test): - test_description = test.id().split('.')[-1].replace('_', ' ').replace("cve", "CVE").replace("signed off by", - "Signed-off-by").replace("upstream status", - "Upstream-Status").replace("non auh", - "non-AUH").replace("presence format", "presence") - success_str = '{}: {} ({})'.format(self.success, - test_description, test.id()) - print(success_str) - if logfile: - with open(logfile, "a") as f: - f.write(success_str + "\n") + desc = _format_test_description(test) + _write_patchtest_result('{}: {} ({})'.format(self.success, desc, test.id()), logfile) def addSkip(self, test, reason): - test_description = test.id().split('.')[-1].replace('_', ' ').replace("cve", "CVE").replace("signed off by", - "Signed-off-by").replace("upstream status", - "Upstream-Status").replace("non auh", - "non-AUH").replace("presence format", "presence") - skip_str = '{}: {}: {} ({})'.format(self.skip, - test_description, json.loads(str(reason))["issue"], - test.id()) - print(skip_str) - if logfile: - with open(logfile, "a") as f: - f.write(skip_str + "\n") + desc = _format_test_description(test) + issue = json.loads(str(reason))["issue"] + _write_patchtest_result('{}: {}: {} ({})'.format(self.skip, desc, issue, test.id()), logfile) def stopTestRun(self):
Signature · 1 line
2.54.0
PATCH v2 2/7 scripts/patchtest: clean up startTestRun()
In reply to Trevor Gamblin- Initialize self.repo directly instead of in two steps
- Remove extra whitespace when setting error and failure members
--- scripts/patchtest | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-)
scripts/patchtest +9 -12
@@ -61,20 +61,17 @@ def getResult(patch, mergepatch, logfile=None): skip = 'SKIP' def startTestRun(self): - # let's create the repo already, it can be used later on - repoargs = { - "repodir": PatchtestParser.repodir, - "commit": PatchtestParser.basecommit, - "branch": PatchtestParser.basebranch, - "patch": patch, - } - - self.repo_error = False - self.test_error = False - self.test_failure = False + self.repo_error = False + self.test_error = False + self.test_failure = False try: - self.repo = PatchtestParser.repo = PatchTestRepo(**repoargs) + self.repo = PatchtestParser.repo = PatchTestRepo( + patch=patch, + repodir=PatchtestParser.repodir, + commit=PatchtestParser.basecommit, + branch=PatchtestParser.basebranch, + ) except: logger.error(traceback.print_exc()) self.repo_error = True
Signature · 1 line
2.54.0
PATCH v2 3/7 scripts/patchtest: simplify _runner()
In reply to Trevor Gamblin- Use the test suite's countTestCases() method directly instead of creating a variable
- Simplify return logic - we still want to fail early if there are no test suites to use, but otherwise we can reduce it to a single return value determination based on the result of runner.run()
- Add a newline above where the 'runner' variable is initialized
--- scripts/patchtest | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-)
scripts/patchtest +3 -6
@@ -123,11 +123,11 @@ def _runner(resultklass, prefix=None): pattern=PatchtestParser.pattern, top_level_dir=PatchtestParser.topdir, ) - ntc = suite.countTestCases() # if there are no test cases, just quit - if not ntc: + if not suite.countTestCases(): return 2 + runner = unittest.TextTestRunner(resultclass=resultklass, verbosity=0) try:
@@ -135,11 +135,8 @@ def _runner(resultklass, prefix=None): except: logger.error(traceback.print_exc()) logger.error('patchtest: something went wrong') - return 1 - if result.test_failure or result.test_error: - return 1 - return 0 + return 1 if (result.test_failure or result.test_error) else 0 def run(patch, logfile=None): """ Load, setup and run pre and post-merge tests """
Signature · 1 line
2.54.0
PATCH v2 4/7 scripts/patchtest: simplify traceback logging, remove whitespace
In reply to Trevor GamblinWe currently use the logging module to wrap tracebacks when a failure occurs. The traceback module is sufficient for this task, so use it directly. Also remove a redundant import of the traceback module, and fix some whitespace in the getResult class that was missed previously.
--- scripts/patchtest | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-)
scripts/patchtest +6 -9
@@ -30,8 +30,6 @@ loggerhandler = logging.StreamHandler() loggerhandler.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(loggerhandler) logger.setLevel(logging.INFO) -info = logger.info -error = logger.error def _format_test_description(test): return (test.id().split('.')[-1]
@@ -56,9 +54,9 @@ def getResult(patch, mergepatch, logfile=None): shouldStop = True longMessage = False - success = 'PASS' - fail = 'FAIL' - skip = 'SKIP' + success = 'PASS' + fail = 'FAIL' + skip = 'SKIP' def startTestRun(self): self.repo_error = False
@@ -84,7 +82,7 @@ def getResult(patch, mergepatch, logfile=None): def addError(self, test, err): self.test_error = True (ty, va, trace) = err - logger.error(traceback.print_exc()) + traceback.print_exc() def addFailure(self, test, err): self.test_failure = True
@@ -132,8 +130,8 @@ def _runner(resultklass, prefix=None): try: result = runner.run(suite) - except: - logger.error(traceback.print_exc()) + except Exception: + traceback.print_exc() logger.error('patchtest: something went wrong') return 1 if (result.test_failure or result.test_error) else 0
@@ -227,7 +225,6 @@ if __name__ == '__main__': try: ret = main() except Exception: - import traceback traceback.print_exc(5) sys.exit(ret)
Signature · 1 line
2.54.0
PATCH v2 5/7 scripts/patchtest: simplify run()
In reply to Trevor GamblinSet premerge_result and postmerge_result directly by calling getResult(), instead of doing it in multiple stages with confusing variable names.
--- scripts/patchtest | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-)
scripts/patchtest +2 -7
@@ -141,13 +141,8 @@ def run(patch, logfile=None): # Get the result class and install the control-c handler unittest.installHandler() - # run pre-merge tests, meaning those methods with 'pretest' as prefix - premerge_resultklass = getResult(patch, False, logfile) - premerge_result = _runner(premerge_resultklass, 'pretest') - - # run post-merge tests, meaning those methods with 'test' as prefix - postmerge_resultklass = getResult(patch, True, logfile) - postmerge_result = _runner(postmerge_resultklass, 'test') + premerge_result = _runner(getResult(patch, False, logfile), 'pretest') + postmerge_result = _runner(getResult(patch, True, logfile), 'test') print_result_message(premerge_result, postmerge_result) return premerge_result or postmerge_result
Signature · 1 line
2.54.0
PATCH v2 6/7 scripts/patchtest: clean up main()
In reply to Trevor Gamblin- Reference PatchtestParser members directly instead of setting local variables
- Remove unused variables
- Declare 'ret' just before where it gets used
- Use subprocess.run() instead of os.popen() for a cleaner 'git status' call
- Remove unnecessary square brackets in the status_matches if block
- Remove unneeded try-finally block
--- scripts/patchtest | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-)
scripts/patchtest +10 -16
@@ -12,6 +12,7 @@ import json import logging import os +import subprocess import sys import traceback import unittest
@@ -162,16 +163,14 @@ def print_result_message(preresult, postresult): print("----------------------------------------------------------------------\n") def main(): - ret = 0 - tmp_patch = False patch_path = PatchtestParser.patch_path - log_results = PatchtestParser.log_results - log_path = None - patch_list = None - git_status = os.popen("(cd %s && git status)" % PatchtestParser.repodir).read() + git_status = subprocess.run( + ['git', '-C', PatchtestParser.repodir, 'status'], + capture_output=True, text=True, + ).stdout status_matches = ["Changes not staged for commit", "Changes to be committed"] - if any([match in git_status for match in status_matches]): + if any(match in git_status for match in status_matches): logger.error("patchtest: there are uncommitted changes in the target repo that would be overwritten. Please commit or restore them before running patchtest") return 1
@@ -180,6 +179,7 @@ def main(): else: patch_list = [patch_path] + ret = 0 for patch in patch_list: if os.path.getsize(patch) == 0: logger.error('patchtest: patch is empty')
@@ -187,19 +187,13 @@ def main(): logger.info('Testing patch %s' % patch) - if log_results: + log_path = None + if PatchtestParser.log_results: log_path = patch + ".testresult" with open(log_path, "a") as f: f.write("Patchtest results for patch '%s':\n\n" % patch) - try: - if log_path: - ret = run(patch, log_path) - else: - ret = run(patch) - finally: - if tmp_patch: - os.remove(patch) + ret = run(patch, log_path) return ret
Signature · 1 line
2.54.0
PATCH v2 7/7 scripts/patchtest: check for meta-selftest
In reply to Trevor GamblinThe patchtest suite (in particular, the selftests) makes use of the meta-selftest layer for full operation. Make sure that the layer is added to bblayers.conf before kicking off any test runs.
--- scripts/patchtest | 11 +++++++++++ 1 file changed, 11 insertions(+)
scripts/patchtest +11 -0
@@ -174,6 +174,17 @@ def main(): logger.error("patchtest: there are uncommitted changes in the target repo that would be overwritten. Please commit or restore them before running patchtest") return 1 + builddir = os.environ.get('BUILDDIR') + if builddir: + bblayers_conf = os.path.join(builddir, 'conf', 'bblayers.conf') + if os.path.exists(bblayers_conf): + with open(bblayers_conf) as f: + if 'meta-selftest' not in f.read(): + logger.error( + "patchtest: meta-selftest layer not found in %s - add it to BBLAYERS before running patchtest" % bblayers_conf + ) + return 1 + if os.path.isdir(patch_path): patch_list = [os.path.join(patch_path, filename) for filename in sorted(os.listdir(patch_path))] else:
Signature · 1 line
2.54.0