"""CPU contracts for the visual lighting and camera controls. The JSON boundary is also the server-side trust boundary: malformed widget values must fail before any inference work. Markup checks cover keyboard controls and the exact choices the server supports. """ import copy from html.parser import HTMLParser import json import unittest from relight_backend import PRESETS import visual_controls as controls DIRECTIONS = {"Left", "Right", "Front", "Above", "Behind"} AZIMUTHS = set(range(0, 360, 30)) ELEVATIONS = {0, 30, 60, 90} class Elements(HTMLParser): def __init__(self, html): super().__init__() self.elements = [] self.ancestors = [] self.svg_hidden = [] self.feed(html) self.close() def handle_starttag(self, tag, attrs): attrs = dict(attrs) self.elements.append((tag, attrs)) hidden = attrs.get("aria-hidden") == "true" or any( ancestor_hidden for _, ancestor_hidden in self.ancestors) if tag == "svg": self.svg_hidden.append(hidden) if tag not in {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"}: self.ancestors.append((tag, hidden)) def handle_endtag(self, tag): for index in range(len(self.ancestors) - 1, -1, -1): if self.ancestors[index][0] == tag: del self.ancestors[index:] break def with_attribute(self, attribute, tag=None): return [attrs for element, attrs in self.elements if attribute in attrs and (tag is None or element == tag)] class RelightValuesTests(unittest.TestCase): def test_empty_and_partial_values_initialize_safe_preset_defaults(self): expected = ("Soft studio", "Left", "#FFFFFF") for value in (None, "", " \n\t", {}, "{}"): with self.subTest(value=value): self.assertEqual(controls.read_relight_widget(value), expected) for preset, settings in PRESETS.items(): for value in ({"preset": preset}, json.dumps({"preset": preset})): with self.subTest(preset=preset, value=value): self.assertEqual(controls.read_relight_widget(value), (preset, settings["direction"], settings["color"])) self.assertEqual(controls.read_relight_widget({"direction": "Behind"}), ("Soft studio", "Behind", "#FFFFFF")) self.assertEqual(controls.read_relight_widget({"color": "#ab12ef"}), ("Soft studio", "Left", "#AB12EF")) def test_every_preset_direction_and_custom_color_survives_roundtrip(self): for preset in PRESETS: for direction in DIRECTIONS: for color in ("#FFFFFF", "#000000", "#aB12eF"): with self.subTest(preset=preset, direction=direction, color=color): value = controls.relight_widget_value(preset, direction, color) self.assertIsInstance(value, str) payload = json.loads(value) self.assertEqual(payload, {"preset": preset, "direction": direction, "color": color.upper()}) self.assertEqual(controls.read_relight_widget(value), (preset, direction, color.upper())) self.assertEqual(controls.read_relight_widget(payload), (preset, direction, color.upper())) def test_explicit_color_and_direction_override_preset_without_mutating(self): value = {"preset": "Warm sunset", "direction": "Above", "color": "#0a12ef"} original = copy.deepcopy(value) self.assertEqual(controls.read_relight_widget(value), ("Warm sunset", "Above", "#0A12EF")) self.assertEqual(value, original) self.assertEqual(controls.read_relight_widget(controls.relight_widget_value()), ("Soft studio", "Left", "#FFFFFF")) def test_unknown_or_wrong_type_presets_and_directions_are_rejected(self): for field, invalid_values in ( ("preset", ("", "soft studio", "Unknown", None, 0, True, [], {})), ("direction", ("", "left", "Below", None, 0, False, [], {})), ): for value in invalid_values: with self.subTest(field=field, value=value): with self.assertRaises(ValueError): controls.read_relight_widget({field: value}) with self.assertRaises(ValueError): controls.relight_widget_value(**{field: value}) def test_only_six_digit_hex_colors_are_accepted(self): for color in ("", "#fff", "ABCDEF", "#12345678", "#12GG34", "red", " #123456", "#123456\n", None, True, 123456, [], {}): with self.subTest(color=color): with self.assertRaises(ValueError): controls.read_relight_widget({"color": color}) with self.assertRaises(ValueError): controls.relight_widget_value(color=color) class CameraValuesTests(unittest.TestCase): def test_empty_and_partial_values_initialize_defaults(self): for value in (None, "", " \n\t", {}, "{}"): with self.subTest(value=value): self.assertEqual(controls.read_camera_widget(value), (90, 0, False)) self.assertEqual(controls.read_camera_widget({"azimuth": 330}), (330, 0, False)) self.assertEqual(controls.read_camera_widget({"elevation": 60}), (90, 60, False)) self.assertEqual(controls.read_camera_widget({"closeup": True}), (90, 0, True)) self.assertEqual(controls.read_camera_widget(controls.camera_widget_value()), (90, 0, False)) def test_all_96_supported_camera_states_survive_roundtrip(self): for azimuth in AZIMUTHS: for elevation in ELEVATIONS: for closeup in (False, True): with self.subTest(azimuth=azimuth, elevation=elevation, closeup=closeup): value = controls.camera_widget_value(azimuth, elevation, closeup) self.assertIsInstance(value, str) payload = json.loads(value) self.assertEqual(payload, {"azimuth": azimuth, "elevation": elevation, "closeup": closeup}) for encoded in (value, payload): result = controls.read_camera_widget(encoded) self.assertEqual(result, (azimuth, elevation, closeup)) self.assertIs(type(result[0]), int) self.assertIs(type(result[1]), int) self.assertIs(type(result[2]), bool) def test_whole_number_floats_normalize_without_mutating_input(self): value = {"azimuth": 330.0, "elevation": 90.0, "closeup": True} original = copy.deepcopy(value) self.assertEqual(controls.read_camera_widget(value), (330, 90, True)) self.assertEqual(value, original) output = json.loads(controls.camera_widget_value(30.0, 60.0, False)) self.assertIs(type(output["azimuth"]), int) self.assertIs(type(output["elevation"]), int) def test_invalid_angles_are_rejected_in_readers_and_makers(self): common_invalid = (None, True, False, "0", "30", "", [], {}, float("nan"), float("inf"), -float("inf"), 29.5) invalid_by_field = { "azimuth": common_invalid + (-30, -1, 1, 15, 31, 359, 360, 390), "elevation": common_invalid + (-30, -1, 1, 15, 31, 91, 120, 330), } for field, invalid_values in invalid_by_field.items(): for value in invalid_values: with self.subTest(field=field, value=value): with self.assertRaises(ValueError): controls.read_camera_widget({field: value}) with self.assertRaises(ValueError): controls.camera_widget_value(**{field: value}) def test_closeup_requires_boolean_not_truthy_coercion(self): for value in (None, 0, 1, 0.0, 1.0, "", "true", "false", "True", [], {}): with self.subTest(value=value): with self.assertRaises(ValueError): controls.read_camera_widget({"closeup": value}) with self.assertRaises(ValueError): controls.camera_widget_value(closeup=value) class PayloadBoundaryTests(unittest.TestCase): def test_both_readers_reject_malformed_json_and_non_objects(self): invalid = ("{", "{broken}", '{"x":1,}', "[]", "[{}]", "null", "true", "false", "1", '"text"', [], (), 0, 1, False, True, b"{}") for reader in (controls.read_relight_widget, controls.read_camera_widget): for value in invalid: with self.subTest(reader=reader.__name__, value=value): with self.assertRaises(ValueError): reader(value) def test_both_readers_reject_unknown_fields_including_other_widget_fields(self): for reader, payload in ( (controls.read_relight_widget, {"unknown": 1}), (controls.read_relight_widget, {"azimuth": 90}), (controls.read_camera_widget, {"unknown": 1}), (controls.read_camera_widget, {"color": "#FFFFFF"}), ): for value in (payload, json.dumps(payload)): with self.subTest(reader=reader.__name__, value=value): with self.assertRaises(ValueError): reader(value) def test_serialized_state_has_a_strict_2048_character_limit(self): for reader, expected in ( (controls.read_relight_widget, ("Soft studio", "Left", "#FFFFFF")), (controls.read_camera_widget, (90, 0, False)), ): with self.subTest(reader=reader.__name__): self.assertEqual(reader("{}" + " " * 2046), expected) with self.assertRaises(ValueError): reader("{}" + " " * 2047) with self.assertRaises(ValueError): reader(" " * 2049) class MarkupContractsTests(unittest.TestCase): def test_relight_buttons_match_supported_presets_and_directions(self): markup = Elements(controls.RELIGHT_HTML) presets = markup.with_attribute("data-preset", "button") directions = markup.with_attribute("data-direction", "button") self.assertCountEqual([item["data-preset"] for item in presets], PRESETS) self.assertCountEqual([item["data-direction"] for item in directions], DIRECTIONS) swatches = markup.with_attribute("data-swatch", "button") self.assertEqual(len(swatches), 6) self.assertEqual(len({item["data-swatch"] for item in swatches}), 6) for swatch in swatches: self.assertRegex(swatch["data-swatch"], r"^#[0-9A-Fa-f]{6}$") custom = markup.with_attribute("data-custom-color", "input") self.assertEqual(len(custom), 1) self.assertEqual(custom[0].get("type"), "color") self.assertTrue(custom[0].get("aria-label", "").strip()) def test_camera_buttons_cover_exactly_twelve_angles_and_four_elevations(self): markup = Elements(controls.CAMERA_HTML) azimuths = markup.with_attribute("data-azimuth", "button") elevations = markup.with_attribute("data-elevation", "button") self.assertCountEqual([int(item["data-azimuth"]) for item in azimuths], AZIMUTHS) self.assertCountEqual([int(item["data-elevation"]) for item in elevations], ELEVATIONS) self.assertEqual(len(markup.with_attribute("data-closeup", "button")), 1) def test_widget_buttons_have_native_keyboard_semantics_and_accessible_names(self): for name, html in (("relight", controls.RELIGHT_HTML), ("camera", controls.CAMERA_HTML)): markup = Elements(html) buttons = [attrs for tag, attrs in markup.elements if tag == "button"] self.assertTrue(buttons, name) for attrs in buttons: with self.subTest(widget=name, label=attrs.get("aria-label")): self.assertEqual(attrs.get("type"), "button") self.assertTrue(attrs.get("aria-label", "").strip()) self.assertIn(attrs.get("aria-pressed"), ("true", "false")) self.assertNotEqual(attrs.get("tabindex"), "-1") for index, hidden in enumerate(markup.svg_hidden): with self.subTest(widget=name, svg=index): self.assertTrue(hidden, "Decorative SVG needs aria-hidden on itself or an ancestor") if __name__ == "__main__": unittest.main()