Testing the Helper.
All checks were successful
continuous-integration/drone/push Build is passing

We're now getting to 88% coverage on python. I don't think I can get it much higher between the statements that pytest doesn't count,
the ones which aren't easy to reproduce in test env (eg no internet connection), and the ones essential to the app's startup workflow.
This commit is contained in:
Adsooi 2024-09-23 05:58:29 +02:00
parent 5bdf81b2ed
commit 84a65cd1fc
Signed by: Ad5001
GPG key ID: EF45F9C6AFE20160
6 changed files with 201 additions and 42 deletions

View file

@ -36,7 +36,8 @@ tempdir = TemporaryDirectory()
tmpfile = path.join(tempdir.name, 'graph.png')
pwd = getcwd()
chdir(path.dirname(path.realpath(__file__)))
logarithmplotter_path = path.dirname(path.realpath(__file__))
chdir(logarithmplotter_path)
if path.realpath(path.join(getcwd(), "..")) not in sys_path:
sys_path.append(path.realpath(path.join(getcwd(), "..")))
@ -91,7 +92,7 @@ def get_platform_qt_style(os) -> str:
def register_icon_directories() -> None:
icon_fallbacks = QIcon.fallbackSearchPaths()
base_icon_path = path.join(getcwd(), "qml", "eu", "ad5001", "LogarithmPlotter", "icons")
base_icon_path = path.join(logarithmplotter_path, "qml", "eu", "ad5001", "LogarithmPlotter", "icons")
paths = [["common"], ["objects"], ["history"], ["settings"], ["settings", "custom"]]
for p in paths:
icon_fallbacks.append(path.realpath(path.join(base_icon_path, *p)))
@ -106,7 +107,7 @@ def create_qapp() -> QApplication:
app.setDesktopFileName("eu.ad5001.LogarithmPlotter")
app.setOrganizationName("Ad5001")
app.styleHints().setShowShortcutsInContextMenus(True)
app.setWindowIcon(QIcon(path.realpath(path.join(getcwd(), "logarithmplotter.svg"))))
app.setWindowIcon(QIcon(path.realpath(path.join(logarithmplotter_path, "logarithmplotter.svg"))))
return app
@ -115,10 +116,12 @@ def install_translation(app: QApplication) -> QTranslator:
translator = QTranslator()
# Check if lang is forced.
forcedlang = [p for p in argv if p[:7] == "--lang="]
i18n_path = path.realpath(path.join(logarithmplotter_path, "i18n"))
locale = QLocale(forcedlang[0][7:]) if len(forcedlang) > 0 else QLocale()
if not translator.load(locale, "lp", "_", path.realpath(path.join(getcwd(), "i18n"))):
if not translator.load(locale, "lp", "_", i18n_path):
# Load default translation
translator.load(QLocale("en"), "lp", "_", path.realpath(path.join(getcwd(), "i18n")))
print("Loading default language en...")
translator.load(QLocale("en"), "lp", "_", i18n_path)
app.installTranslator(translator)
return translator
@ -133,8 +136,9 @@ def create_engine(helper: Helper, latex: Latex, dep_time: float) -> tuple[QQmlAp
engine.rootContext().setContextProperty("TestBuild", "--test-build" in argv)
engine.rootContext().setContextProperty("StartTime", dep_time)
engine.addImportPath(path.realpath(path.join(getcwd(), "qml")))
engine.load(path.realpath(path.join(getcwd(), "qml", "eu", "ad5001", "LogarithmPlotter", "LogarithmPlotter.qml")))
qml_path = path.realpath(path.join(logarithmplotter_path, "qml"))
engine.addImportPath(qml_path)
engine.load(path.join(qml_path, "eu", "ad5001", "LogarithmPlotter", "LogarithmPlotter.qml"))
return engine, js_globals

View file

@ -24,16 +24,29 @@ from PySide6 import __version__ as PySide6_version
from os import chdir, path
from json import loads
from sys import version as sys_version
from sys import version as sys_version, argv
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from LogarithmPlotter import __VERSION__
from LogarithmPlotter.util import config
SHOW_GUI_MESSAGES = "--test-build" not in argv
CHANGELOG_VERSION = __VERSION__
class InvalidFileException(Exception): pass
def show_message(msg: str) -> None:
"""
Shows a GUI message if GUI messages are enabled
"""
if SHOW_GUI_MESSAGES:
QMessageBox.warning(None, "LogarithmPlotter", msg, QMessageBox.OK)
else:
raise InvalidFileException(msg)
class ChangelogFetcher(QRunnable):
def __init__(self, helper):
@ -44,7 +57,7 @@ class ChangelogFetcher(QRunnable):
msg_text = "Unknown changelog error."
try:
# Fetching version
r = urlopen("https://api.ad5001.eu/changelog/logarithmplotter/?version=" + __VERSION__)
r = urlopen("https://api.ad5001.eu/changelog/logarithmplotter/?version=" + CHANGELOG_VERSION)
lines = r.readlines()
r.close()
msg_text = "".join(map(lambda x: x.decode('utf-8'), lines)).strip()
@ -53,21 +66,16 @@ class ChangelogFetcher(QRunnable):
str(e.code))
except URLError as e:
msg_text = QCoreApplication.translate("changelog", "Could not fetch update: {}.").format(str(e.reason))
self.helper.gotChangelog.emit(msg_text)
self.helper.changelogFetched.emit(msg_text)
class Helper(QObject):
changelogFetched = Signal(str)
gotChangelog = Signal(str)
def __init__(self, cwd: str, tmpfile: str):
QObject.__init__(self)
self.cwd = cwd
self.tmpfile = tmpfile
self.gotChangelog.connect(self.fetched)
def fetched(self, changelog: str):
self.changelogFetched.emit(changelog)
@Slot(str, str)
def write(self, filename, filedata):
@ -93,20 +101,19 @@ class Helper(QObject):
if data[:5] == "LPFv1":
# V1 version of the file
data = data[5:]
elif data[0] == "{" and "type" in loads(data) and loads(data)["type"] == "logplotv1":
pass
elif data[:3] == "LPF":
# More recent version of LogarithmPlotter file, but incompatible with the current format
msg = QCoreApplication.translate("This file was created by a more recent version of LogarithmPlotter and cannot be backloaded in LogarithmPlotter v{}.\nPlease update LogarithmPlotter to open this file.")
msg = QCoreApplication.translate('main',
"This file was created by a more recent version of LogarithmPlotter and cannot be backloaded in LogarithmPlotter v{}.\nPlease update LogarithmPlotter to open this file.")
raise InvalidFileException(msg.format(__VERSION__))
else:
raise Exception("Invalid LogarithmPlotter file.")
except Exception as e: # If file can't be loaded
raise InvalidFileException("Invalid LogarithmPlotter file.")
except InvalidFileException as e: # If file can't be loaded
msg = QCoreApplication.translate('main', 'Could not open file "{}":\n{}')
QMessageBox.warning(None, 'LogarithmPlotter', msg.format(filename, e), QMessageBox.Ok) # Cannot parse file
show_message(msg.format(filename, e)) # Cannot parse file
else:
msg = QCoreApplication.translate('main', 'Could not open file: "{}"\nFile does not exist.')
QMessageBox.warning(None, 'LogarithmPlotter', msg.format(filename), QMessageBox.Ok) # Cannot parse file
show_message(msg.format(filename)) # Cannot parse file
try:
chdir(path.dirname(path.realpath(__file__)))
except NotADirectoryError as e:
@ -130,31 +137,27 @@ class Helper(QObject):
@Slot(str, result=str)
def getSetting(self, namespace):
return config.getSetting(namespace)
return str(config.getSetting(namespace))
@Slot(str, result=float)
def getSettingInt(self, namespace):
return config.getSetting(namespace)
return float(config.getSetting(namespace))
@Slot(str, result=bool)
def getSettingBool(self, namespace):
return config.getSetting(namespace)
return bool(config.getSetting(namespace))
@Slot(str, str)
def setSetting(self, namespace, value):
return config.setSetting(namespace, value)
return config.setSetting(namespace, str(value))
@Slot(str, bool)
def setSettingBool(self, namespace, value):
return config.setSetting(namespace, value)
return config.setSetting(namespace, bool(value))
@Slot(str, float)
def setSettingInt(self, namespace, value):
return config.setSetting(namespace, value)
@Slot(str)
def setLanguage(self, new_lang):
config.setSetting("language", new_lang)
return config.setSetting(namespace, float(value))
@Slot(result=str)
def getDebugInfos(self):
@ -167,7 +170,6 @@ class Helper(QObject):
@Slot()
def fetchChangelog(self):
changelog_cache_path = path.join(path.dirname(path.realpath(__file__)), "CHANGELOG.md")
print(changelog_cache_path)
if path.exists(changelog_cache_path):
# We have a cached version of the changelog, for env that don't have access to the internet.
f = open(changelog_cache_path);

View file

@ -89,3 +89,4 @@ def check_for_updates(current_version, window):
runnable = UpdateCheckerRunnable(current_version, update_info)
QThreadPool.globalInstance().start(runnable)
return update_info