Removed deprecated test, new location for tests, init gresource test

This commit is contained in:
Vladyslav Hroshev
2025-04-05 22:21:06 +03:00
parent ad8f3fb9bd
commit 8da9b564be
7 changed files with 320 additions and 111 deletions

View File

@@ -3,6 +3,7 @@ from tempfile import gettempdir
# folder definitions
temp_folder = f"{gettempdir()}/marble"
temp_tests_folder = f"{temp_folder}/tests"
gdm_folder = "gdm"
gnome_folder = "gnome-shell"
temp_gnome_folder = f"{temp_folder}/{gnome_folder}"

View File

@@ -1,70 +0,0 @@
# TODO: Add more tests
import unittest
import os
import json
import shutil
from unittest.mock import patch
from . import config
from .theme import Theme
# folders
tests_folder = '.tests'
project_folder = '.'
class TestInstall(unittest.TestCase):
def setUp(self):
# Create necessary directories
os.makedirs(f"{project_folder}/{config.raw_theme_folder}/{config.gnome_folder}", exist_ok=True)
os.makedirs(f"{tests_folder}/.themes", exist_ok=True)
os.makedirs(f"{tests_folder}/.temp", exist_ok=True)
def tearDown(self):
# Clean up after tests
shutil.rmtree(tests_folder, ignore_errors=True)
@patch('scripts.utils.gnome.subprocess.check_output')
def test_install_theme(self, mock_check_output):
"""
Test if theme is installed correctly (colors are replaced)
"""
mock_check_output.return_value = 'GNOME Shell 47.0\n'
# folders
themes_folder = f"{tests_folder}/.themes"
temp_folder = f"{tests_folder}/.temp"
# colors from colors.json
colors_json = open(f"{project_folder}/{config.colors_json}")
colors = json.load(colors_json)
colors_json.close()
# create test theme
test_theme = Theme("gnome-shell", colors,
f"{project_folder}/{config.raw_theme_folder}/{config.gnome_folder}",
themes_folder, temp_folder,
mode='light', is_filled=True)
# install test theme
test_theme.install(120, 'test', 70)
# folder with installed theme (.tests/.themes/Marble-test-light/gnome-shell)
installed_theme = f"{themes_folder}/{os.listdir(themes_folder)[0]}/{config.gnome_folder}"
# check if files are installed
for file in os.listdir(installed_theme):
with open(f"{installed_theme}/{file}") as f:
read_file = f.read()
for color in colors["elements"]:
self.assertNotIn(color, read_file, msg=f"Color {color} is not replaced in {file}")
# delete test theme
del test_theme
shutil.rmtree(tests_folder)
if __name__ == '__main__':
unittest.main()

View File

@@ -13,6 +13,11 @@ class GresourceBackupNotFoundError(FileNotFoundError):
else:
super().__init__("Gresource backup file not found.")
class MissingDependencyError(Exception):
def __init__(self, dependency: str):
super().__init__(f"Missing required dependency: {dependency}")
self.dependency = dependency
class Gresource:
"""Handles the extraction and compilation of gresource files for GNOME Shell themes."""
@@ -27,38 +32,38 @@ class Gresource:
self.temp_folder = temp_folder
self.destination = destination
self.__temp_gresource = os.path.join(temp_folder, gresource_file)
self.__destination_gresource = os.path.join(destination, gresource_file)
self.__active_source_gresource = self.__destination_gresource
self.__backup_gresource = os.path.join(destination, f"{gresource_file}.backup")
self.__gresource_xml = os.path.join(temp_folder, f"{gresource_file}.xml")
self._temp_gresource = os.path.join(temp_folder, gresource_file)
self._destination_gresource = os.path.join(destination, gresource_file)
self._active_source_gresource = self._destination_gresource
self._backup_gresource = os.path.join(destination, f"{gresource_file}.backup")
self._gresource_xml = os.path.join(temp_folder, f"{gresource_file}.xml")
def use_backup_gresource(self):
if not os.path.exists(self.__backup_gresource):
raise GresourceBackupNotFoundError(self.__backup_gresource)
self.__active_source_gresource = self.__backup_gresource
if not os.path.exists(self._backup_gresource):
raise GresourceBackupNotFoundError(self._backup_gresource)
self._active_source_gresource = self._backup_gresource
def extract(self):
extract_line = Console.Line()
extract_line.update("Extracting gresource files...")
resources = self.__get_resources_list()
self.__extract_resources(resources)
resources = self._get_resources_list()
self._extract_resources(resources)
extract_line.success("Extracted gresource files.")
def __get_resources_list(self):
def _get_resources_list(self):
resources_list_response = subprocess.run(
["gresource", "list", self.__active_source_gresource],
["gresource", "list", self._active_source_gresource],
capture_output=True, text=True, check=False
)
if resources_list_response.stderr:
raise Exception(f"gresource could not process the theme file: {self.__active_source_gresource}")
raise Exception(f"gresource could not process the theme file: {self._active_source_gresource}")
return resources_list_response.stdout.strip().split("\n")
def __extract_resources(self, resources: list[str]):
def _extract_resources(self, resources: list[str]):
prefix = "/org/gnome/shell/theme/"
try:
for resource in resources:
@@ -68,38 +73,38 @@ class Gresource:
with open(output_path, 'wb') as f:
subprocess.run(
["gresource", "extract", self.__active_source_gresource, resource],
["gresource", "extract", self._active_source_gresource, resource],
stdout=f, check=True
)
except FileNotFoundError as e:
if "gresource" in str(e):
self.__raise_gresource_error(e)
self._raise_gresource_error(e)
raise
@staticmethod
def __raise_gresource_error(e: Exception):
def _raise_gresource_error(e: Exception):
print("Error: 'gresource' command not found.")
print("Please install the glib2-devel package:")
print(" - For Fedora/RHEL: sudo dnf install glib2-devel")
print(" - For Ubuntu/Debian: sudo apt install libglib2.0-dev")
print(" - For Arch: sudo pacman -S glib2-devel")
raise Exception("Missing required dependency: glib2-devel") from e
raise MissingDependencyError("glib2-devel") from e
def compile(self):
compile_line = Console.Line()
compile_line.update("Compiling gnome-shell theme...")
self.__create_gresource_xml()
self.__compile_resources()
self._create_gresource_xml()
self._compile_resources()
compile_line.success("Theme compiled.")
def __create_gresource_xml(self):
with open(self.__gresource_xml, 'w') as gresource_xml:
gresource_xml.write(self.__generate_gresource_xml())
def _create_gresource_xml(self):
with open(self._gresource_xml, 'w') as gresource_xml:
gresource_xml.write(self._generate_gresource_xml())
def __generate_gresource_xml(self):
files_to_include = self.__get_files_to_include()
def _generate_gresource_xml(self):
files_to_include = self._get_files_to_include()
nl = "\n" # fstring doesn't support newline character
return textwrap.dedent(f"""
<?xml version="1.0" encoding="UTF-8"?>
@@ -110,7 +115,7 @@ class Gresource:
</gresources>
""")
def __get_files_to_include(self):
def _get_files_to_include(self):
temp_path = Path(self.temp_folder)
return [
f"<file>{file.relative_to(temp_path)}</file>"
@@ -118,17 +123,17 @@ class Gresource:
if file.is_file()
]
def __compile_resources(self):
def _compile_resources(self):
try:
subprocess.run(["glib-compile-resources",
"--sourcedir", self.temp_folder,
"--target", self.__temp_gresource,
self.__gresource_xml
"--target", self._temp_gresource,
self._gresource_xml
],
cwd=self.temp_folder, check=True)
except FileNotFoundError as e:
if "glib-compile-resources" in str(e):
self.__raise_gresource_error(e)
self._raise_gresource_error(e)
raise
def backup(self):
@@ -136,19 +141,19 @@ class Gresource:
backup_line.update("Backing up gresource files...")
subprocess.run(["cp", "-aT",
self.__destination_gresource,
self.__backup_gresource],
self._destination_gresource,
self._backup_gresource],
check=True)
backup_line.success("Backed up gresource files.")
def restore(self):
if not os.path.exists(self.__backup_gresource):
raise GresourceBackupNotFoundError(self.__backup_gresource)
if not os.path.exists(self._backup_gresource):
raise GresourceBackupNotFoundError(self._backup_gresource)
subprocess.run(["sudo", "mv", "-f",
self.__backup_gresource,
self.__destination_gresource],
subprocess.run(["mv", "-f",
self._backup_gresource,
self._destination_gresource],
check=True)
@@ -156,9 +161,11 @@ class Gresource:
move_line = Console.Line()
move_line.update("Moving gresource files...")
subprocess.run(["sudo", "cp", "-f",
self.__temp_gresource,
self.__destination_gresource],
subprocess.run(["cp", "-f",
self._temp_gresource,
self._destination_gresource],
check=True)
subprocess.run(["chmod", "644", self._destination_gresource], check=True)
move_line.success("Moved gresource files.")