Skip to contentSkip to conversation

prepare patchtest to be run with b4 prep --check

RFC PATCH New Quentin Schulz 1 participant 7 messages Feb 3, 2025

lore
Share & tools
lore
#0 lore raw

cover prepare patchtest to be run with b4 prep --check

Marked as RFC because the second to last patch is very ewww but I don't have a much better idea right now.

b4 prep --check can run an executable on each patch in a series, so it'd be nice to be able to use patchtest with that so that we don't duplicate tests run locally and those run on patches found on the ML by a bot.

b4 sends the patch to check over stdin, with the "From " field stripped
from the Mbox, c.f. https://git.kernel.org/pub/scm/utils/b4/b4.git/tree/src/b4/__init__.py?h=stable-0.14.y#n3494
This means we need to add to patchtest the ability to pass patches from
stdin and also tell it to ignore "malformed" Mboxes in some cases
(whenever the patch is passed via stdin for example).

b4 expects absolutely zero message on either stderr or stdout or it interprets those as error messages. patchtest is currently quite verbose, so we need to disable everything we can and only keep error messages.

This would be a first step for using patchtest with b4 prep --check, ideally we should also make it possible to use patchtest with other git repos, specifically poky for example. This would allow people to run tests for BitBake, OE-Core, Yocto-docs and poky source code. We're not there yet but this is a step in that direction.

One can now use patchtest as b4 prep --check step with the following .b4-config:

[b4]
prep-perpatch-check-cmd = patchtest --patch - --quiet --no-summary

oe-init-buildenv needs to be sourced first to make patchtest available in PATH and a few Python modules installed (e.g. unidiff, pylint, ...; see meta/lib/patchtest/requirements.txt).

This series depends on
https://lore.kernel.org/openembedded-core/[email protected]/T/#m24b6594da5d57d0715e16636ad2936b1478f08ae
except if the last patch in this series is removed (the modification of .b4-config).

---
Quentin Schulz (6):
patchtest: use logger instead of printing to stdout
patchtest: allow to pass patch from stdin
patchtest: allow to silence non-error messages
patchtest: allow to not print summary
patchtest: allow malformed Mbox
b4: enable patchtest as b4 prep --check step

 .b4-config                             |  3 +-
 meta/lib/patchtest/mbox.py             |  9 +++---
 meta/lib/patchtest/patchtest_parser.py |  8 +++++
 meta/lib/patchtest/repo.py             |  4 +--
 meta/lib/patchtest/tests/base.py       |  2 +-
 scripts/patchtest                      | 54 ++++++++++++++++++++++++----------
 6 files changed, 56 insertions(+), 24 deletions(-)

---
base-commit: ea18694110e68cdfd90984e0f7f2d4303fd12ff0
change-id: 20250203-b4-patchtest-86b35d7772ee

Best regards,

Signature · 1 line
Quentin Schulz <[email protected]>
#1 lore raw

RFC PATCH 1/6 patchtest: use logger instead of printing to stdout

From: Quentin Schulz <[email protected]>

This will allow use to specify which messages we want to see later on. This will be useful for using this script with b4 for example which expects output on stdout/stderr only when an error happened.

To that end, success string is set to the info level, warning string to warning level and error to error level.

The summary is printed with the appropriate log level, error if warnings or errors were found, info otherwise.

---
 scripts/patchtest | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)
scripts/patchtest +9 -5
index 9218db232a77516d2a8bdcd967521b884f0de89d..bcd48dbcc39573d7abd3247bc34cb9ac8a8a5c2e 100755
@@ -82,7 +82,7 @@ def getResult(patch, mergepatch, logfile=None):
             fail_str = '{}: {}: {} ({})'.format(self.fail,
             test_description, json.loads(str(err[1]))["issue"],
             test.id())
-            print(fail_str)
+            logger.error(fail_str)
             if logfile:
                 with open(logfile, "a") as f:
                     f.write(fail_str + "\n")
@@ -94,7 +94,7 @@ def getResult(patch, mergepatch, logfile=None):
             "non-AUH").replace("presence format", "presence")
             success_str = '{}: {} ({})'.format(self.success,
             test_description, test.id())
-            print(success_str)
+            logger.info(success_str)
             if logfile:
                 with open(logfile, "a") as f:
                     f.write(success_str + "\n")
@@ -107,7 +107,7 @@ def getResult(patch, mergepatch, logfile=None):
             skip_str = '{}: {}: {} ({})'.format(self.skip,
             test_description, json.loads(str(reason))["issue"],
             test.id())
-            print(skip_str)
+            logger.warning(skip_str)
             if logfile:
                 with open(logfile, "a") as f:
                     f.write(skip_str + "\n")
@@ -169,18 +169,22 @@ def run(patch, logfile=None):
     return premerge_result or postmerge_result
 
 def print_result_message(preresult, postresult):
-    print("----------------------------------------------------------------------\n")
     if preresult == 2 and postresult == 2:
+        logger.error("----------------------------------------------------------------------\n")
         logger.error(
             "patchtest: No test cases found - did you specify the correct suite directory?"
         )
+        logger.error("----------------------------------------------------------------------\n")
     if preresult == 1 or postresult == 1:
+        logger.error("----------------------------------------------------------------------\n")
         logger.error(
             "WARNING: patchtest: At least one patchtest caused a failure or an error - please check https://wiki.yoctoproject.org/wiki/Patchtest for further guidance"
         )
+        logger.error("----------------------------------------------------------------------\n")
     else:
+        logger.info("----------------------------------------------------------------------\n")
         logger.info("OK: patchtest: All patchtests passed")
-    print("----------------------------------------------------------------------\n")
+        logger.info("----------------------------------------------------------------------\n")
 
 def main():
     tmp_patch = False
Signature · 1 line
2.48.1
#2 lore raw

RFC PATCH 2/6 patchtest: allow to pass patch from stdin

In reply to Quentin Schulz

From: Quentin Schulz <[email protected]>

This allows to pass a patch via stdin to patchtest. This will be useful when using b4 with patchtest, with the former passing each patch to the latter via stdin.

---
 scripts/patchtest | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
scripts/patchtest +12 -3
index bcd48dbcc39573d7abd3247bc34cb9ac8a8a5c2e..66a9f6470ca860c2233fb9ace042edf4b4737c88 100755
@@ -205,11 +205,20 @@ def main():
         patch_list = [patch_path]
 
     for patch in patch_list:
-        if os.path.getsize(patch) == 0:
+        if patch == "-":
+            import tempfile
+
+            patch = tempfile.NamedTemporaryFile(delete=False)
+            patch.write(sys.stdin.buffer.read())
+            patch.flush()
+            logger.info('Testing patch from stdin')
+            tmp_patch = True
+            patch = patch.name
+        elif os.path.getsize(patch) == 0:
             logger.error('patchtest: patch is empty')
             return 1
-
-        logger.info('Testing patch %s' % patch)
+        else:
+            logger.info('Testing patch %s' % patch)
 
         if log_results:
             log_path = patch + ".testresult"
Signature · 1 line
2.48.1
#3 lore raw

RFC PATCH 3/6 patchtest: allow to silence non-error messages

In reply to Quentin Schulz

From: Quentin Schulz <[email protected]>

When passing --quiet to patchtest, TinFoil and Knotty will be silenced so almost nothing makes it to stdout/stderr if not required (e.g. an error happens).

patchtest configures its own logger to the ERROR level for the same effect.

---
 meta/lib/patchtest/patchtest_parser.py | 4 ++++
 meta/lib/patchtest/tests/base.py       | 2 +-
 scripts/patchtest                      | 4 +++-
 3 files changed, 8 insertions(+), 2 deletions(-)
meta/lib/patchtest/patchtest_parser.py +4 -0
index 2a11cb76c2364e768bdb4c1fc050c84221428a4a..66c54628466b0234f8492f0a7d8ddbe59f5f7582 100644
@@ -69,6 +69,10 @@ class PatchtestParser(object):
                             action='store_true',
                             help='Enable debug output')
 
+        parser.add_argument('--quiet', '-q',
+                            action='store_true',
+                            help='Only output error messages')
+
         parser.add_argument('--log-results', 
                             action='store_true', 
                             help='Enable logging to a file matching the target patch name with ".testresult" appended')
meta/lib/patchtest/tests/base.py +1 -1
index 919ca136bb469eee3e5af4b145e8293588728f84..7844e1c9e9f05e0a5c19eaaaa6a4267b10f96c0f 100644
@@ -170,7 +170,7 @@ class Metadata(Base):
                 return tinfoil
             os.chdir(builddir)
             tinfoil = bb.tinfoil.Tinfoil()
-            tinfoil.prepare(config_only=config_only)
+            tinfoil.prepare(config_only=config_only, quiet=2 if PatchtestParser.quiet else 0)
         except bb.tinfoil.TinfoilUIException as te:
             if tinfoil:
                 tinfoil.shutdown()
scripts/patchtest +3 -1
index 66a9f6470ca860c2233fb9ace042edf4b4737c88..6efd69465ef8d8dc6fa459d05220ccd08ca28536 100755
@@ -139,7 +139,7 @@ def _runner(resultklass, prefix=None):
     # if there are no test cases, just quit
     if not ntc:
         return 2
-    runner = unittest.TextTestRunner(resultclass=resultklass, verbosity=0)
+    runner = unittest.TextTestRunner(stream=open(os.devnull, 'w') if PatchtestParser.quiet else None, resultclass=resultklass, verbosity=0)
 
     try:
         result = runner.run(suite)
@@ -243,6 +243,8 @@ if __name__ == '__main__':
     # set debugging level
     if PatchtestParser.debug:
         logger.setLevel(logging.DEBUG)
+    if PatchtestParser.quiet:
+        logger.setLevel(logging.ERROR)
 
     # if topdir not define, default it to testdir
     if not PatchtestParser.topdir:
Signature · 1 line
2.48.1
#4 lore raw

RFC PATCH 4/6 patchtest: allow to not print summary

In reply to Quentin Schulz

From: Quentin Schulz <[email protected]>

The summary is printed even when quiet is passed if an error happens. However, in the case when only one patch is passed to patchtest, this summary isn't useful at all. That is the case for b4 with patchtest used for b4 prep --check, where patchtest will be executed on each patch individually so this summary will be redundant.

---
 meta/lib/patchtest/patchtest_parser.py | 4 ++++
 scripts/patchtest                      | 4 +++-
 2 files changed, 7 insertions(+), 1 deletion(-)
meta/lib/patchtest/patchtest_parser.py +4 -0
index 66c54628466b0234f8492f0a7d8ddbe59f5f7582..27ab1d464a58c5747f400921e8388029996d483b 100644
@@ -73,6 +73,10 @@ class PatchtestParser(object):
                             action='store_true',
                             help='Only output error messages')
 
+        parser.add_argument('--no-summary',
+                            action='store_true',
+                            help='Do not output summary of tests')
+
         parser.add_argument('--log-results', 
                             action='store_true', 
                             help='Enable logging to a file matching the target patch name with ".testresult" appended')
scripts/patchtest +3 -1
index 6efd69465ef8d8dc6fa459d05220ccd08ca28536..82ce665c1a5c950dfaf02cda9ed70b935a9bfe25 100755
@@ -165,7 +165,9 @@ def run(patch, logfile=None):
     postmerge_resultklass = getResult(patch, True, logfile)
     postmerge_result = _runner(postmerge_resultklass, 'test')
 
-    print_result_message(premerge_result, postmerge_result)
+    if not PatchtestParser.no_summary:
+        print_result_message(premerge_result, postmerge_result)
+
     return premerge_result or postmerge_result
 
 def print_result_message(preresult, postresult):
Signature · 1 line
2.48.1
#5 lore raw

RFC PATCH 5/6 patchtest: allow malformed Mbox

In reply to Quentin Schulz

From: Quentin Schulz <[email protected]>

b4 strips the "From " field from the Mbox before sending it to stdin for consumption, see
https://git.kernel.org/pub/scm/utils/b4/b4.git/tree/src/b4/__init__.py?h=stable-0.14.y#n3494

The issue is that patchtest Mbox parsing expects this field to know when a patch starts and finishes.

Considering that we know only one patch will be sent over stdin (well, not necessarily but we make the assumption here) then we allow this malformed Mbox when this way of passing the patch is used.

---
 meta/lib/patchtest/mbox.py |  9 +++++----
 meta/lib/patchtest/repo.py |  4 ++--
 scripts/patchtest          | 17 +++++++++++------
 3 files changed, 18 insertions(+), 12 deletions(-)
meta/lib/patchtest/mbox.py +5 -4
index 1d95819b7aee5daa879eac0710827b45b2acfec3..640e74001490ba6a6234da4acf1b13094c280d37 100644
@@ -15,9 +15,10 @@ import re
 
 # From: https://stackoverflow.com/questions/59681461/read-a-big-mbox-file-with-python
 class MboxReader:
-    def __init__(self, filepath):
+    def __init__(self, filepath, allow_malformed=False):
         self.handle = open(filepath, 'rb')
-        assert self.handle.readline().startswith(b'From ')
+        if not allow_malformed:
+            assert self.handle.readline().startswith(b'From ')
 
     def __enter__(self):
         return self
@@ -51,8 +52,8 @@ class Patch:
         self.diff = self.split_body[1]
 
 class PatchSeries:
-    def __init__(self, filepath):
-        with MboxReader(filepath) as mbox:
+    def __init__(self, filepath, allow_malformed=False):
+        with MboxReader(filepath, allow_malformed=allow_malformed) as mbox:
             self.patches = [Patch(message) for message in mbox]
 
         assert self.patches
meta/lib/patchtest/repo.py +2 -2
index 8ec8f68a0bc61fc3b52b5d965663fa3bcfc0a684..9df50ef65f6a2fabc5ff7c5c06252ff44b2e6e9b 100644
@@ -17,10 +17,10 @@ class PatchTestRepo(object):
     # prefixes used for temporal branches/stashes
     prefix = 'patchtest'
 
-    def __init__(self, patch, repodir, commit=None, branch=None):
+    def __init__(self, patch, repodir, commit=None, branch=None, allow_malformed=False):
         self.repodir = repodir
         self.repo = git.Repo.init(repodir)
-        self.patch = mbox.PatchSeries(patch)
+        self.patch = mbox.PatchSeries(patch, allow_malformed=allow_malformed)
         self.current_branch = self.repo.active_branch.name
 
         # targeted branch defined on the patch may be invalid, so make sure there
scripts/patchtest +11 -6
index 82ce665c1a5c950dfaf02cda9ed70b935a9bfe25..2b0bda88cabec3812499f88bb3c4b68d7352bff0 100755
@@ -33,7 +33,7 @@ logger.setLevel(logging.INFO)
 info = logger.info
 error = logger.error
 
-def getResult(patch, mergepatch, logfile=None):
+def getResult(patch, mergepatch, logfile=None, allow_malformed=False):
 
     class PatchTestResult(unittest.TextTestResult):
         """ Patchtest TextTestResult """
@@ -51,6 +51,7 @@ def getResult(patch, mergepatch, logfile=None):
                 "commit": PatchtestParser.basecommit,
                 "branch": PatchtestParser.basebranch,
                 "patch": patch,
+                "allow_malformed": allow_malformed,
             }
 
             self.repo_error    = False
@@ -152,17 +153,17 @@ def _runner(resultklass, prefix=None):
 
     return 0
 
-def run(patch, logfile=None):
+def run(patch, logfile=None, allow_malformed=False):
     """ Load, setup and run pre and post-merge tests """
     # 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_resultklass = getResult(patch, False, logfile, allow_malformed)
     premerge_result = _runner(premerge_resultklass, 'pretest')
 
     # run post-merge tests, meaning those methods with 'test' as prefix
-    postmerge_resultklass = getResult(patch, True, logfile)
+    postmerge_resultklass = getResult(patch, True, logfile, allow_malformed)
     postmerge_result = _runner(postmerge_resultklass, 'test')
 
     if not PatchtestParser.no_summary:
@@ -207,6 +208,7 @@ def main():
         patch_list = [patch_path]
 
     for patch in patch_list:
+        allow_malformed = False
         if patch == "-":
             import tempfile
 
@@ -216,6 +218,9 @@ def main():
             logger.info('Testing patch from stdin')
             tmp_patch = True
             patch = patch.name
+            # b4 strips the "From ", c.f.
+            # https://git.kernel.org/pub/scm/utils/b4/b4.git/tree/src/b4/__init__.py?h=stable-0.14.y#n3494
+            allow_malformed = True
         elif os.path.getsize(patch) == 0:
             logger.error('patchtest: patch is empty')
             return 1
@@ -229,9 +234,9 @@ def main():
 
         try:
             if log_path:
-                run(patch, log_path)
+                run(patch, log_path, allow_malformed=allow_malformed)
             else:
-                run(patch)
+                run(patch, allow_malformed=allow_malformed)
         finally:
             if tmp_patch:
                 os.remove(patch)
Signature · 1 line
2.48.1
#6 lore raw

RFC PATCH 6/6 b4: enable patchtest as b4 prep --check step

In reply to Quentin Schulz

From: Quentin Schulz <[email protected]>

Now that patchtest is silent when everything goes well, we can use it as validation step in OE-Core for each local commit with b4 prep --check.

While at it reenable the pre-flight check for b4 prep --check.

oe-init-buildenv needs to be sourced first to make patchtest available in PATH and a few Python modules installed (e.g. unidiff, pylint, ...; see meta/lib/patchtest/requirements.txt).

---
 .b4-config | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
.b4-config +2 -1
index 8ec5ddd91e1da05f27a53ff6f3d7351317461859..58b45051d554a13643ad65ff6602de82c0c91844 100644
@@ -1,3 +1,4 @@
 [b4]
   send-series-cc = [email protected]
-  prep-pre-flight-checks = disable-needs-auto-to-cc, disable-needs-checking
+  prep-perpatch-check-cmd = patchtest --patch - --quiet --no-summary
+  prep-pre-flight-checks = disable-needs-auto-to-cc
Signature · 1 line
2.48.1