Files
pruefwerk/scripts/test_codesys_export.py
T
Sharang ParnerkarandClaude Opus 5.5 0b833b85e8
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m4s
CI / Check (pull_request) Successful in 17m14s
fix(scan): Prüfwerk's own code no longer flags its test literals
Four findings of Prüfwerk's scan of its own repository, each a test value:

- scripts/test_codesys_export.py ran the export script with
  exec(compile(...)) (semgrep exec-used). runpy.run_path runs it the same
  way, with the Script Engine's `projects` as an initial global, without
  eval.
- patterns.rs: the oauth-token-url test held the strings the rule matches,
  so the rule matched its own test. The strings are now split with
  concat!, and the test checks the same.
- A made-up Firebase-shaped key in gitleaks.rs's tests and the throwaway
  MongoDB password of a CI test container are in the git history, which
  the secret scanner walks. .gitleaksignore lists their fingerprints
  (commit:file:rule:line); gitleaks honours it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 19:06:45 +01:00

126 lines
4.4 KiB
Python

"""Offline tests of docs/public/downloads/codesys-export-plcopen.py.
The script runs inside the CODESYS Script Engine, which provides the global
`projects`. Here it runs with a stand-in that records what the script asks of
it and writes a fake export, so the script's own logic is checked: arguments,
the default export path, opening and closing, and the POU check.
Run: python3 -I -m unittest discover -s scripts -p "test_*.py"
"""
from __future__ import annotations
import os
import tempfile
import unittest
from pathlib import Path
SCRIPT = (Path(__file__).resolve().parent.parent
/ "docs" / "public" / "downloads" / "codesys-export-plcopen.py")
class FakeProject:
"""A ScriptProject that writes `body` as its PLCopen XML export."""
def __init__(self, path: str, body: bytes) -> None:
self.path = path
self.body = body
self.calls: list[tuple[object, ...]] = []
def get_children(self, recursive: bool) -> list[str]:
self.calls.append(("get_children", recursive))
return ["Device", "Application"]
def export_xml(self, objects: list[str], path: str, recursive: bool) -> None:
self.calls.append(("export_xml", tuple(objects), path, recursive))
Path(path).write_bytes(self.body)
def close(self) -> None:
self.calls.append(("close",))
class FakeProjects:
"""The Script Engine's `projects`: one primary project, or one to open."""
def __init__(self, project: FakeProject, primary: bool) -> None:
self.project = project
self.primary = project if primary else None
self.opened: list[str] = []
def open(self, path: str) -> FakeProject:
self.opened.append(path)
return self.project
def run(argv: list[str], projects: FakeProjects | None) -> int:
"""Run the script with `argv`; its exit status (0 when it returns)."""
# The Script Engine's globals; runpy adds __name__ and __file__.
scope: dict[str, object] = {}
if projects is not None:
scope["projects"] = projects
import runpy
import sys
saved = sys.argv
sys.argv = argv
try:
runpy.run_path(str(SCRIPT), init_globals=scope, run_name="__main__")
except SystemExit as stop:
return int(stop.code or 0)
finally:
sys.argv = saved
return 0
POUS = b'<?xml version="1.0"?><project><pou name="A"/><pou name="B"/></project>'
class ExportTests(unittest.TestCase):
def setUp(self) -> None:
self.dir = tempfile.TemporaryDirectory()
self.root = Path(self.dir.name)
self.project_file = self.root / "Line.project"
self.project_file.write_bytes(b"\x00native")
def tearDown(self) -> None:
self.dir.cleanup()
def test_a_named_project_is_opened_exported_and_closed(self) -> None:
out = self.root / "export" / "Line.xml"
project = FakeProject(str(self.project_file), POUS)
engine = FakeProjects(project, primary=False)
status = run(["x", str(self.project_file), str(out)], engine)
self.assertEqual(status, 0)
self.assertEqual(engine.opened, [str(self.project_file)])
self.assertIn(("export_xml", ("Device", "Application"), str(out), True), project.calls)
self.assertEqual(project.calls[-1], ("close",))
self.assertTrue(out.is_file(), "the export folder is created")
def test_the_open_project_is_exported_next_to_itself_and_left_open(self) -> None:
project = FakeProject(str(self.project_file), POUS)
status = run(["x"], FakeProjects(project, primary=True))
self.assertEqual(status, 0)
self.assertTrue((self.root / "Line.plcopen.xml").is_file())
self.assertNotIn(("close",), project.calls)
def test_an_export_without_a_pou_fails(self) -> None:
project = FakeProject(str(self.project_file), b"<project/>")
status = run(["x", str(self.project_file)], FakeProjects(project, primary=False))
self.assertEqual(status, 1)
def test_a_missing_project_or_none_open_fails(self) -> None:
project = FakeProject(str(self.project_file), POUS)
missing = os.path.join(self.dir.name, "Missing.project")
self.assertEqual(run(["x", missing], FakeProjects(project, primary=False)), 1)
self.assertEqual(run(["x"], FakeProjects(project, primary=False)), 1)
def test_outside_codesys_it_says_so(self) -> None:
self.assertEqual(run(["x"], None), 1)
if __name__ == "__main__":
unittest.main()