From 17b1fa46179369e28142b7c6971a9d6695daf50b Mon Sep 17 00:00:00 2001 From: Svein Seldal Date: Wed, 11 Sep 2024 14:28:23 +0200 Subject: [PATCH] Update tests --- packaging/filereplacer.py | 7 +++---- sonar-project.properties | 2 +- tests/test_installer.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 tests/test_installer.py diff --git a/packaging/filereplacer.py b/packaging/filereplacer.py index bd12a25..33d88ba 100644 --- a/packaging/filereplacer.py +++ b/packaging/filereplacer.py @@ -40,11 +40,10 @@ def convert(infile, outfile): out += os.environ[name] else: - raise Exception(f"The variable {name} is not defined") + raise KeyError(f"The variable {name} is not defined") - if out: - with open(outfile, 'w', encoding="utf-8") as fout: - fout.write(out) + with open(outfile, 'w', encoding="utf-8") as fout: + fout.write(out) if __name__ == '__main__': diff --git a/sonar-project.properties b/sonar-project.properties index 98f47b1..741820f 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,4 +1,4 @@ sonar.projectKey=Laerdal_python-objdictgen sonar.organization=laerdal-foss sonar.python.coverage.reportPaths=coverage.xml -sonar.exclusions = tests/** +sonar.exclusions = tests/**, packaging/** diff --git a/tests/test_installer.py b/tests/test_installer.py new file mode 100644 index 0000000..c71a40c --- /dev/null +++ b/tests/test_installer.py @@ -0,0 +1,38 @@ + +import pytest +from unittest import mock +import os +import sys + +@pytest.fixture +def setenvvar(monkeypatch): + with mock.patch.dict(os.environ, {"TEST": "foobar"}): + yield + + +def test_filereplacer(basepath, wd, setenvvar): + + sys.path.append(str(basepath / "packaging")) + os.chdir(basepath) + from filereplacer import convert + + tests = [ + (1, "Test data", "Test data"), + (2, "@@{name}", "objdictgen"), + (3, "@@{TEST}", "foobar"), # Read from the mocked environment variable + (4, "@@{nonexisting}", "non-existing"), + ] + + for i, data, result in tests: + infile = wd / "test.txt" + outfile = wd / "out.txt" + with open(infile, "w", encoding="utf-8") as f: + f.write(data) + if i == 4: + with pytest.raises(KeyError): + convert(infile, outfile) + continue + else: + convert(infile, outfile) + with open(outfile, "r", encoding="utf-8") as f: + assert f.read() == result