Skip to contentSkip to conversation

RFC: Support pytest for bitbake self-tests

PATCH In review Peter Hoyes 2 participants 8 messages Jun 16, 2023

lore
Share & tools
lore
#0 lore raw

cover RFC: Support pytest for bitbake self-tests

From: Peter Hoyes <[email protected]>

pytest [1] is a test runner for Python test suites. Its advantages over vanilla unittest are:

* An existing tool with a familiar entry-point.
* A flexible plugin architecture that supports a large plugin ecosystem, including for parallel testing and embedded testing.
* Fixtures, for more flexible and granular sharing of setup/teardown logic.

This patch chain proposes introducing pytest as an alternative test runner for the Bitbake self-tests.

pytest is mostly compatible with unittest TestCases out of the box, but some small adaptations are included in this patch chain, alongside a pytest.ini file and an update to the README.

This patch chain does not mandate how the pytest package is obtained, apart from a reference to PyPI in the README. The 'minversion' is set to 7.3, the latest version, in the pytest.ini file.

[1] https://docs.pytest.org/

Peter Hoyes (5):
bitbake: tests/fetch: Mark TestTimeout as not a test suite
bitbake: tests/fetch: Rename assertRaisesRegexp to assertRaisesRegex
bitbake: tests/fetch: Set git config if not already set
bitbake: tests: Use assertLogs to test logging output
bitbake: Bootstrap pytest for self-tests

 bitbake/README                   |  8 ++++++--
 bitbake/lib/bb/tests/conftest.py |  8 ++++++++
 bitbake/lib/bb/tests/fetch.py    | 23 +++++++++++++++--------
 bitbake/lib/bb/tests/parse.py    | 16 +++++++++-------
 bitbake/pytest.ini               |  7 +++++++
 5 files changed, 45 insertions(+), 17 deletions(-)
 create mode 100644 bitbake/lib/bb/tests/conftest.py
 create mode 100644 bitbake/pytest.ini
Signature · 1 line
2.34.1
#1 lore raw

PATCH 1/5 bitbake: tests/fetch: Mark TestTimeout as not a test suite

From: Peter Hoyes <[email protected]>

pytest test collection attempts to collect all classes containing "Test". TestTimeout is not a test class so add the __test__ = False attribute to indicate this.

---
 bitbake/lib/bb/tests/fetch.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
bitbake/lib/bb/tests/fetch.py +2 -1
index d230120271..ba7be048a8 100644
@@ -24,7 +24,8 @@ def skipIfNoNetwork():
     return lambda f: f
 
 class TestTimeout(Exception):
-    pass
+    # Indicate to pytest that this is not a test suite
+    __test__ = False
 
 class Timeout():
 
Signature · 1 line
2.34.1
#2 lore raw

PATCH 2/5 bitbake: tests/fetch: Rename assertRaisesRegexp to assertRaisesRegex

In reply to Peter Hoyes

From: Peter Hoyes <[email protected]>

TestCase.assertRaisesRegexp was renamed to assertRaisesRegex in Python 3.2, so rename to fix a warning during test execution.

---
 bitbake/lib/bb/tests/fetch.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
bitbake/lib/bb/tests/fetch.py +1 -1
index ba7be048a8..871c174e82 100644
@@ -2486,7 +2486,7 @@ class CrateTest(FetcherTest):
         uris = self.d.getVar('SRC_URI').split()
 
         fetcher = bb.fetch2.Fetch(uris, self.d)
-        with self.assertRaisesRegexp(bb.fetch2.FetchError, "Fetcher failure for URL"):
+        with self.assertRaisesRegex(bb.fetch2.FetchError, "Fetcher failure for URL"):
             fetcher.download()
 
 class NPMTest(FetcherTest):
Signature · 1 line
2.34.1
#3 lore raw

PATCH 3/5 bitbake: tests/fetch: Set git config if not already set

In reply to Peter Hoyes

From: Peter Hoyes <[email protected]>

git config returns an error code if user.email or user.name are not set, so bb.process.run raises an ExecutionError, failing the test.

Improve the logic by catching the ExectionError and using this to set a default value.

Change a direct invocation of 'git init' to use self.git_init so that it follows the code path above.

Remove the related comment from the README now that git sets up the user details automatically.

---
 bitbake/README                |  3 +--
 bitbake/lib/bb/tests/fetch.py | 12 +++++++++---
 2 files changed, 10 insertions(+), 5 deletions(-)
bitbake/README +1 -2
index a5f5c1b64f..bdb1e81dc1 100644
@@ -45,8 +45,7 @@ it has so many corner cases. The datastore has many tests too. Testing with the
 recommended before submitting patches, particularly to the fetcher and datastore. We also
 appreciate new test cases and may require them for more obscure issues.
 
-To run the tests "zstd" and "git" must be installed. Git must be correctly configured, in
-particular the user.email and user.name values must be set.
+To run the tests "zstd" and "git" must be installed.
 
 The assumption is made that this testsuite is run from an initialized OpenEmbedded build
 environment (i.e. `source oe-init-build-env` is used). If this is not the case, run the
bitbake/lib/bb/tests/fetch.py +9 -3
index 871c174e82..8ca7e6c155 100644
@@ -429,9 +429,15 @@ class FetcherTest(unittest.TestCase):
         # a common setup is to use other default
         # branch than master.
         self.git(['checkout', '-b', 'master'], cwd=cwd)
-        if not self.git(['config', 'user.email'], cwd=cwd):
+
+        try:
+            self.git(['config', 'user.email'], cwd=cwd)
+        except bb.process.ExecutionError:
             self.git(['config', 'user.email', '[email protected]'], cwd=cwd)
-        if not self.git(['config', 'user.name'], cwd=cwd):
+
+        try:
+            self.git(['config', 'user.name'], cwd=cwd)
+        except bb.process.ExecutionError:
             self.git(['config', 'user.name', 'Your Name'], cwd=cwd)
 
 class MirrorUriTest(FetcherTest):
@@ -3038,7 +3044,7 @@ class FetchPremirroronlyLocalTest(FetcherTest):
         self.mirrorname = "git2_git.fake.repo.bitbake.tar.gz"
         recipeurl = "git:/git.fake.repo/bitbake"
         os.makedirs(self.gitdir)
-        self.git("init", self.gitdir)
+        self.git_init(cwd=self.gitdir)
         for i in range(0):
             self.git_new_commit()
         bb.process.run('tar -czvf {} .'.format(os.path.join(self.mirrordir, self.mirrorname)), cwd =  self.gitdir)
Signature · 1 line
2.34.1
#4 lore raw

PATCH 4/5 bitbake: tests: Use assertLogs to test logging output

In reply to Peter Hoyes

From: Peter Hoyes <[email protected]>

By default, pytest captures all stdout and exposes it using its built-in fixtures (capsys, caplog etc), so stdout does not support getvalue().

To support running tests using both unittest and pytest, use assertLogs to capture logging and assert on the log output instead.

---
 bitbake/lib/bb/tests/fetch.py |  6 +++---
 bitbake/lib/bb/tests/parse.py | 16 +++++++++-------
 2 files changed, 12 insertions(+), 10 deletions(-)
bitbake/lib/bb/tests/fetch.py +3 -3
index 8ca7e6c155..20593764fd 100644
@@ -3183,7 +3183,7 @@ class FetchPremirroronlyBrokenTarball(FetcherTest):
         import sys
         self.d.setVar("SRCREV", "0"*40)
         fetcher = bb.fetch.Fetch([self.recipe_url], self.d)
-        with self.assertRaises(bb.fetch2.FetchError):
+        with self.assertRaises(bb.fetch2.FetchError), self.assertLogs() as logs:
             fetcher.download()
-        stdout = sys.stdout.getvalue()
-        self.assertFalse(" not a git repository (or any parent up to mount point /)" in stdout)
+        output = "".join(logs.output)
+        self.assertFalse(" not a git repository (or any parent up to mount point /)" in output)
bitbake/lib/bb/tests/parse.py +9 -7
index a3165d95bd..304bbbe222 100644
@@ -186,14 +186,16 @@ deltask ${EMPTYVAR}
 """
     def test_parse_addtask_deltask(self):
         import sys
-        f = self.parsehelper(self.addtask_deltask)
-        d = bb.parse.handle(f.name, self.d)['']
 
-        stdout = sys.stdout.getvalue()
-        self.assertTrue("addtask contained multiple 'before' keywords" in stdout)
-        self.assertTrue("addtask contained multiple 'after' keywords" in stdout)
-        self.assertTrue('addtask ignored: " do_patch"' in stdout)
-        #self.assertTrue('dependent task do_foo for do_patch does not exist' in stdout)
+        with self.assertLogs() as logs:
+            f = self.parsehelper(self.addtask_deltask)
+            d = bb.parse.handle(f.name, self.d)['']
+
+        output = "".join(logs.output)
+        self.assertTrue("addtask contained multiple 'before' keywords" in output)
+        self.assertTrue("addtask contained multiple 'after' keywords" in output)
+        self.assertTrue('addtask ignored: " do_patch"' in output)
+        #self.assertTrue('dependent task do_foo for do_patch does not exist' in output)
 
     broken_multiline_comment = """
 # First line of comment \\
Signature · 1 line
2.34.1
#5 lore raw

PATCH 5/5 bitbake: Bootstrap pytest for self-tests

In reply to Peter Hoyes

From: Peter Hoyes <[email protected]>

To support running the bitbake self-tests using pytest, add a pytest.ini This enables these tests to be run using the following command from the bitbake directory.

pytest

For now, testpaths only includes the bitbake selftests.

Add a note to the README.

---
 bitbake/README                   | 5 +++++
 bitbake/lib/bb/tests/conftest.py | 8 ++++++++
 bitbake/pytest.ini               | 7 +++++++
 3 files changed, 20 insertions(+)
 create mode 100644 bitbake/lib/bb/tests/conftest.py
 create mode 100644 bitbake/pytest.ini
bitbake/README +5 -0
index bdb1e81dc1..78610e65f1 100644
@@ -53,3 +53,8 @@ testsuite as follows:
 
     export PATH=$(pwd)/bin:$PATH
     bin/bitbake-selftest
+
+The testsuite can alternatively be executed using pytest, e.g. obtained from PyPI (in this
+case, the PATH is configured automatically):
+
+    pytest
bitbake/lib/bb/tests/conftest.py new file +8 -0
new file mode 100644
index 0000000000..59a8c6753b
@@ -0,0 +1,8 @@
+import pathlib
+import pytest
+
+BB_BIN_PATH = pathlib.Path(__file__).parents[3].resolve() / 'bin'
+
[email protected](autouse=True)
+def bitbake_path(monkeypatch):
+    monkeypatch.setenv('PATH', str(BB_BIN_PATH), prepend=':')
bitbake/pytest.ini new file +7 -0
new file mode 100644
index 0000000000..3927e49021
@@ -0,0 +1,7 @@
+[pytest]
+addopts = --import-mode=importlib
+minversion = 7.3
+junit_family = xunit1
+python_files = tests/*.py
+pythonpath = lib
+testpaths = lib/bb
Signature · 1 line
2.34.1
#6 lore raw

Re: [bitbake-devel] [PATCH 5/5] bitbake: Bootstrap pytest for self-tests

Quoted 19 lines · Peter Hoyes

From: Peter Hoyes <[email protected]>

To support running the bitbake self-tests using pytest, add a pytest.ini This enables these tests to be run using the following command from the bitbake directory.

pytest

For now, testpaths only includes the bitbake selftests.

Add a note to the README.

 bitbake/lib/bb/tests/conftest.py | 8 ++++++++
bitbake/lib/bb/tests/conftest.py new file +0 -0
new file mode 100644
index 0000000000..59a8c6753b

bitbake/lib/bb/tests/conftest.py line 8

Quoted 8 lines
bitbake/lib/bb/tests/conftest.py new file +8 -0
@@ -0,0 +1,8 @@
+import pathlib
+import pytest
+
+BB_BIN_PATH = pathlib.Path(__file__).parents[3].resolve() / 'bin'
+
[email protected](autouse=True)
+def bitbake_path(monkeypatch):
+    monkeypatch.setenv('PATH', str(BB_BIN_PATH), prepend=':')

The addition and purpose of this file should be explained.

Alex

#7 lore raw

Re: [bitbake-devel] [PATCH 5/5] bitbake: Bootstrap pytest for self-tests

Quoted 29 lines · Alexander Kanavin
Quoted 18 lines · Peter Hoyes

From: Peter Hoyes <[email protected]>

To support running the bitbake self-tests using pytest, add a pytest.ini This enables these tests to be run using the following command from the bitbake directory.

pytest

For now, testpaths only includes the bitbake selftests.

Add a note to the README.

  bitbake/lib/bb/tests/conftest.py | 8 ++++++++
bitbake/lib/bb/tests/conftest.py new file +0 -0
new file mode 100644
index 0000000000..59a8c6753b

bitbake/lib/bb/tests/conftest.py line 8

Quoted 8 lines
bitbake/lib/bb/tests/conftest.py new file +8 -0
@@ -0,0 +1,8 @@
+import pathlib
+import pytest
+
+BB_BIN_PATH = pathlib.Path(__file__).parents[3].resolve() / 'bin'
+
[email protected](autouse=True)
+def bitbake_path(monkeypatch):
+    monkeypatch.setenv('PATH', str(BB_BIN_PATH), prepend=':')

The addition and purpose of this file should be explained.

Quoted 1 line

Alex

"conftest.py" is a pytest feature [1] for test module-specific configuration, which is ignored by unittest.

The intention here is to automatically configure the PATH to avoid extra manual steps after checkout. I can either add a comment to this effect in v2, or drop this file and require the user to manually configure the PATH, as for bitbake-selftest.

Peter

[1] https://docs.pytest.org/en/7.3.x/reference/fixtures.html#conftest-py-sharing-fixtures-across-multiple-files