From ccddb068a670ceb607c9e034c4dfb0accdebf2e9 Mon Sep 17 00:00:00 2001 From: Ad5001 Date: Tue, 15 Oct 2024 18:06:24 +0200 Subject: [PATCH] Fixing tests for Promises (new ones need to be written) --- runtime-pyside6/.coverage | Bin 0 -> 53248 bytes .../LogarithmPlotter/util/promise.py | 22 +++-- runtime-pyside6/tests/test_helper.py | 83 ++++++++---------- runtime-pyside6/tests/test_latex.py | 10 +-- 4 files changed, 57 insertions(+), 58 deletions(-) create mode 100644 runtime-pyside6/.coverage diff --git a/runtime-pyside6/.coverage b/runtime-pyside6/.coverage new file mode 100644 index 0000000000000000000000000000000000000000..8eab2ed6efa5c8f1c8ebd2f83154347499e04eff GIT binary patch literal 53248 zcmeI4Uu+yl9mn^dZ*T99CykY!ToW=tsbkfDVxWm=B~q70q7X<+LtjwY?%j>;EqA-; z-95)fRM9m>k&s#m5aI#aClC+tzynD92`LpX1PM@t5J*rWifHpd2^B4hlm_#g{o}if z?W!+6tMPYrH?uoCGr!;OGryVHxxL+oA3E+vg3tRw(~0;8l|728D)(}(D2hejGJUhn zq#YwWpjhqM-)h%VroXUMW{)VP+|vsCT=@i>Dt)VbNAY5*X??l)oatCKI)M!YKmY_l zV0RPfJXA6(qoeARPee|&A)>&ki69BfAN};Pxs%8E$+`QEALB_HKUmCgD*wD# zos2W2(ju`EB?(lCa2Gt8gC9(bPw+s@i$Hia5hhw3bn6p^i8H4QW@ThVJu70HoS;UZ zVxKjX&^6_Od8(-92X(1^HE_Jzq6jCsvuY>vuyh+J4ds=v&l=J)yYqy{jO@(8fy>_!o z$RBSvTe5MeL?Sryw<@_+*~m|gecNrbNn3X9?Q6~qxopv-RNHfx+G4%&CwaHzWNe1# zPjYDldBFRNxypw}RE4}!tb|Jqy56##cI3y$HZ{IIOF`+WTk>Y*zybB_QtT)ak6m@6 zaDB(>bDH(!EnG*Q-`a0vFX?v@*^3$t?$5_vMwaGDf#bIO|k#E#p zCX?dhL%GU5`?gYCs$kE`Fn8v&TCDQf(U^Xd27UR}`&5=GU6nr}R;QMo28|{y#|@~< z(ioh~09l$~qR7$77wc$wdzHC#lnA{fl;* zO~s4kg}?sp;)xlO@kmROnCu}(Q5uLXim(p)+*uD_KV$kwuFWhht4d3h<SLAkPXI@z4^MxfKvrq&vcfL2 zH{O{BLTeBJ0T2KI5C8!X009sH0T2KI5CDOUKuO=PX1@Yx1%1p)e*}>C|BJ;jg?)wX zAO7C(-Q{1EKT~?8v|L;(K26EkKmY_l00ck)1V8`;Kw!5JXcY~mBW9YS?m9D0{jNiY zW@o~%E+0~!nQOJendAO~6S&c0^TCE6MIzXk5VSq{Q1Mi2HFWFZ@Wu@7$ZgEDTU4i@ zhnHK00ZH`eH()%aoT`4ipNTNG{ zcC>BRb0ga(nN5{s+S@C$N1VL>Uo5^$VP7pN?A^oPAHJu2p>(-)s`yO#5lY4e0w4ea zAOHd&00JNY0=tI5lFwhyaItzo4)?NSS2IV^I>;IuawPCjYHwIm;$mD4{x@{6DUY;5d3dks2whoLDy{?G5mXFv8A`^2|bZ`CPn zS|=l}`)fyE|N2wc_l{pZ{_k>5qx4}-wN%5hZq<|zJ*UUd|Fa({>>7KWegSxyU1EP? z7um1bFWEUt#s&f)00JNY0w4eaAOHd&00JNY0wAzc1mv#-YOxqcg+d%zRvhK?ab%it zl*`4@&`=y1MjYvS9BGH^_To3>O5C8!X009sH0T2KI5C8!X7zhD* z{~zoBfuM#E5C8!X009sH0T2KI5C8!X009u#F#^f+{}<%{|NqNgWB+8Yu$S12^bEl7 z*>Bl}9a9T}K>!3m00ck)1V8`;KmY_l00ck)1U4g}7wK*OdO-%34DvECWssA>kPHkN M=rYh`Am9K0e?Y`G00000 literal 0 HcmV?d00001 diff --git a/runtime-pyside6/LogarithmPlotter/util/promise.py b/runtime-pyside6/LogarithmPlotter/util/promise.py index f129d41..41b916d 100644 --- a/runtime-pyside6/LogarithmPlotter/util/promise.py +++ b/runtime-pyside6/LogarithmPlotter/util/promise.py @@ -17,7 +17,7 @@ """ from typing import Callable -from PySide6.QtCore import QRunnable, Signal, QObject, Slot, QThreadPool +from PySide6.QtCore import QRunnable, Signal, Property, QObject, Slot, QThreadPool from PySide6.QtQml import QJSValue from LogarithmPlotter.util.js import PyJSValue @@ -51,10 +51,10 @@ class PyPromiseRunner(QRunnable): data = data.qjs_value else: raise InvalidReturnValue("Must return either a primitive, a valid QObject, JS Value, or None.") - self.promise.finished.emit(data) + self.promise.fulfilled.emit(data) except Exception as e: try: - self.promise.errored.emit(repr(e)) + self.promise.rejected.emit(repr(e)) except RuntimeError as e2: # Happens when the PyPromise has already been garbage collected. # In other words, nothing to report to nowhere. @@ -66,18 +66,22 @@ class PyPromise(QObject): Asynchronous Promise-like object meant to interface between Python and Javascript easily. Runs to_run in another thread, and calls fulfilled (populated by then) with its return value. """ - finished = Signal((QJSValue,), (QObject,)) - errored = Signal(Exception) + fulfilled = Signal((QJSValue,), (QObject,)) + rejected = Signal(Exception) - def __init__(self, to_run: Callable, args): + def __init__(self, to_run: Callable, args=[]): QObject.__init__(self) self._fulfills = [] self._rejects = [] - self.finished.connect(self._fulfill) - self.errored.connect(self._reject) + self._state = "pending" + self.fulfilled.connect(self._fulfill) + self.rejected.connect(self._reject) self._runner = PyPromiseRunner(to_run, self, args) QThreadPool.globalInstance().start(self._runner) + @Property(str) + def state(self): + return self._state @Slot(QJSValue, result=QObject) @Slot(QJSValue, QJSValue, result=QObject) @@ -98,6 +102,7 @@ class PyPromise(QObject): @Slot(QJSValue) @Slot(QObject) def _fulfill(self, data): + self._state = "fulfilled" no_return = [None, QJSValue.SpecialValue.UndefinedValue] for on_fulfill in self._fulfills: try: @@ -110,6 +115,7 @@ class PyPromise(QObject): @Slot(QJSValue) @Slot(str) def _reject(self, error): + self._state = "rejected" no_return = [None, QJSValue.SpecialValue.UndefinedValue] for on_reject in self._rejects: result = on_reject(error) diff --git a/runtime-pyside6/tests/test_helper.py b/runtime-pyside6/tests/test_helper.py index 73dfb23..5cfb239 100644 --- a/runtime-pyside6/tests/test_helper.py +++ b/runtime-pyside6/tests/test_helper.py @@ -17,7 +17,7 @@ """ import pytest -from os import getcwd, remove +from os import getcwd, remove, path from os.path import join from tempfile import TemporaryDirectory from json import loads @@ -25,11 +25,12 @@ from shutil import copy2 from PySide6.QtCore import QObject, Signal, QThreadPool from PySide6.QtGui import QImage +from PySide6.QtQml import QJSValue from PySide6.QtWidgets import QApplication from LogarithmPlotter import __VERSION__ as version from LogarithmPlotter.util import config, helper -from LogarithmPlotter.util.helper import ChangelogFetcher, Helper, InvalidFileException +from LogarithmPlotter.util.helper import Helper, InvalidFileException pwd = getcwd() helper.SHOW_GUI_MESSAGES = False @@ -43,41 +44,45 @@ def temporary(): directory.cleanup() -class MockHelperSignals(QObject): - changelogFetched = Signal(str) +def create_changelog_callback_asserter(promise, expect_404=False): + def cb(changelog, expect_404=expect_404): + # print("Got changelog", changelog) + assert isinstance(changelog, QJSValue) + assert changelog.isString() + changlogValue = changelog.toVariant() + assert ('404' in changlogValue) == expect_404 + def error(e): + raise eval(e) + promise.then(cb, error) - def __init__(self, expect_404): - QObject.__init__(self) - self.expect_404 = expect_404 - self.changelogFetched.connect(self.changelog_fetched) - self.changelog = None - - def changelog_fetched(self, changelog): - self.changelog = changelog - - -class TestChangelog: - - def test_exists(self, qtbot): - helper.CHANGELOG_VERSION = '0.5.0' - mock_helper = MockHelperSignals(False) - fetcher = ChangelogFetcher(mock_helper) - fetcher.run() # Does not raise an exception - qtbot.waitSignal(mock_helper.changelogFetched, timeout=10000) - assert type(mock_helper.changelog) == str - assert '404' not in mock_helper.changelog - - def tests_no_exist(self, qtbot): - mock_helper = MockHelperSignals(True) - helper.CHANGELOG_VERSION = '1.0.0' - fetcher = ChangelogFetcher(mock_helper) - fetcher.run() - qtbot.waitSignal(mock_helper.changelogFetched, timeout=10000) - assert type(mock_helper.changelog) == str - assert '404' in mock_helper.changelog +CHANGELOG_BASE_PATH = path.realpath(path.join(path.dirname(path.realpath(__file__)), "..", "CHANGELOG.md")) class TestHelper: + def test_changelog(self, temporary, qtbot): + helper.CHANGELOG_VERSION = '0.5.0' + tmpfile, directory = temporary + obj = Helper(pwd, tmpfile) + promise = obj.fetchChangelog() + create_changelog_callback_asserter(promise, expect_404=False) + qtbot.waitSignal(promise.fulfilled, timeout=10000) + # No exist + helper.CHANGELOG_VERSION = '2.0.0' + tmpfile, directory = temporary + obj = Helper(pwd, tmpfile) + promise = obj.fetchChangelog() + create_changelog_callback_asserter(promise, expect_404=True) + qtbot.waitSignal(promise.fulfilled, timeout=10000) + # Local + tmpfile, directory = temporary + obj = Helper(pwd, tmpfile) + assert path.exists(CHANGELOG_BASE_PATH) + copy2(CHANGELOG_BASE_PATH, helper.CHANGELOG_CACHE_PATH) + assert path.exists(helper.CHANGELOG_CACHE_PATH) + promise = obj.fetchChangelog() + create_changelog_callback_asserter(promise, expect_404=False) + qtbot.waitSignal(promise.fulfilled, timeout=10000) # Local + def test_read(self, temporary): # Test file reading and information loading. tmpfile, directory = temporary @@ -168,15 +173,3 @@ class TestHelper: obj.setSetting("last_install_greet", obj.getSetting("last_install_greet")) obj.setSetting("check_for_updates", obj.getSetting("check_for_updates")) obj.setSetting("default_graph.xzoom", obj.getSetting("default_graph.xzoom")) - - def test_fetch_changelog(self, temporary, qtbot): - tmpfile, directory = temporary - obj = Helper(pwd, tmpfile) - copy2("../../CHANGELOG.md", "../../LogarithmPlotter/util/CHANGELOG.md") - obj.fetchChangelog() - assert QThreadPool.globalInstance().activeThreadCount() == 0 - qtbot.waitSignal(obj.changelogFetched, timeout=10000) - remove("../../LogarithmPlotter/util/CHANGELOG.md") - obj.fetchChangelog() - assert QThreadPool.globalInstance().activeThreadCount() > 0 - qtbot.waitSignal(obj.changelogFetched, timeout=10000) \ No newline at end of file diff --git a/runtime-pyside6/tests/test_latex.py b/runtime-pyside6/tests/test_latex.py index d74f9f1..6fd5c97 100644 --- a/runtime-pyside6/tests/test_latex.py +++ b/runtime-pyside6/tests/test_latex.py @@ -54,8 +54,8 @@ class TestLatex: # Reset [latex.DVIPNG_PATH, latex.LATEX_PATH] = bkp - def test_render(self, latex_obj: latex.Latex) -> None: - result = latex_obj.render(r"\frac{d\sqrt{\mathrm{f}(x \times 2.3)}}{dx}", 14, QColor(0, 0, 0, 255)) + def test_render_sync(self, latex_obj: latex.Latex) -> None: + result = latex_obj.renderSync(r"\frac{d\sqrt{\mathrm{f}(x \times 2.3)}}{dx}", 14, QColor(0, 0, 0, 255)) # Ensure result format assert type(result) == str [path, width, height] = result.split(",") @@ -64,17 +64,17 @@ class TestLatex: assert match(r"\d+", height) # Ensure it returns errors on invalid latex. with pytest.raises(latex.RenderError): - latex_obj.render(r"\nonexistant", 14, QColor(0, 0, 0, 255)) + latex_obj.renderSync(r"\nonexistant", 14, QColor(0, 0, 0, 255)) # Replace latex bin with one that returns errors bkp = latex.LATEX_PATH latex.LATEX_PATH = which("false") with pytest.raises(latex.RenderError): - latex_obj.render(r"\mathrm{f}(x)", 14, QColor(0, 0, 0, 255)) + latex_obj.renderSync(r"\mathrm{f}(x)", 14, QColor(0, 0, 0, 255)) latex.LATEX_PATH = bkp def test_prerendered(self, latex_obj: latex.Latex) -> None: args = [r"\frac{d\sqrt{\mathrm{f}(x \times 2.3)}}{dx}", 14, QColor(0, 0, 0, 255)] - latex_obj.render(*args) + latex_obj.renderSync(*args) prerendered = latex_obj.findPrerendered(*args) assert type(prerendered) == str [path, width, height] = prerendered.split(",")