Switch to Path objects nearly everywhere

This commit is contained in:
Veronica Berglyd Olsen
2022-11-09 22:43:48 +01:00
parent cb755ba820
commit 03e173634f
36 changed files with 406 additions and 521 deletions
+13 -40
View File
@@ -19,10 +19,9 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import hashlib
import os
import time
import pytest
import hashlib
from mock import causeOSError
from tools import writeFile
@@ -33,8 +32,8 @@ from novelwriter.common import (
checkUuid, isHandle, isTitleTag, isItemClass, isItemType, isItemLayout,
hexToInt, minmax, checkIntTuple, formatInt, formatTimeStamp, formatTime,
simplified, yesNo, splitVersionNumber, transferCase, fuzzyTime,
numberToRoman, jsonEncode, readTextFile, makeFileNameSafe, ensureFolder,
sha256sum, getGuiItem, NWConfigParser
numberToRoman, jsonEncode, readTextFile, makeFileNameSafe, sha256sum,
getGuiItem, NWConfigParser
)
@@ -591,18 +590,18 @@ def testBaseCommon_JsonEncode():
@pytest.mark.base
def testBaseCommon_ReadTextFile(monkeypatch, fncDir, ipsumText):
def testBaseCommon_ReadTextFile(monkeypatch, fncPath, ipsumText):
"""Test the readTextFile function.
"""
testText = "\n\n".join(ipsumText) + "\n"
testFile = os.path.join(fncDir, "ipsum.txt")
testFile = fncPath / "ipsum.txt"
writeFile(testFile, testText)
assert readTextFile(os.path.join(fncDir, "not_a_file.txt")) == ""
assert readTextFile(fncPath / "not_a_file.txt") == ""
assert readTextFile(testFile) == testText
with monkeypatch.context() as mp:
mp.setattr("builtins.open", causeOSError)
mp.setattr("pathlib.Path.read_text", causeOSError)
assert readTextFile(testFile) == ""
# END Test testBaseCommon_ReadTextFile
@@ -621,33 +620,7 @@ def testBaseCommon_MakeFileNameSafe():
@pytest.mark.base
def testBaseCommon_EnsureFolder(monkeypatch, fncDir):
"""Test the ensureFolder function.
"""
newDir1 = os.path.join(fncDir, "newDir1")
newDir2 = os.path.join(fncDir, "newDir2")
newDir3 = os.path.join(fncDir, "newDir3")
assert ensureFolder(None) is False
assert ensureFolder(newDir1) is True
assert os.path.isdir(newDir1)
assert ensureFolder("newDir2", parent=fncDir) is True
assert os.path.isdir(newDir2)
with monkeypatch.context() as mp:
mp.setattr("os.mkdir", causeOSError)
errLog = []
assert ensureFolder("newDir3", parent=fncDir, errLog=errLog) is False
assert errLog[0] == f"Could not create folder: {newDir3}"
assert not os.path.isdir(newDir3)
# END Test testBaseCommon_EnsureFolder
@pytest.mark.base
def testBaseCommon_Sha256Sum(monkeypatch, fncDir, ipsumText):
def testBaseCommon_Sha256Sum(monkeypatch, fncPath, ipsumText):
"""Test the sha256sum function.
"""
longText = 50*(" ".join(ipsumText) + " ")
@@ -656,9 +629,9 @@ def testBaseCommon_Sha256Sum(monkeypatch, fncDir, ipsumText):
assert len(longText) == 175650
longFile = os.path.join(fncDir, "long_file.txt")
shortFile = os.path.join(fncDir, "short_file.txt")
noneFile = os.path.join(fncDir, "none_file.txt")
longFile = fncPath / "long_file.txt"
shortFile = fncPath / "short_file.txt"
noneFile = fncPath / "none_file.txt"
writeFile(longFile, longText)
writeFile(shortFile, shortText)
@@ -697,10 +670,10 @@ def testBaseCommon_GetGuiItem(nwGUI):
@pytest.mark.base
def testBaseCommon_NWConfigParser(fncDir):
def testBaseCommon_NWConfigParser(fncPath):
"""Test the NWConfigParser subclass.
"""
tstConf = os.path.join(fncDir, "test.cfg")
tstConf = fncPath / "test.cfg"
writeFile(tstConf, (
"[main]\n"
"stropt = value\n"
+2 -22
View File
@@ -20,9 +20,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import pytest
import novelwriter
from PyQt5.QtWidgets import QMessageBox, qApp
from mock import causeException
@@ -30,18 +27,9 @@ from novelwriter.error import NWErrorMessage, exceptionHandler
@pytest.mark.base
def testBaseError_Dialog(qtbot, monkeypatch, fncDir, tmpDir):
def testBaseError_Dialog(qtbot, monkeypatch, nwGUI):
"""Test the error dialog.
"""
# Block message box
monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes)
qApp.closeAllWindows()
nwGUI = novelwriter.main(["--testmode", "--config=%s" % fncDir, "--data=%s" % tmpDir])
qtbot.addWidget(nwGUI)
nwGUI.show()
qtbot.wait(20)
nwErr = NWErrorMessage(nwGUI)
qtbot.addWidget(nwErr)
nwErr.show()
@@ -76,19 +64,11 @@ def testBaseError_Dialog(qtbot, monkeypatch, fncDir, tmpDir):
@pytest.mark.base
def testBaseError_Handler(qtbot, monkeypatch, fncDir, tmpDir):
def testBaseError_Handler(qtbot, monkeypatch, nwGUI):
"""Test the error handler. This test doesn'thave any asserts, but it
checks that the error handler handles potential exceptions. The test
will fail if excpetions are not handled.
"""
monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes)
qApp.closeAllWindows()
nwGUI = novelwriter.main(["--testmode", "--config=%s" % fncDir, "--data=%s" % tmpDir])
qtbot.addWidget(nwGUI)
nwGUI.show()
qtbot.wait(20)
# Normal shutdown
with monkeypatch.context() as mp:
mp.setattr(NWErrorMessage, "exec_", lambda *a: None)
+16 -16
View File
@@ -28,13 +28,13 @@ from mock import MockGuiMain
@pytest.mark.base
def testBaseInit_Launch(caplog, monkeypatch, tmpDir):
def testBaseInit_Launch(caplog, monkeypatch, tmpPath):
"""Check launching the main GUI.
"""
monkeypatch.setattr("novelwriter.guimain.GuiMain", MockGuiMain)
# TestMode Launch
nwGUI = novelwriter.main(["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir])
nwGUI = novelwriter.main(["--testmode", f"--config={tmpPath}", f"--data={tmpPath}"])
assert isinstance(nwGUI, MockGuiMain)
# Darwin Launch
@@ -43,7 +43,7 @@ def testBaseInit_Launch(caplog, monkeypatch, tmpDir):
novelwriter.CONFIG.osDarwin = True
with monkeypatch.context() as mp:
mp.setitem(sys.modules, "Foundation", None)
nwGUI = novelwriter.main(["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir])
nwGUI = novelwriter.main(["--testmode", f"--config={tmpPath}", f"--data={tmpPath}"])
assert isinstance(nwGUI, MockGuiMain)
assert "Failed" in caplog.text
@@ -55,7 +55,7 @@ def testBaseInit_Launch(caplog, monkeypatch, tmpDir):
novelwriter.CONFIG.osWindows = True
with monkeypatch.context() as mp:
mp.setitem(sys.modules, "ctypes", None)
nwGUI = novelwriter.main(["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir])
nwGUI = novelwriter.main(["--testmode", f"--config={tmpPath}", f"--data={tmpPath}"])
assert isinstance(nwGUI, MockGuiMain)
if not sys.platform.startswith("darwin"):
# For some reason, the test doesn't work on macOS
@@ -71,19 +71,19 @@ def testBaseInit_Launch(caplog, monkeypatch, tmpDir):
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.setOrganizationDomain", lambda *a: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.exec_", lambda *a: 0)
with pytest.raises(SystemExit) as ex:
novelwriter.main(["--config=%s" % tmpDir, "--data=%s" % tmpDir])
novelwriter.main([f"--config={tmpPath}", f"--data={tmpPath}"])
assert ex.value.code == 0
# END Test testBaseInit_Launch
@pytest.mark.base
def testBaseInit_Options(monkeypatch, tmpDir):
def testBaseInit_Options(monkeypatch, tmpPath):
"""Test command line options for logging level.
"""
monkeypatch.setattr("novelwriter.guimain.GuiMain", MockGuiMain)
monkeypatch.setattr(sys, "argv", [
"novelWriter.py", "--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir
"novelWriter.py", "--testmode", f"--config={tmpPath}", f"--data={tmpPath}"
])
# Defaults w/None Args
@@ -93,20 +93,20 @@ def testBaseInit_Options(monkeypatch, tmpDir):
# Defaults
nwGUI = novelwriter.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir, "--style=Fusion"]
["--testmode", f"--config={tmpPath}", f"--data={tmpPath}", "--style=Fusion"]
)
assert novelwriter.logger.getEffectiveLevel() == logging.WARNING
assert nwGUI.closeMain() == "closeMain"
# Log Levels
nwGUI = novelwriter.main(
["--testmode", "--info", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", "--info", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert novelwriter.logger.getEffectiveLevel() == logging.INFO
assert nwGUI.closeMain() == "closeMain"
nwGUI = novelwriter.main(
["--testmode", "--debug", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", "--debug", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert novelwriter.logger.getEffectiveLevel() == logging.DEBUG
assert nwGUI.closeMain() == "closeMain"
@@ -114,14 +114,14 @@ def testBaseInit_Options(monkeypatch, tmpDir):
# Help and Version
with pytest.raises(SystemExit) as ex:
nwGUI = novelwriter.main(
["--testmode", "--help", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", "--help", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 0
with pytest.raises(SystemExit) as ex:
nwGUI = novelwriter.main(
["--testmode", "--version", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", "--version", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 0
@@ -129,14 +129,14 @@ def testBaseInit_Options(monkeypatch, tmpDir):
# Invalid options
with pytest.raises(SystemExit) as ex:
nwGUI = novelwriter.main(
["--testmode", "--invalid", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", "--invalid", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 2
# Project Path
nwGUI = novelwriter.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir, "sample/"]
["--testmode", f"--config={tmpPath}", f"--data={tmpPath}", "sample/"]
)
assert novelwriter.CONFIG.cmdOpen == "sample/"
assert nwGUI.closeMain() == "closeMain"
@@ -145,7 +145,7 @@ def testBaseInit_Options(monkeypatch, tmpDir):
@pytest.mark.base
def testBaseInit_Imports(caplog, monkeypatch, tmpDir):
def testBaseInit_Imports(caplog, monkeypatch, tmpPath):
"""Check import error handling.
"""
monkeypatch.setattr("novelwriter.guimain.GuiMain", MockGuiMain)
@@ -161,7 +161,7 @@ def testBaseInit_Imports(caplog, monkeypatch, tmpDir):
with pytest.raises(SystemExit) as ex:
_ = novelwriter.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
["--testmode", f"--config={tmpPath}", f"--data={tmpPath}"]
)
assert ex.value.code & 4 == 4 # Python version not satisfied