Skip to contentSkip to conversation

Add external test support

RFC New Colin Foster 3 participants 6 messages Jan 3, 2024 – Nov 23

lore
Share & tools
lore
#0 lore raw

v2 cover Add external test support

NOTE: This is an RFC that isn't fully functional! Do not merge!

Add the ability to create and maintain tests in a BR2_EXTERNAL directory.

I recently submitted a simple tftpy test module. My current system is based on Buildroot 2023.02.x, and I would like to be able to run verifications without modification to Buildroot and without waiting until 2024.02.x lands.

There were some Python dependencies that led me to this current iteration, which is to create a temporary directory for all tests and pointing nose2 to the temp directory. I'm not sure if that is elegant, or kludgy... so I'm looking for feedback on that.

I also tested this with my "tftpy" script, but it currently fails.

```
(.venv) $ BR2_EXTERNAL=`pwd`/buildroot-external ./buildroot/support/testing/run-tests -d dl -o output_folder -k tests.package.test_python_tftpy.TestPythonTftpy
17:07:56 TestPythonTftpy                          Starting
17:07:56 TestPythonTftpy                          Building
E
======================================================================
ERROR: test_run (tests.package.test_python_tftpy.TestPythonTftpy)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/pwd/buildroot/support/testing/infra/basetest.py", line 73, in setUp
    self.b.build()
  File "/path/to/pwd/buildroot/support/testing/infra/builder.py", line 98, in build
    raise SystemError("Build failed")
SystemError: Build failed

----------------------------------------------------------------------
Ran 1 test in 4.925s

FAILED (errors=1)
```

I figure I should get some feedback on my approach before digging into this too much further. I did run a simple verification that the functional tests aren't broken:

```
(.venv) $ BR2_EXTERNAL=`pwd`/buildroot-external ./buildroot/support/testing/run-tests -d dl -o output
_folder -k tests.package.test_python_aexpect.TestPythonPy3Aexpect
17:12:55 TestPythonPy3Aexpect                     Starting
17:13:01 TestPythonPy3Aexpect                     Cleaning up
.
----------------------------------------------------------------------
Ran 1 test in 6.521s

OK
```

Thoughts on this approach?
Is there a different way to overlay the external directory that I'm overlooking?

If this approach is valid... then why might the test be failing? I'm surprised to see "/path/to/pwd/buildroot/support/testing/infra/*" referenced in the output... I'd expect it to be "/tmp/tmp*/testing/infra/*".

Thanks for any feedback!

*** Notes on V2 ***

There are two other techniques that might make this "cleaner". The first was suggested by Yann in review, where every test was discovered and soft-linked.

A second option might be to duplicate a directory into a directory like buildroot/support/testing/tests/external. This directory could be in .gitignore and removed upon a clean.

v1 -> v2:
* Still non-functional
* Split into three patches for readability
* Support for multiple BR2_EXTERNALs
* Remove conditional copy to temp directory - always do it.

Colin Foster (3):
support/testing/run-tests: add try block for indentation support/testing/run-tests: run tests from temp directory support/testing/run-tests: add ability to run tests from external

 support/testing/run-tests | 164 +++++++++++++++++++++-----------------
 1 file changed, 91 insertions(+), 73 deletions(-)
Signature · 19 lines
2.34.1

From 1a2a472ec77173101f12a27b28acba688dbc37a6 Mon Sep 17 00:00:00 2001
From: Colin Foster <[email protected]>
Date: Fri, 22 Dec 2023 16:55:32 -0600

Colin Foster (1):
  support/testing/run-tests: add ability to run tests from external

 support/testing/run-tests | 163 +++++++++++++++++++++-----------------
 1 file changed, 91 insertions(+), 72 deletions(-)

-- 
2.34.1

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#1 lore raw

RFC v2 1/3 support/testing/run-tests: add try block for indentation

Cleanup code for try/finally is necessary for a separate patch. Utilize a separate patch to add a try block so that the other patches that actually will change the behavior are much more reviewable.

---

v2: New patch, broken out for reviewability

---
 support/testing/run-tests | 146 ++++++++++++++++++++------------------
 1 file changed, 75 insertions(+), 71 deletions(-)
support/testing/run-tests +75 -71
index 485811b746..9d1174cb3b 100755
@@ -42,94 +42,98 @@ def main():
     script_path = os.path.realpath(__file__)
     test_dir = os.path.dirname(script_path)
 
-    if args.stdout:
-        BRConfigTest.logtofile = False
-
-    if args.list:
-        print("List of tests")
-        nose2.discover(argv=[script_path,
-                             "-s", test_dir,
-                             "-v",
-                             "--collect-only"],
-                       plugins=["nose2.plugins.collect"])
-        return 0
-
-    if args.download is None:
-        args.download = os.getenv("BR2_DL_DIR")
+    try:
+        if args.stdout:
+            BRConfigTest.logtofile = False
+
+        if args.list:
+            print("List of tests")
+            nose2.discover(argv=[script_path,
+                                 "-s", test_dir,
+                                 "-v",
+                                 "--collect-only"],
+                        plugins=["nose2.plugins.collect"])
+            return 0
+
         if args.download is None:
-            print("Missing download directory, please use -d/--download")
+            args.download = os.getenv("BR2_DL_DIR")
+            if args.download is None:
+                print("Missing download directory, please use -d/--download")
+                print("")
+                parser.print_help()
+                return 1
+
+        BRConfigTest.downloaddir = os.path.abspath(args.download)
+
+        if args.prepare_only:
+            emulator_builtin_binaries = ["kernel-vexpress-5.10.202",
+                                         "vexpress-v2p-ca9-5.10.202.dtb",
+                                         "kernel-versatile-5.10.202",
+                                         "versatile-pb-5.10.202.dtb"]
+            print("Downloading emulator builtin binaries")
+            for binary in emulator_builtin_binaries:
+                infra.download(BRConfigTest.downloaddir, binary)
+            return 0
+
+        if args.output is None:
+            print("Missing output directory, please use -o/--output")
             print("")
             parser.print_help()
             return 1
 
-    BRConfigTest.downloaddir = os.path.abspath(args.download)
-
-    if args.prepare_only:
-        emulator_builtin_binaries = ["kernel-vexpress-5.10.202",
-                                     "vexpress-v2p-ca9-5.10.202.dtb",
-                                     "kernel-versatile-5.10.202",
-                                     "versatile-pb-5.10.202.dtb"]
-        print("Downloading emulator builtin binaries")
-        for binary in emulator_builtin_binaries:
-            infra.download(BRConfigTest.downloaddir, binary)
-        return 0
-
-    if args.output is None:
-        print("Missing output directory, please use -o/--output")
-        print("")
-        parser.print_help()
-        return 1
-
-    if not os.path.exists(args.output):
-        os.mkdir(args.output)
+        if not os.path.exists(args.output):
+            os.mkdir(args.output)
 
-    BRConfigTest.outputdir = os.path.abspath(args.output)
+        BRConfigTest.outputdir = os.path.abspath(args.output)
 
-    if args.all is False and not args.testname:
-        print("No test selected")
-        print("")
-        parser.print_help()
-        return 1
-
-    BRConfigTest.keepbuilds = args.keep
-
-    if args.testcases != 1:
-        if args.testcases < 1:
-            print("Invalid number of testcases to run simultaneously")
+        if args.all is False and not args.testname:
+            print("No test selected")
             print("")
             parser.print_help()
             return 1
-        # same default BR2_JLEVEL as package/Makefile.in
-        br2_jlevel = 1 + multiprocessing.cpu_count()
-        each_testcase = int((br2_jlevel + args.testcases) / args.testcases)
-        BRConfigTest.jlevel = each_testcase
-
-    if args.jlevel:
-        if args.jlevel < 0:
-            print("Invalid BR2_JLEVEL to use for each testcase")
+
+        BRConfigTest.keepbuilds = args.keep
+
+        if args.testcases != 1:
+            if args.testcases < 1:
+                print("Invalid number of testcases to run simultaneously")
+                print("")
+                parser.print_help()
+                return 1
+            # same default BR2_JLEVEL as package/Makefile.in
+            br2_jlevel = 1 + multiprocessing.cpu_count()
+            each_testcase = int((br2_jlevel + args.testcases) / args.testcases)
+            BRConfigTest.jlevel = each_testcase
+
+        if args.jlevel:
+            if args.jlevel < 0:
+                print("Invalid BR2_JLEVEL to use for each testcase")
+                print("")
+                parser.print_help()
+                return 1
+            # the user can override the auto calculated value
+            BRConfigTest.jlevel = args.jlevel
+
+        if args.timeout_multiplier < 1:
+            print("Invalid multiplier for timeout values")
             print("")
             parser.print_help()
             return 1
-        # the user can override the auto calculated value
-        BRConfigTest.jlevel = args.jlevel
-
-    if args.timeout_multiplier < 1:
-        print("Invalid multiplier for timeout values")
-        print("")
-        parser.print_help()
-        return 1
-    BRConfigTest.timeout_multiplier = args.timeout_multiplier
+        BRConfigTest.timeout_multiplier = args.timeout_multiplier
 
-    nose2_args = ["-v",
-                  "-N", str(args.testcases),
-                  "-s", test_dir,
-                  "-c", os.path.join(test_dir, "conf/unittest.cfg")]
+        nose2_args = ["-v",
+                      "-N", str(args.testcases),
+                      "-s", test_dir,
+                      "-c", os.path.join(test_dir, "conf/unittest.cfg")]
 
-    if args.testname:
-        nose2_args += args.testname
+        if args.testname:
+            nose2_args += args.testname
 
-    nose2.discover(argv=nose2_args)
+        nose2.discover(argv=nose2_args)
 
+    finally:
+        # Placeholder for try, to be undone shortly
+        pass
 
 if __name__ == "__main__":
     sys.exit(main())
Signature · 6 lines
2.34.1

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#2 lore raw

RFC v2 2/3 support/testing/run-tests: run tests from temp directory

In reply to Colin Foster

When building with the BR2_EXTERNAL environment variable set, it becomes desirable to have a place where tests from buildroot as well as externals can live together.

In lieu of having two branches - one where tests are run internally and one where they're copied to a temp directory - utilize a temp directory for running all tests.

---

v2: New patch

---
 support/testing/run-tests | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
support/testing/run-tests +8 -3
index 9d1174cb3b..dedb487ffd 100755
@@ -3,6 +3,8 @@ import argparse
 import multiprocessing
 import os
 import sys
+import tempfile
+import shutil
 
 import nose2
 
@@ -40,7 +42,11 @@ def main():
     args = parser.parse_args()
 
     script_path = os.path.realpath(__file__)
-    test_dir = os.path.dirname(script_path)
+    script_dir = os.path.dirname(script_path)
+
+    temp_dir = tempfile.TemporaryDirectory()
+    shutil.copytree(script_dir, temp_dir.name, dirs_exist_ok=True)
+    test_dir = temp_dir.name
 
     try:
         if args.stdout:
@@ -132,8 +138,7 @@ def main():
         nose2.discover(argv=nose2_args)
 
     finally:
-        # Placeholder for try, to be undone shortly
-        pass
+        shutil.rmtree(temp_dir.name)
 
 if __name__ == "__main__":
     sys.exit(main())
Signature · 6 lines
2.34.1

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#3 lore raw

RFC v2 3/3 support/testing/run-tests: add ability to run tests from external

In reply to Colin Foster

The BR2_EXTERNAL variable can be used to keep customizations outside of Buildroot. There was no support for writing tests in those external environments.

When the BR2_EXTERNAL environment variable is used for running tests, include the tests found in ${BR2_EXTERNAL}/support/testing.

---

v1 -> v2:
* try / finally reformatting broken out into a separate patch
* Multiple BR2_EXTERNAL support

---
 support/testing/run-tests | 9 +++++++++
 1 file changed, 9 insertions(+)
support/testing/run-tests +9 -0
index dedb487ffd..87ce91266f 100755
@@ -48,6 +48,15 @@ def main():
     shutil.copytree(script_dir, temp_dir.name, dirs_exist_ok=True)
     test_dir = temp_dir.name
 
+    overlay_paths = os.getenv("BR2_EXTERNAL")
+    if overlay_paths:
+        for overlay_path in overlay_paths.split():
+            external_testing_path = overlay_path + "/support/testing"
+            if os.path.exists(external_testing_path):
+                shutil.copytree(external_testing_path,
+                                temp_dir.name,
+                                dirs_exist_ok=True)
+
     try:
         if args.stdout:
             BRConfigTest.logtofile = False
Signature · 6 lines
2.34.1

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#4 lore raw

PATCH v3 1/1 support/testing/run-tests: add ability to run tests from external

In reply to Colin Foster

From: Colin Foster <[email protected]>

The BR2_EXTERNAL variable can be used to keep customizations outside of Buildroot. There was no support for writing tests in those external environments.

When the BR2_EXTERNAL environment variable is set, run-tests now also finds the tests in the support/testing/tests folder of each br2-external:

- The support/testing folders of the br2-externals are added to the Python path, and the tests package of Buildroot and its subpackages use pkgutil.extend_path(). So the tests of the br2-externals merge in the tests package: they are named and run like the Buildroot ones, e.g. tests.package.test_foo.TestFoo.
- PYTHONPATH passes these folders to the nose2 workers.
- nose2 only discovers the tests of one folder, so run-tests gives the names of the external tests to nose2, for -l and for --all.

Document it in the manual, with the two things to know:
infra.filepath() points to the Buildroot tree, and the build of a test case does not use the BR2_EXTERNAL environment variable. So a test case that builds packages of its br2-external lists it in its br2_external member.

---
Changes v2 -> v3:
- new approach: instead of copying all the tests to a temporary folder, merge the tests of the br2-externals in the tests package with pkgutil.extend_path(). Nothing is copied, and infra stays the one of Buildroot.
- drop patch 1/3 (try block) and patch 2/3 (temporary folder), not needed anymore
- list and run the external tests with -l and --all too: nose2 only discovers the tests of one folder
- the build failure in the v2 cover letter came from the build of the test case: it does not use the BR2_EXTERNAL environment variable. Document the br2_external member of the test class, which does it.
- document the feature in the manual
- rebase on master, drop RFC

Supersedes v2:
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/

 docs/manual/contribute.adoc                 | 29 +++++++++++++++
 support/testing/run-tests                   | 39 ++++++++++++++++++++-
 support/testing/tests/__init__.py           |  2 ++
 support/testing/tests/boot/__init__.py      |  2 ++
 support/testing/tests/core/__init__.py      |  2 ++
 support/testing/tests/download/__init__.py  |  2 ++
 support/testing/tests/fs/__init__.py        |  2 ++
 support/testing/tests/init/__init__.py      |  2 ++
 support/testing/tests/package/__init__.py   |  2 ++
 support/testing/tests/toolchain/__init__.py |  2 ++
 support/testing/tests/utils/__init__.py     |  2 ++
 11 files changed, 85 insertions(+), 1 deletion(-)
docs/manual/contribute.adoc +29 -0
index 6ac75fb66a..653be26543 100644
@@ -683,6 +683,35 @@ Creating a basic test case involves:
 After creating the test script, add yourself to the +DEVELOPERS+ file to
 be the maintainer of that test case.
 
+==== Test cases in a br2-external
+
+Test cases can also live in a br2-external tree, in its
++support/testing/tests/+ folder, organized like the one of Buildroot,
+e.g. +support/testing/tests/package/test_foo.py+.
+
+When the +BR2_EXTERNAL+ environment variable is set, +run-tests+ finds
+these test cases too: +run-tests -l+ lists them, and they run like the
+Buildroot ones:
+
+----
+$ BR2_EXTERNAL=/path/to/my-external support/testing/run-tests -d dl -o output_folder tests.package.test_foo.TestFoo
+----
+
+These test cases use the +infra+ of Buildroot, so:
+
+* +infra.filepath()+ points to the Buildroot tree. To find its own
+  files, a test case uses paths relative to its own file, e.g.
+  +os.path.dirname(__file__)+.
+
+* The build of a test case does not use the +BR2_EXTERNAL+ environment
+  variable. To build the packages of its br2-external, the test class
+  lists it in its +br2_external+ member:
+
+----
+class TestFoo(infra.basetest.BRTest):
+    br2_external = [os.path.join(os.path.dirname(__file__), "../../../..")]
+----
+
 ==== Debugging a test case
 
 When a test case runs, the +output_folder+ will contain the following:
support/testing/run-tests +38 -1
index f0c1cc782a..90f564da0a 100755
@@ -11,6 +11,30 @@ from infra.basetest import BRTestSettings
 import infra
 
 
+def external_tests():
+    """Find the tests of the br2-externals, in their support/testing/tests
+
+    The directories are added to the Python path, so that their tests merge
+    in the tests package. PYTHONPATH passes them to the nose2 workers.
+    nose2 only discovers the tests of one directory, so return the names
+    of the external tests, to give them to nose2.
+    """
+    tests = []
+    for external in os.getenv("BR2_EXTERNAL", "").replace(":", " ").split():
+        testing_dir = os.path.join(os.path.abspath(external), "support", "testing")
+        if not os.path.isdir(os.path.join(testing_dir, "tests")):
+            continue
+        sys.path.append(testing_dir)
+        os.environ["PYTHONPATH"] = os.pathsep.join(
+            filter(None, [os.getenv("PYTHONPATH"), testing_dir]))
+        for root, _, files in os.walk(os.path.join(testing_dir, "tests")):
+            for f in sorted(files):
+                if f.startswith("test_") and f.endswith(".py"):
+                    module = os.path.relpath(os.path.join(root, f[:-3]), testing_dir)
+                    tests.append(module.replace(os.sep, "."))
+    return tests
+
+
 def main():
     parser = argparse.ArgumentParser(description='Run Buildroot tests')
     parser.add_argument('testname', nargs='*',
@@ -43,6 +67,7 @@ def main():
 
     script_path = os.path.realpath(__file__)
     test_dir = os.path.dirname(script_path)
+    ext_tests = external_tests()
 
     if args.list:
         print("List of tests")
@@ -55,7 +80,12 @@ def main():
         if args.debug:
             nose2_args += ["--log-level", "debug"]
         nose2.discover(argv=nose2_args,
-                       plugins=["nose2.plugins.collect"])
+                       plugins=["nose2.plugins.collect"],
+                       exit=False)
+        if ext_tests:
+            nose2.discover(argv=nose2_args + ext_tests,
+                           plugins=["nose2.plugins.collect"],
+                           exit=False)
         return 0
 
     if args.download is None:
@@ -140,6 +170,13 @@ def main():
 
     if args.testname:
         nose2_args += args.testname
+    elif ext_tests:
+        # Run all the tests: first the ones of Buildroot, then the ones of
+        # the br2-externals
+        ok = nose2.discover(argv=nose2_args, exit=False).result.wasSuccessful()
+        ok &= nose2.discover(argv=nose2_args + ext_tests,
+                             exit=False).result.wasSuccessful()
+        return 0 if ok else 1
 
     nose2.discover(argv=nose2_args)
 
support/testing/tests/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/boot/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/core/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/download/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/fs/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/init/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/package/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/toolchain/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
support/testing/tests/utils/__init__.py +2 -0
index e69de29bb2..a220f8c5ba 100644
@@ -0,0 +1,2 @@
+# Merge the tests of the br2-externals in this package, see run-tests
+__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Signature · 6 lines
2.53.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#5 lore raw

Re: [Buildroot] [PATCH v3] support/testing/run-tests: add ability to run tests from external

Quoted 18 lines · Angelo Compagnucci

From: Colin Foster <[email protected]>

---
Changes v2 -> v3:
- new approach: instead of copying all the tests to a temporary folder, merge the tests of the br2-externals in the tests package with pkgutil.extend_path(). Nothing is copied, and infra stays the one of Buildroot.
- drop patch 1/3 (try block) and patch 2/3 (temporary folder), not needed anymore
- list and run the external tests with -l and --all too: nose2 only discovers the tests of one folder
- the build failure in the v2 cover letter came from the build of the test case: it does not use the BR2_EXTERNAL environment variable. Document the br2_external member of the test class, which does it.
- document the feature in the manual
- rebase on master, drop RFC

Quoted 5 lines

Supersedes v2:
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/
https://patchwork.buildroot.org/project/buildroot/patch/[email protected]/

Thanks for finding and running with this!

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot