import importlib.util from pathlib import Path import unittest import tempfile import json from unittest.mock import patch spec = importlib.util.spec_from_file_location("desktop", Path(__file__).parents[1] / "vm/desktop.py") desktop = importlib.util.module_from_spec(spec) spec.loader.exec_module(desktop) class ValidationTests(unittest.TestCase): def test_session_save(self): with tempfile.TemporaryDirectory() as directory: state = Path(directory) with patch.object(desktop, "STATE", state): desktop.save_session({"DISPLAY": ":0"}) desktop.save_session({"DISPLAY": ":1"}) path = state / "session.json" self.assertEqual(json.loads(path.read_text()), {"DISPLAY": ":1"}) self.assertEqual(path.stat().st_mode & 0o777, 0o600) self.assertEqual(len(list(state.iterdir())), 1) def test_autostart(self): with tempfile.TemporaryDirectory() as directory: with patch.object(Path, "home", return_value=Path(directory)): desktop.install_autostart() desktop.install_autostart() entries = list((Path(directory) / ".config/autostart").iterdir()) self.assertEqual(len(entries), 1) self.assertIn("--register-session\n", entries[0].read_text()) self.assertIn("OnlyShowIn=XFCE;", entries[0].read_text()) def test_normalized_coordinates(self): for value, expected in [(0, (0, 0)), (500, (640, 400)), (1000, (1279, 799))]: self.assertEqual(desktop.click_pixels({"x": value, "y": value}, 1280, 800, "normalized_1000"), expected) self.assertEqual(desktop.click_pixels({"x": 1000, "y": 1000}, 1, 1, "normalized_1000"), (0, 0)) self.assertEqual(desktop.click_pixels({"x": 480, "y": 425}, 1280, 800, "pixels"), (480, 425)) for value in (-1, 1001, 0.5, True): with self.assertRaises(ValueError): desktop.click_pixels({"x": value, "y": 0}, 1280, 800, "normalized_1000") def test_invalid_coordinate_space(self): with self.assertRaises(ValueError): desktop.validate({"actions": [], "coordinateSpace": "guess"}, 1280, 800) def test_capture(self): self.assertEqual(desktop.validate({"actions": []}, 100, 100), []) def test_bounds(self): for x in (-1, 100, True, "2"): with self.assertRaises(ValueError): desktop.validate({"actions": [{"type": "click", "x": x, "y": 0}]}, 100, 100) def test_invalid_keys(self): with self.assertRaises(ValueError): desktop.validate({"actions": [{"type": "keys", "keys": ["--repeat"]}]}, 100, 100) def test_wait_budget(self): with self.assertRaises(ValueError): desktop.validate({"actions": [{"type": "wait", "milliseconds": 3000}] * 2}, 100, 100) if __name__ == "__main__": unittest.main()