util,test: add test for new shlex based os-release parsing

This commit adds a tiny unit test for the new `shlex` based
os-release parsing and tweaks the error message in a small
and non-functional way (just because it's slightly nicer
for a user). The test checks for three keys NAME which is
quoted with `"`, ID which is not quoted and OSTREE_VERSION
which is quoted with `'`.
This commit is contained in:
Michael Vogt 2024-12-04 17:20:31 +01:00 committed by Dusty Mabe
parent 07d4f6955d
commit 25d3656068
2 changed files with 26 additions and 2 deletions

View file

@ -35,8 +35,10 @@ def parse_files(*paths):
continue continue
key, value = line.split("=", 1) key, value = line.split("=", 1)
split_value = shlex.split(value) split_value = shlex.split(value)
if not split_value or len(split_value) > 1: if not split_value:
raise ValueError(f"Key '{key}' has an empty value or more than one token: {value}") raise ValueError(f"Key '{key}' has an empty value")
if len(split_value) > 1:
raise ValueError(f"Key '{key}' has more than one token: {value}")
osrelease[key] = split_value[0] osrelease[key] = split_value[0]
return osrelease return osrelease

View file

@ -5,6 +5,8 @@
import os import os
import unittest import unittest
import pytest
from osbuild.util import osrelease from osbuild.util import osrelease
from .. import test from .. import test
@ -28,3 +30,23 @@ class TestUtilOSRelease(test.TestBase):
for entry in os.scandir(os.path.join(self.locate_test_data(), "os-release")): for entry in os.scandir(os.path.join(self.locate_test_data(), "os-release")):
with self.subTest(entry.name): with self.subTest(entry.name):
self.assertEqual(osrelease.describe_os(entry.path), entry.name) self.assertEqual(osrelease.describe_os(entry.path), entry.name)
def test_osreleae_f40_really_coreos_happy():
here = os.path.dirname(__file__)
res = osrelease.parse_files(os.path.join(here, "../data/os-release/fedora40"))
assert res["NAME"] == 'Fedora Linux'
assert res["ID"] == 'fedora'
assert res["OSTREE_VERSION"] == '40.20241106.dev.0'
@pytest.mark.parametrize("content,expected_err", [
("OSTREE=", "Key 'OSTREE' has an empty value"),
("OSTREE='foo' 'bar'", "Key 'OSTREE' has more than one token: 'foo' 'bar'"),
])
def test_osrelease_bad_split_empty(tmp_path, content, expected_err):
bad_os_release_path = tmp_path / "os-release"
bad_os_release_path.write_text(content + "\n")
with pytest.raises(ValueError) as exc:
osrelease.parse_files(bad_os_release_path)
assert str(exc.value) == expected_err