test(wallaper_changer): add tests modules

add tests for monitor_manager, wallpaper_builder, encryption_manager,
walpaper_Setter
This commit is contained in:
Lucas Vivo committed 2026-11-16 19:48:08 +01:00
1 parent 8669499c36
commit 69b39940b0
4 files changed
+1043

No files matched your search

@@ -0,0 +1,207 @@
import os
import shutil
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from wallpaper_changer.argument_parser import parse_args
from wallpaper_changer.config import Config
from wallpaper_changer.encryption_manager import EncryptionManager, FileInfo
from wallpaper_changer.image_repository import ImageRepository
class EncryptionManagerTests(unittest.TestCase):
def parse_args(self, *arguments: str):
return parse_args(list(arguments))
def test_encrypt_decrypt_round_trip(self) -> None:
"""Verify encrypted bytes decrypt to the original content and hash."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "corrupt"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "corrupt", config.img_dir)
image_repository = ImageRepository(config.img_dir)
images_enc = image_repository.scan(config.private_key)
hash_enc = {image["hash"] for image in images_enc}
image_repository.decode_all(config.private_key)
images_dec = image_repository.scan(config.private_key, calc_hash=True)
hash_dec = {image["hash"] for image in images_dec}
image_repository.check_encryption(config.private_key)
images_reenc = image_repository.scan(config.private_key)
hash_reenc = {image["hash"] for image in images_reenc}
self.assertEqual(hash_enc, hash_dec)
self.assertEqual(hash_enc, hash_reenc)
def test_decrypt_rejects_wrong_passphrase(self) -> None:
"""Verify decryption fails when given a different passphrase."""
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(ValueError, "Invalid padding bytes"):
assets = Path(__file__).resolve().parents[1] / "assets"
shutil.copytree(assets / "corrupt", Path(temporary_directory) / "corrupt")
image_root = Path(temporary_directory) / "corrupt"
# Generate 4096-bit RSA private key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096
)
private_key_file = image_root / "private_key.pem"
# Save to PEM file
with open(private_key_file, "wb") as f:
f.write(
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
)
ImageRepository(image_root).decode_all(private_key_file)
def test_decrypt_rejects_invalid_or_truncated_ciphertext(self) -> None:
"""Verify malformed headers and incomplete ciphertext are rejected."""
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(ValueError, "Hash mismatch for"):
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "corrupt"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "corrupt" , config.img_dir)
with open(config.img_dir / "00001.jpg_enc", "r+b") as f:
f.seek(0, 2)
size = f.tell()
middle = size // 2
f.seek(middle)
byte = f.read(1)
corrupted = bytes([byte[0] ^ 0b00000011])
f.seek(middle)
f.write(corrupted)
ImageRepository(config.img_dir).decode_all(config.private_key)
def test_passphrase_formats(self) -> None:
"""Verify byte, literal, and passphrase-file inputs are read correctly."""
with TemporaryDirectory() as temporary_directory:
temporary_path = Path(temporary_directory)
passphrase_file = temporary_path / "passphrase.txt"
passphrase_file.write_bytes(b"test passphrase\r\nignored line")
encrypted_file = temporary_path / "encrypted.bin"
plaintext = b"passphrase format test"
manager = EncryptionManager()
manager.encrypt_data(plaintext, encrypted_file, b"test passphrase")
for passphrase in (
b"test passphrase",
"test passphrase",
"pass:test passphrase",
passphrase_file,
f"file:{passphrase_file}",
):
with self.subTest(passphrase=type(passphrase).__name__):
decrypted, _ = manager.decrypt(encrypted_file, None, passphrase)
self.assertEqual(decrypted, plaintext)
def test_naming_table_round_trip_and_malformed_lines(self) -> None:
"""Verify naming-table entries round-trip and malformed lines are handled."""
with TemporaryDirectory() as temporary_directory:
naming_table_path = Path(temporary_directory) / "naming_table.enc"
passphrase = "pass:test passphrase"
manager = EncryptionManager()
naming_table = [
FileInfo("image one.jpg", "00001.jpg_enc", "hash-one"),
FileInfo("image-two.jpg", "00002.jpg_enc", "hash-two"),
]
manager.store_naming_table(naming_table, naming_table_path, passphrase)
self.assertEqual(
manager.load_naming_table(naming_table_path, passphrase),
naming_table,
)
manager.encrypt_data(
b"\nmalformed line\nimage.jpg;00003.jpg_enc;hash-three\n",
naming_table_path,
passphrase,
)
self.assertEqual(
manager.load_naming_table(naming_table_path, passphrase),
[FileInfo("image.jpg", "00003.jpg_enc", "hash-three")],
)
def test_load_naming_table_missing_file(self) -> None:
"""Verify a missing naming table loads as an empty list."""
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(FileNotFoundError, "No naming table found"):
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "corrupt"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "corrupt", config.img_dir)
os.remove(config.img_dir / "naming_table.enc")
image_repository = ImageRepository(config.img_dir)
image_repository.decode_all(config.private_key)
def test_naming_table_file_operations_remove_source_after_success(self) -> None:
"""Verify file conversion removes its source only after a successful operation."""
with TemporaryDirectory() as temporary_directory:
directory = Path(temporary_directory)
source_path = directory / "naming_table.dec"
encrypted_path = directory / "naming_table.enc"
decrypted_path = directory / "decrypted.dec"
passphrase = "pass:test passphrase"
manager = EncryptionManager()
source_content = b"image.jpg;00001.jpg_enc;hash\n"
source_path.write_bytes(source_content)
manager.encrypt_naming_table_file(
source_path, encrypted_path, passphrase
)
self.assertFalse(source_path.exists())
self.assertTrue(encrypted_path.exists())
manager.decrypt_naming_table_file(
encrypted_path, decrypted_path, passphrase
)
self.assertFalse(encrypted_path.exists())
self.assertEqual(decrypted_path.read_bytes(), source_content)
invalid_source = directory / "invalid.enc"
invalid_destination = directory / "invalid.dec"
invalid_source.write_bytes(b"invalid ciphertext")
with self.assertRaisesRegex(ValueError, "Invalid or truncated"):
manager.decrypt_naming_table_file(
invalid_source, invalid_destination, passphrase
)
self.assertTrue(invalid_source.exists())
self.assertFalse(invalid_destination.exists())
def test_naming_table_file_operations_reject_same_source_and_destination(self) -> None:
"""Verify naming-table file conversion rejects identical paths."""
with TemporaryDirectory() as temporary_directory:
source_path = Path(temporary_directory) / "naming_table"
source_content = b"naming-table content"
source_path.write_bytes(source_content)
manager = EncryptionManager()
with self.assertRaisesRegex(ValueError, "must be different"):
manager.encrypt_naming_table_file(
source_path, source_path, "pass:test passphrase"
)
with self.assertRaisesRegex(ValueError, "must be different"):
manager.decrypt_naming_table_file(
source_path, source_path, "pass:test passphrase"
)
self.assertEqual(source_path.read_bytes(), source_content)
@@ -0,0 +1,387 @@
import random
import tkinter as tk
import unittest
import xml.etree.ElementTree as ET
from pathlib import Path
from tempfile import TemporaryDirectory
from wallpaper_changer.argument_parser import parse_args
from wallpaper_changer.config import Config
from wallpaper_changer.monitor_manager import Monitor, MonitorManager, ScreenLayout
class MonitorManagerTests(unittest.TestCase):
def parse_args(self, *arguments: str):
return parse_args(list(arguments))
def test_screen_layout_properties(self) -> None:
"""Verify monitor count and combined aspect ratio for a layout."""
for max_monitors in range(1, 5):
x_coord = 0
layout_monitors = []
for _ in range(0, max_monitors):
layout_monitors.append(Monitor(1920, 1080, x_coord,set("TestMon")))
x_coord+=1920
monitors = ScreenLayout(tuple(layout_monitors))
self.assertEqual(monitors.monitor_count, max_monitors)
self.assertEqual(monitors.screen_aspect_ratio, max_monitors * 1920 / 1080)
x_coord=0
for monitor in monitors.monitors:
self.assertEqual(monitor.width, 1920)
self.assertEqual(monitor.height, 1080)
self.assertEqual(monitor.x_coord, x_coord)
x_coord+=1920
def test_headless_mode_reads_correct_config(self) -> None:
"""Verify server dimensions load from the default monitor config."""
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--headless")
config = Config.load(args)
for file in (assets/"monitors").glob("monitors_[1-3]mon.xml"):
monitors = MonitorManager().get_screensize(config.headless_mode,
file)
monitor_number = int(file.name.split("_")[1].replace("mon.xml", ""))
self.assertEqual(monitors.monitor_count, monitor_number)
self.assertEqual(monitors.screen_aspect_ratio, monitor_number * 1920 / 1080)
x_coord=0
for monitor in monitors.monitors:
self.assertEqual(monitor.width, 1920)
self.assertEqual(monitor.height, 1080)
self.assertEqual(monitor.x_coord, x_coord)
x_coord+=1920
def test_monitor_manager_uses_correct_config(self) -> None:
"""Verify incomplete, non-positive, or inconsistent dimensions are rejected."""
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args()
config = Config.load(args)
file = assets / "monitors" / "monitors_2mon.xml"
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-eDP-1"]
create_drm_root(drm_root,cards)
monitors = MonitorManager().get_screensize(config.headless_mode,file,
drm_root=drm_root)
self.assertEqual(monitors.monitor_count, 2)
self.assertEqual(monitors.screen_aspect_ratio, 2 * 1920 / 1080)
x_coord=0
for monitor in monitors.monitors:
self.assertEqual(monitor.width, 1920)
self.assertEqual(monitor.height, 1080)
self.assertEqual(monitor.x_coord, x_coord)
x_coord+=1920
def test_monitor_manager_rejects_config_with_too_many_monitors(self) -> None:
"""Verify incomplete, non-positive, or inconsistent dimensions are rejected."""
assets = Path(__file__).resolve().parents[1] / "assets"
monitor_file = assets / "monitors" / "monitors_3mon.xml"
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(RuntimeError, "No matching monitor configuration found"):
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-eDP-1"]
create_drm_root(drm_root,cards)
MonitorManager().get_screensize(
False,
monitor_file,
drm_root=drm_root
)
def test_monitor_manager_uses_correct_config_with_multi_monitor_config_xml(self) -> None:
"""Verify incomplete, non-positive, or inconsistent dimensions are rejected."""
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args()
config = Config.load(args)
file = assets / "monitors" / "monitors_all.xml"
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-eDP-1"]
create_drm_root(drm_root,cards)
monitors = MonitorManager().get_screensize(config.headless_mode,file,
drm_root=drm_root)
self.assertEqual(monitors.monitor_count, 2)
self.assertEqual(monitors.screen_aspect_ratio, 2 * 1920 / 1080)
x_coord=0
for monitor in monitors.monitors:
self.assertEqual(monitor.width, 1920)
self.assertEqual(monitor.height, 1080)
self.assertEqual(monitor.x_coord, x_coord)
x_coord+=1920
def test_server_layout_rejects_missing_or_invalid_dimensions(self) -> None:
"""Verify incomplete, non-positive, or inconsistent dimensions are rejected."""
with TemporaryDirectory() as temporary_directory:
monitor_file = Path(__file__).resolve().parents[1] / "assets" / "monitors" / "monitors_2mon.xml"
args = self.parse_args()
config = Config.load(args)
for file in create_faulty_xmls(monitor_file, Path(temporary_directory)):
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1","card1-eDP-1"]
create_drm_root(drm_root,cards)
field = file.stem.rsplit("_", 3)[1]
if file.name.endswith("_empty.xml") and field != "y":
with self.assertRaisesRegex(ValueError, f"Missing <{field}>"):
MonitorManager().get_screensize(
config.headless_mode,
file,
drm_root=drm_root,
)
elif field in {"width", "height"}:
with self.assertRaisesRegex(
RuntimeError,
f"No matching monitor configuration found in {file}",
):
MonitorManager().get_screensize(
config.headless_mode,
file,
drm_root=drm_root,
)
else:
monitors = MonitorManager().get_screensize(
config.headless_mode,
file,
drm_root=drm_root,
)
self.assertEqual(monitors.monitor_count, 2)
def test_detect_single_connected_monitor_actual_monitor(self) -> None:
"""Verify a single enabled connector produces a one-monitor layout."""
args = self.parse_args()
config = Config.load(args)
monitors = MonitorManager().get_screensize(
config.headless_mode,
config.monitor_file,
)
root = tk.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
self.assertEqual(monitors.monitor_count, 1)
self.assertEqual(monitors.screen_aspect_ratio, width / height)
self.assertEqual(monitors.monitors[0].width, width)
self.assertEqual(monitors.monitors[0].height, height)
self.assertEqual(monitors.monitors[0].x_coord, 0)
def test_detect_single_connected_monitor_patched_monitor(self) -> None:
"""Verify one enabled connector reports its virtual 1920x1080 size."""
assets = Path(__file__).resolve().parents[1] / "assets"
monitor_file = assets / "monitors" / "monitors_1mon.xml"
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1"]
create_drm_root(drm_root,cards)
monitors = MonitorManager().get_screensize(
False,
monitor_file,
drm_root=drm_root,
)
self.assertEqual(monitors.monitor_count, 1)
self.assertEqual(monitors.screen_aspect_ratio, 1920 / 1080)
self.assertEqual(monitors.monitors[0].width, 1920)
self.assertEqual(monitors.monitors[0].height, 1080)
self.assertEqual(monitors.monitors[0].x_coord, 0)
def test_detect_multiple_monitors_from_xml_layout(self) -> None:
"""Verify two or more connected monitors map to their XML positions and sizes."""
assets = Path(__file__).resolve().parents[1] / "assets"
monitor_file = assets / "monitors" / "monitors_3mon.xml"
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-HDMI-A-2", "card1-eDP-1"]
create_drm_root(drm_root,cards)
monitors = MonitorManager().get_screensize(
False,
monitor_file,
drm_root=drm_root,
)
self.assertEqual(monitors.monitor_count, 3)
self.assertEqual(monitors.screen_aspect_ratio, 3*1920 / 1080)
x=0
for monitor in monitors.monitors:
self.assertEqual(monitor.width, 1920)
self.assertEqual(monitor.height, 1080)
self.assertEqual(monitor.x_coord, x)
x+=1920
def test_ignore_disconnected_and_disabled_connectors(self) -> None:
"""Verify disconnected or disabled displays are excluded from layouts."""
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-HDMI-A-2", "card1-eDP-1"]
stati = ["enabled", "disabled", "disabled"]
connections = ["connected", "disconnected", "disconnected"]
create_drm_root(drm_root,cards,stati,connections)
drm_connectors = MonitorManager()._connected_drm_connectors(drm_root,"")
self.assertEqual(len(drm_connectors),1)
def test_laptop_monitor_respects_lid_state_open(self) -> None:
"""Verify the internal display is included only when the lid is open."""
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-eDP-1"]
lid_state_path_str = temporary_directory + "/proc/acpi/button/lid/LID*/state"
create_drm_root(drm_root,cards,lid_state_path_str=lid_state_path_str)
drm_connectors = MonitorManager()._connected_drm_connectors(drm_root,lid_state_path_str)
self.assertEqual(len(drm_connectors),2)
def test_laptop_monitor_respects_lid_state_closed(self) -> None:
"""Verify the internal display is included only when the lid is open."""
with TemporaryDirectory() as temporary_directory:
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-eDP-1"]
lid_state_path_str = temporary_directory + "/proc/acpi/button/lid/LID*/state"
create_drm_root(drm_root,cards,
lid_state_path_str=lid_state_path_str, lid_state="Closed")
drm_connectors = MonitorManager()._connected_drm_connectors(drm_root,lid_state_path_str)
self.assertEqual(len(drm_connectors),1)
def test_reject_no_enabled_monitors(self) -> None:
"""Verify no active displays raises an error."""
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(RuntimeError, "No enabled monitors found"):
assets = Path(__file__).resolve().parents[1] / "assets"
monitor_file = assets / "monitors" / "monitors_all.xml"
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1", "card1-HDMI-A-2", "card1-eDP-1"]
stati = ["disabled", "disabled", "enabled"]
connections = ["disconnected", "disconnected", "connected"]
lid_state_path_str = temporary_directory + "/proc/acpi/button/lid/LID*/state"
create_drm_root(drm_root,cards,stati,connections,lid_state_path_str,"Closed")
MonitorManager().get_screensize(
False,
monitor_file,
drm_root=drm_root,
lid_state=lid_state_path_str,
)
def test_reject_unmatched_monitor_configuration(self) -> None:
"""Verify active displays without a matching XML layout raise an error."""
assets = Path(__file__).resolve().parents[1] / "assets"
monitor_file = assets / "monitors" / "monitors_3mon.xml"
with TemporaryDirectory() as temporary_directory, \
self.assertRaisesRegex(RuntimeError, "No matching monitor configuration found"):
drm_root = Path(temporary_directory)
cards = ["card1-HDMI-A-1","card1-eDP-1"]
create_drm_root(drm_root,cards)
MonitorManager().get_screensize(
False,
monitor_file,
drm_root=drm_root
)
def test_reject_malformed_monitor_configuration(self) -> None:
"""Verify malformed XML or missing mode values are reported."""
with TemporaryDirectory() as temporary_directory:
monitor_file = Path(temporary_directory) / "monitors.xml"
manager = MonitorManager()
monitor_file.write_text("<monitors><configuration>")
with self.subTest("malformed XML"), \
self.assertRaises(ET.ParseError):
manager.get_screensize(True, monitor_file)
monitor_file.write_text(
"<monitors><configuration><logicalmonitor><x>0</x>"
"<monitor><mode><height>1080</height></mode></monitor>"
"</logicalmonitor></configuration></monitors>"
)
with self.subTest("missing mode width"), \
self.assertRaisesRegex(ValueError, "Missing <width>"):
manager.get_screensize(True, monitor_file)
def create_faulty_xmls(
source_file: Path,
temp_dir: Path,
) -> list[Path]:
"""Generate XML files with exactly one faulty x/y/width/height value."""
values = {
"x": [-3840, -1920, -1080, -500, 500, 1080, 1920, 3840, 5760],
"y": [-2160, -1080, -500, 500, 1080, 2160],
"width": [1280, 1600, 1920, 2560, 3440, 3840, 5120],
"height": [720, 900, 1080, 1440, 2160],
}
generated_files = []
original_tree = ET.parse(source_file)
original_root = original_tree.getroot()
for tag, candidates in values.items():
elements = list(original_root.iter(tag))
for index, element in enumerate(elements):
original_value = (element.text or "").strip()
for fault_type in ("empty", "random"):
tree = ET.parse(source_file)
root = tree.getroot()
target = list(root.iter(tag))[index]
if fault_type == "empty":
target.text = ""
else:
available = [
value for value in candidates
if str(value) != original_value
]
target.text = str(random.choice(available))
output_file = temp_dir / (
f"{source_file.stem}_{tag}_{index}_{fault_type}.xml"
)
tree.write(
output_file,
encoding="utf-8",
xml_declaration=True,
)
generated_files.append(output_file)
return generated_files
def create_drm_root(
drm_root: Path,
cards: list[str],
stati: list[str] | None = None,
connections: list[str] | None = None,
lid_state_path_str: str | None = None,
lid_state: str = "Open",
):
if stati is None:
stati = ["enabled"] * len(cards)
if connections is None:
connections = ["connected"]*len(cards)
if lid_state_path_str is None:
lid_state_path_str = str(drm_root) + "/proc/acpi/button/lid/LID*/state"
(drm_root / "card1").mkdir()
for card, status, connected in zip(cards,stati,connections):
connector = drm_root / card
connector.mkdir()
(connector / "status").write_text(f"{connected}\n")
(connector / "enabled").write_text(f"{status}\n")
size_file = (
connector / "device/device/graphics/fb0/virtual_size"
)
size_file.parent.mkdir(parents=True)
size_file.write_text("1920,1080")
if lid_state_path_str:
lid_state_file_path = Path(lid_state_path_str.replace("*","0"))
lid_state_file_path.parent.mkdir(parents=True)
lid_state_file_path.write_text(f"state: {lid_state}\n")
@@ -0,0 +1,69 @@
import subprocess
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import call, patch
from wallpaper_changer.wallpaper_setter import WallpaperSetter
class WallpaperSetterTests(unittest.TestCase):
def test_set_ubuntu_updates_light_dark_and_layout_settings(self) -> None:
with TemporaryDirectory() as directory:
wallpaper = Path(directory) / "wallpaper.jpg"
wallpaper.write_bytes(b"placeholder")
uri = wallpaper.resolve().as_uri()
with patch("wallpaper_changer.wallpaper_setter.subprocess.run") as run:
WallpaperSetter().set_ubuntu(wallpaper)
self.assertEqual(run.call_args_list, [
call(
["gsettings", "set", "org.gnome.desktop.background",
"picture-uri", uri],
check=True,
),
call(
["gsettings", "set", "org.gnome.desktop.background",
"picture-uri-dark", uri],
check=True,
),
call(
["gsettings", "set", "org.gnome.desktop.background",
"picture-options", "spanned"],
check=True,
),
])
def test_set_ubuntu_rejects_missing_wallpaper(self) -> None:
"""Verify a missing wallpaper path raises FileNotFoundError."""
wallpaper = Path("wallpaper.jpg")
with patch("wallpaper_changer.wallpaper_setter.subprocess.run"), \
self.assertRaises(FileNotFoundError):
WallpaperSetter().set_ubuntu(wallpaper)
def test_set_ubuntu_surfaces_gsettings_failure(self) -> None:
"""Verify failures from gsettings are propagated to the caller."""
with TemporaryDirectory() as directory:
wallpaper = Path(directory) / "wallpaper.jpg"
wallpaper.write_bytes(b"placeholder")
command = [
"gsettings",
"set",
"org.gnome.desktop.background",
"picture-uri",
wallpaper.resolve().as_uri(),
]
with patch(
"wallpaper_changer.wallpaper_setter.subprocess.run",
side_effect=subprocess.CalledProcessError(1, command),
) as run, self.assertRaises(subprocess.CalledProcessError) as error:
WallpaperSetter().set_ubuntu(wallpaper)
self.assertEqual(error.exception.returncode, 1)
run.assert_called_once_with(command, check=True)
def test_set_gnome_delegates_to_set_ubuntu(self) -> None:
"""Verify the GNOME entry point delegates to the Ubuntu setter."""
self.skipTest("TODO: assert delegation")
@@ -0,0 +1,380 @@
import os
import shutil
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
from PIL import Image, UnidentifiedImageError
from wallpaper_changer.argument_parser import parse_args
from wallpaper_changer.config import Config
from wallpaper_changer.image_repository import ImageRepository
from wallpaper_changer.monitor_manager import Monitor, ScreenLayout
from wallpaper_changer.wallpaper_builder import WallpaperBuilder
class ImageRepositoryTests(unittest.TestCase):
def parse_args(self, *arguments: str):
return parse_args(list(arguments))
def test_build_wallpaper(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors, config.private_key, config.wallpaper_dir)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
def test_build_wallpaper_encoded(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "corrupt"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "corrupt", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors, config.private_key, config.wallpaper_dir)
self.assertEqual( sum(1 for image in images if image["file"].suffix == ".jpg_enc"), 8)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
def test_build_wallpaper_search(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"-s", "Hochschwab",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0, set("TestMon")),))
_,images_used = WallpaperBuilder().build(images,
monitors,
config.private_key,
config.wallpaper_dir,
search_terms_monitor=args.search)
self.assertTrue(images_used[0] == "Foto_Berg_Hochschwab01.jpg")
def test_build_wallpaper_decode_and_leave(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "corrupt"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "corrupt", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors,
config.private_key, config.wallpaper_dir,
decode_and_leave=True)
images = ImageRepository(config.img_dir).scan(config.private_key)
self.assertEqual( sum(1 for image in images if image["file"].suffix == ".jpg"), 1)
self.assertEqual( sum(1 for image in images if image["file"].suffix == ".jpg_enc"), 8)
def test_build_wallpaper_left(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
img_folder = image_root / "Desktop1920x1080"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
img_folder.mkdir(parents=True, exist_ok=True)
shutil.copy(
assets / "images" /"half-white-half-black.jpg",
img_folder / "Foto_Left_WhiteBlack.jpg",
)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors,
config.private_key,
config.wallpaper_dir)
wallpaper_path = config.wallpaper_dir / "wallpaper.jpg"
image = Image.open(wallpaper_path).convert("L")
total_pixels = int(np.asarray(image).sum())
self.assertTrue(wallpaper_path.exists())
self.assertGreater(total_pixels , 10000000)
def test_build_wallpaper_right(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
img_folder = image_root / "Desktop1920x1080"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
img_folder.mkdir(parents=True, exist_ok=True)
shutil.copy(
assets / "images" /"half-white-half-black.jpg",
img_folder / "Foto_Right_WhiteBlack.jpg",
)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors,
config.private_key,
config.wallpaper_dir)
wallpaper_path = config.wallpaper_dir / "wallpaper.jpg"
image = Image.open(wallpaper_path)
image = Image.open(wallpaper_path).convert("L")
total_pixels = int(np.asarray(image).sum())
self.assertTrue(wallpaper_path.exists())
self.assertLess(total_pixels , 10000000)
class WallpaperBuilderEdgeCaseTests(unittest.TestCase):
def parse_args(self, *arguments: str):
return parse_args(list(arguments))
def test_build_rejects_empty_images_and_monitor_layouts(self) -> None:
"""Verify building rejects empty images and layouts without monitors."""
self.assertTrue("TODO: assert both invalid-input errors")
def test_build_rejects_empty_monitor_layouts(self) -> None:
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(0,0,0,set("WrongLayout")),))
try:
WallpaperBuilder().build(images, monitors, config.private_key, config.wallpaper_dir)
except ValueError as e:
self.assertEqual("Monitor 0 has no dimensions", str(e))
def test_build_ignores_search_term_when_no_candidates_remain(self) -> None:
"""Verify building reports when exclusions leave no eligible image."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"-s", "Tal",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,args.search,"")
self.assertEqual(len(candidates),8)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir, search_terms_monitor=args.search)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
def test_build_can_handle_multiple_search_terms(self) -> None:
"""Verify building reports when exclusions leave no eligible image."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"-s", "Tal", "See",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
shutil.move(config.img_dir / "Foto_Berg01.jpg" , config.img_dir / "Foto_Tal_Hügel_See01.jpg")
shutil.move(config.img_dir / "Foto_Berg03.jpg" , config.img_dir / "Foto_Tal_Hügel_Meer01.jpg")
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
_,image_list = WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir, search_terms_gen=args.search)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
self.assertTrue("Tal" in image_list[0] and "See" in image_list[0])
def test_build_can_handle_multiple_monitor_search_terms(self) -> None:
"""Verify separate search terms are assigned to their corresponding monitors."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--search-mon", "See", "Meer",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
shutil.move(config.img_dir / "Foto_Berg01.jpg" , config.img_dir / "Foto_Tal_Hügel_See01.jpg")
shutil.move(config.img_dir / "Foto_Berg03.jpg" , config.img_dir / "Foto_Tal_Hügel_Meer01.jpg")
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),
Monitor(1920, 1080,1920,set("TestMon2")),))
_,image_list = WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir, search_terms_monitor=args.search_mon)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
self.assertTrue("Foto_Tal_Hügel_See01.jpg" in image_list and "Foto_Tal_Hügel_Meer01.jpg" in image_list)
def test_build_raises_when_no_candidates_remain_after_exclusions(self) -> None:
"""Verify building reports when exclusions leave no eligible image."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--exclude", "Berg",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,None,args.exclude)
self.assertEqual(len(candidates),0)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
try:
WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir,exclude=args.exclude)
except ValueError as error:
self.assertEqual(str(error),
f"No images left after excluding {args.exclude}")
def test_search_matching_and_exclusion_are_case_insensitive(self) -> None:
"""Verify building reports when exclusions leave no eligible image."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--search", "gÖller",
"--exclude", "HOCHSCHWAB",
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,None,args.exclude)
self.assertEqual(len(candidates),7)
candidates = WallpaperBuilder().find_candidates(images, None,args.search,())
self.assertEqual(len(candidates),2)
def test_build_creates_custom_output_parent_directory(self) -> None:
"""Verify a custom output path is created along with missing parent folders."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root / "wallpaper" / "custom"),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
WallpaperBuilder().build(images, monitors, config.private_key, config.wallpaper_dir)
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
def test_build_creates_correct_canvas_for_multiple_monitors(self) -> None:
"""Verify multiple monitor images are placed in one canvas with expected dimensions."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
shutil.copytree(assets / "Desktop1920x1080", config.img_dir)
images = ImageRepository(config.img_dir).scan(config.private_key)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),
Monitor(1920, 1080,1920,set("TestMon1")),))
WallpaperBuilder().build(images, monitors, config.private_key, config.wallpaper_dir)
image = Image.open(config.wallpaper_dir/"wallpaper.jpg")
self.assertTrue((config.wallpaper_dir/"wallpaper.jpg").exists())
self.assertTrue(image.size == (3840, 1080))
def test_build_surfaces_image_decode_errors_empty_file(self) -> None:
"""Verify unreadable or undecryptable selected images produce an explicit error."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
(image_root / "Desktop1920x1080" ).mkdir()
iamge_path = image_root / "Desktop1920x1080" / "faulty.jpg"
iamge_path.touch()
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,None,args.exclude)
self.assertEqual(len(candidates),1)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
try:
WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir,exclude=args.exclude)
except UnidentifiedImageError as error:
self.assertTrue(
"cannot identify image file" in str(error))
def test_build_surfaces_image_decode_errors_corrupt_file_header(self) -> None:
"""Verify unreadable or undecryptable selected images produce an explicit error."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
(image_root / "Desktop1920x1080" ).mkdir()
shutil.copy(assets / "Desktop1920x1080" / "Foto_Berg01.jpg", config.img_dir/"Foto_Berg01.jpg")
# Overwrite the first 3 bytes with null bytes
with open( config.img_dir / "Foto_Berg01.jpg", "r+b") as file:
file.write(b"\x00\x00\x00")
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,None,args.exclude)
self.assertEqual(len(candidates),1)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
try:
WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir,exclude=args.exclude)
except UnidentifiedImageError as error:
self.assertTrue(
"cannot identify image file" in str(error))
def test_build_surfaces_image_decode_errors_corrupt_file_tail(self) -> None:
"""Verify unreadable or undecryptable selected images produce an explicit error."""
with TemporaryDirectory() as temporary_directory:
image_root = Path(temporary_directory)
assets = Path(__file__).resolve().parents[1] / "assets"
args = self.parse_args("--conf-dir", str(image_root),
"--folder", str(image_root / "Desktop1920x1080"),
"--private-key", str(assets / "test_private_key.pem"))
config = Config.load(args)
(image_root / "Desktop1920x1080" ).mkdir()
shutil.copy(assets / "Desktop1920x1080" / "Foto_Berg01.jpg", config.img_dir/"Foto_Berg01.jpg")
# Get file size
size = os.path.getsize(config.img_dir/"Foto_Berg01.jpg")
# Remove the last 50 bytes
os.truncate( config.img_dir/"Foto_Berg01.jpg", size - 50)
images = ImageRepository(config.img_dir).scan(config.private_key)
candidates = WallpaperBuilder().find_candidates(images, None,None,args.exclude)
self.assertEqual(len(candidates),1)
monitors = ScreenLayout((Monitor(1920, 1080,0,set("TestMon1")),))
try:
WallpaperBuilder().build(images, monitors, config.private_key,
config.wallpaper_dir,exclude=args.exclude)
except OSError as error:
self.assertTrue(
"image file is truncated" in str(error))
if __name__ == "__main__":
unittest.main()