Move test files into subfolders with similar structure as source code

This commit is contained in:
Veronica K. B. Olsen
2021-01-16 17:59:29 +01:00
parent fd04f94b76
commit a947ec10e4
33 changed files with 0 additions and 0 deletions
+212
View File
@@ -0,0 +1,212 @@
# -*- coding: utf-8 -*-
"""
novelWriter Common Functions Tester
=====================================
This file is a part of novelWriter
Copyright 20182021, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
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 time
import pytest
from nw.common import (
checkString, checkBool, checkInt, colRange, formatInt, transferCase,
fuzzyTime, checkHandle, formatTimeStamp, formatTime
)
from tools import cmpList
@pytest.mark.base
def testBaseCommon_CheckString():
"""Test the checkString function.
"""
assert checkString(None, "NotNone", True) is None
assert checkString("None", "NotNone", True) is None
assert checkString("None", "NotNone", False) == "None"
assert checkString(None, "NotNone", False) == "NotNone"
assert checkString(1, "NotNone", False) == "NotNone"
assert checkString(1.0, "NotNone", False) == "NotNone"
assert checkString(True, "NotNone", False) == "NotNone"
# END Test testBaseCommon_CheckString
@pytest.mark.base
def testBaseCommon_CheckInt():
"""Test the checkInt function.
"""
assert checkInt(None, 3, True) is None
assert checkInt("None", 3, True) is None
assert checkInt(None, 3, False) == 3
assert checkInt(1, 3, False) == 1
assert checkInt(1.0, 3, False) == 1
assert checkInt(True, 3, False) == 1
# END Test testBaseCommon_CheckInt
@pytest.mark.base
def testBaseCommon_CheckBool():
"""Test the checkBool function.
"""
assert checkBool(None, 3, True) is None
assert checkBool("None", 3, True) is None
assert checkBool("True", False, False)
assert not checkBool("False", True, False)
assert checkBool("Boo", None, False) is None
assert not checkBool(0, None, False)
assert checkBool(1, None, False)
assert checkBool(2, None, False) is None
assert checkBool(0.0, None, False) is None
assert checkBool(1.0, None, False) is None
assert checkBool(2.0, None, False) is None
# END Test testBaseCommon_CheckBool
@pytest.mark.base
def testBaseCommon_CheckHandle():
"""Test the checkHandle function.
"""
assert checkHandle("None", 1, True) is None
assert checkHandle("None", 1, False) == 1
assert checkHandle(None, 1, True) is None
assert checkHandle(None, 1, False) == 1
assert checkHandle("47666c91c7ccf", None, False) == "47666c91c7ccf"
assert checkHandle("h7666c91c7ccf", None, False) is None
# END Test testBaseCommon_CheckHandle
@pytest.mark.base
def testBaseCommon_ColRange():
"""Test the colRange function.
"""
assert colRange([0, 0], [0, 0], 0) is None
assert cmpList(
colRange([200, 50, 0], [50, 200, 0], 1),
[200, 50, 0]
)
assert cmpList(
colRange([200, 50, 0], [50, 200, 0], 2),
[[200, 50, 0], [50, 200, 0]]
)
assert cmpList(
colRange([200, 50, 0], [50, 200, 0], 3),
[[200, 50, 0], [125, 125, 0], [50, 200, 0]]
)
assert cmpList(
colRange([200, 50, 0], [50, 200, 0], 4),
[[200, 50, 0], [150, 100, 0], [100, 150, 0], [50, 200, 0]]
)
assert cmpList(
colRange([200, 50, 0], [50, 200, 0], 5),
[[200, 50, 0], [162, 87, 0], [124, 124, 0], [86, 161, 0], [50, 200, 0]]
)
# END Test testBaseCommon_ColRange
@pytest.mark.base
def testBaseCommon_FormatTimeStamp():
"""Test the formatTimeStamp function.
"""
tTime = time.mktime(time.gmtime(0))
assert formatTimeStamp(tTime, False) == "1970-01-01 00:00:00"
assert formatTimeStamp(tTime, True) == "1970-01-01 00.00.00"
# END Test testBaseCommon_FormatTimeStamp
@pytest.mark.base
def testBaseCommon_FormatTime():
"""Test the formatTime function.
"""
assert formatTime("1") == "ERROR"
assert formatTime(1.0) == "ERROR"
assert formatTime(1) == "00:00:01"
assert formatTime(59) == "00:00:59"
assert formatTime(60) == "00:01:00"
assert formatTime(180) == "00:03:00"
assert formatTime(194) == "00:03:14"
assert formatTime(3540) == "00:59:00"
assert formatTime(3599) == "00:59:59"
assert formatTime(3600) == "01:00:00"
assert formatTime(11640) == "03:14:00"
assert formatTime(11655) == "03:14:15"
assert formatTime(86399) == "23:59:59"
assert formatTime(86400) == "1-00:00:00"
assert formatTime(360000) == "4-04:00:00"
# END Test testBaseCommon_FormatTime
@pytest.mark.base
def testBaseCommon_FormatInt():
"""Test the formatInt function.
"""
assert formatInt(1000) == "1000"
assert formatInt(1234) == "1.23\u2009k"
assert formatInt(12345) == "12.3\u2009k"
assert formatInt(123456) == "123\u2009k"
assert formatInt(1234567) == "1.23\u2009M"
assert formatInt(12345678) == "12.3\u2009M"
assert formatInt(123456789) == "123\u2009M"
assert formatInt(1234567890) == "1.23\u2009G"
# END Test testBaseCommon_FormatInt
@pytest.mark.base
def testBaseCommon_TransferCase():
"""Test the transferCase function.
"""
assert transferCase(1, "TaRgEt") == "TaRgEt"
assert transferCase("source", 1) == 1
assert transferCase("", "TaRgEt") == "TaRgEt"
assert transferCase("source", "") == ""
assert transferCase("Source", "target") == "Target"
assert transferCase("SOURCE", "target") == "TARGET"
assert transferCase("source", "TARGET") == "target"
# END Test testBaseCommon_TransferCase
@pytest.mark.base
def testBaseCommon_FuzzyTime():
"""Test the fuzzyTime function.
"""
assert fuzzyTime(-1) == "in the future"
assert fuzzyTime(0) == "just now"
assert fuzzyTime(29) == "just now"
assert fuzzyTime(30) == "a minute ago"
assert fuzzyTime(89) == "a minute ago"
assert fuzzyTime(90) == "2 minutes ago"
assert fuzzyTime(149) == "2 minutes ago"
assert fuzzyTime(151) == "3 minutes ago"
assert fuzzyTime(3299) == "55 minutes ago"
assert fuzzyTime(3300) == "an hour ago"
assert fuzzyTime(5399) == "an hour ago"
assert fuzzyTime(5400) == "2 hours ago"
assert fuzzyTime(84599) == "23 hours ago"
assert fuzzyTime(84600) == "a day ago"
assert fuzzyTime(129599) == "a day ago"
assert fuzzyTime(129600) == "2 days ago"
assert fuzzyTime(561599) == "6 days ago"
assert fuzzyTime(561600) == "a week ago"
assert fuzzyTime(907199) == "a week ago"
assert fuzzyTime(907200) == "2 weeks ago"
assert fuzzyTime(2419199) == "4 weeks ago"
assert fuzzyTime(2419200) == "a month ago"
assert fuzzyTime(3887999) == "a month ago"
assert fuzzyTime(3888000) == "2 months ago"
assert fuzzyTime(29807999) == "11 months ago"
assert fuzzyTime(29808000) == "a year ago"
assert fuzzyTime(47336399) == "a year ago"
assert fuzzyTime(47336400) == "2 years ago"
# END Test testBaseCommon_FuzzyTime
+536
View File
@@ -0,0 +1,536 @@
# -*- coding: utf-8 -*-
"""
novelWriter Config Class Tester
=================================
This file is a part of novelWriter
Copyright 20182021, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
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 pytest
import sys
import os
import configparser
from shutil import copyfile
from dummy import causeOSError
from tools import cmpFiles
from nw.config import Config
from nw.constants import nwConst, nwFiles
@pytest.mark.base
def testBaseConfig_Constructor(monkeypatch):
"""Test config contructor.
"""
# Linux
monkeypatch.setattr("sys.platform", "linux")
tstConf = Config()
assert tstConf.osLinux is True
assert tstConf.osDarwin is False
assert tstConf.osWindows is False
assert tstConf.osUnknown is False
monkeypatch.undo()
# macOS
monkeypatch.setattr("sys.platform", "darwin")
tstConf = Config()
assert tstConf.osLinux is False
assert tstConf.osDarwin is True
assert tstConf.osWindows is False
assert tstConf.osUnknown is False
monkeypatch.undo()
# Windows
monkeypatch.setattr("sys.platform", "win32")
tstConf = Config()
assert tstConf.osLinux is False
assert tstConf.osDarwin is False
assert tstConf.osWindows is True
assert tstConf.osUnknown is False
monkeypatch.undo()
# Cygwin
monkeypatch.setattr("sys.platform", "cygwin")
tstConf = Config()
assert tstConf.osLinux is False
assert tstConf.osDarwin is False
assert tstConf.osWindows is True
assert tstConf.osUnknown is False
monkeypatch.undo()
# Other
monkeypatch.setattr("sys.platform", "some_ther_os")
tstConf = Config()
assert tstConf.osLinux is False
assert tstConf.osDarwin is False
assert tstConf.osWindows is False
assert tstConf.osUnknown is True
monkeypatch.undo()
# END Test testBaseConfig_Constructor
@pytest.mark.base
def testBaseConfig_Init(monkeypatch, tmpDir, fncDir, outDir, refDir):
"""Test config intialisation.
"""
tstConf = Config()
confFile = os.path.join(tmpDir, "novelwriter.conf")
testFile = os.path.join(outDir, "baseConfig_novelwriter.conf")
compFile = os.path.join(refDir, "baseConfig_novelwriter.conf")
# Make sure we don't have any old conf file
if os.path.isfile(confFile):
os.unlink(confFile)
# Let the config class figure out the path
monkeypatch.setattr("PyQt5.QtCore.QStandardPaths.writableLocation", lambda *args: fncDir)
tstConf.verQtValue = 50600
tstConf.initConfig()
assert tstConf.confPath == os.path.join(fncDir, tstConf.appHandle)
assert tstConf.dataPath == os.path.join(fncDir, tstConf.appHandle)
assert not os.path.isfile(confFile)
tstConf.verQtValue = 50000
tstConf.initConfig()
assert tstConf.confPath == os.path.join(fncDir, tstConf.appHandle)
assert tstConf.dataPath == os.path.join(fncDir, tstConf.appHandle)
assert not os.path.isfile(confFile)
monkeypatch.undo()
# Fail to make folders
monkeypatch.setattr("os.mkdir", causeOSError)
tstConfDir = os.path.join(fncDir, "test_conf")
tstConf.initConfig(confPath=tstConfDir, dataPath=tmpDir)
assert tstConf.confPath is None
assert tstConf.dataPath == tmpDir
assert not os.path.isfile(confFile)
tstDataDir = os.path.join(fncDir, "test_data")
tstConf.initConfig(confPath=tmpDir, dataPath=tstDataDir)
assert tstConf.confPath == tmpDir
assert tstConf.dataPath is None
assert os.path.isfile(confFile)
os.unlink(confFile)
monkeypatch.undo()
# Test load/save with no path
tstConf.confPath = None
assert not tstConf.loadConfig()
assert not tstConf.saveConfig()
# Run again and set the paths directly and correctly
# This should create a config file as well
monkeypatch.setattr("os.path.expanduser", lambda *args: "")
tstConf.spellTool = nwConst.SP_INTERNAL
tstConf.initConfig(confPath=tmpDir, dataPath=tmpDir)
assert tstConf.confPath == tmpDir
assert tstConf.dataPath == tmpDir
assert os.path.isfile(confFile)
copyfile(confFile, testFile)
assert cmpFiles(testFile, compFile, [2, 9])
monkeypatch.undo()
# Load and save with OSError
monkeypatch.setattr("builtins.open", causeOSError)
assert not tstConf.loadConfig()
assert tstConf.hasError is True
assert tstConf.errData != []
assert tstConf.getErrData().startswith("Could not")
assert tstConf.hasError is False
assert tstConf.errData == []
assert not tstConf.saveConfig()
assert tstConf.hasError is True
assert tstConf.errData != []
assert tstConf.getErrData().startswith("Could not")
assert tstConf.hasError is False
assert tstConf.errData == []
monkeypatch.undo()
assert tstConf.loadConfig()
assert tstConf.saveConfig()
copyfile(confFile, testFile)
assert cmpFiles(testFile, compFile, [2, 9])
# END Test testBaseConfig_Init
@pytest.mark.base
def testBaseConfig_RecentCache(monkeypatch, tmpConf, tmpDir, fncDir):
"""Test recent cache file.
"""
# Check failing
tmpConf.dataPath = None
assert not tmpConf.loadRecentCache()
assert not tmpConf.saveRecentCache()
tmpConf.dataPath = tmpDir
# Add a couple of values
pathOne = os.path.join(fncDir, "projPathOne", nwFiles.PROJ_FILE)
pathTwo = os.path.join(fncDir, "projPathTwo", nwFiles.PROJ_FILE)
assert tmpConf.updateRecentCache(pathOne, "Proj One", 100, 1600002000)
assert tmpConf.updateRecentCache(pathTwo, "Proj Two", 200, 1600005600)
assert tmpConf.recentProj == {
pathOne: {"time": 1600002000, "title": "Proj One", "words": 100},
pathTwo: {"time": 1600005600, "title": "Proj Two", "words": 200},
}
# Fail to Save
monkeypatch.setattr("builtins.open", causeOSError)
assert not tmpConf.saveRecentCache()
monkeypatch.undo()
# Save Proper
cacheFile = os.path.join(tmpDir, nwFiles.RECENT_FILE)
assert tmpConf.saveRecentCache()
assert tmpConf.saveRecentCache()
assert os.path.isfile(cacheFile)
# Fail to Load
monkeypatch.setattr("builtins.open", causeOSError)
tmpConf.recentProj = {}
assert not tmpConf.loadRecentCache()
assert tmpConf.recentProj == {}
monkeypatch.undo()
# Load Proper
tmpConf.recentProj = {}
assert tmpConf.loadRecentCache()
assert tmpConf.recentProj == {
pathOne: {"time": 1600002000, "title": "Proj One", "words": 100},
pathTwo: {"time": 1600005600, "title": "Proj Two", "words": 200},
}
# Remove Non-Existent Entry
assert not tmpConf.removeFromRecentCache("dummy")
assert tmpConf.recentProj == {
pathOne: {"time": 1600002000, "title": "Proj One", "words": 100},
pathTwo: {"time": 1600005600, "title": "Proj Two", "words": 200},
}
# Remove Second Entry
assert tmpConf.removeFromRecentCache(pathTwo)
assert tmpConf.recentProj == {
pathOne: {"time": 1600002000, "title": "Proj One", "words": 100},
}
# END Test testBaseConfig_RecentCache
@pytest.mark.base
def testBaseConfig_SetPath(tmpConf, tmpDir):
"""Test path setters.
"""
# Conf Path
assert tmpConf.setConfPath(None)
assert not tmpConf.setConfPath(os.path.join("somewhere", "over", "the", "rainbow"))
assert tmpConf.setConfPath(os.path.join(tmpDir, "novelwriter.conf"))
assert tmpConf.confPath == tmpDir
assert tmpConf.confFile == "novelwriter.conf"
assert not tmpConf.confChanged
# Data Path
assert tmpConf.setDataPath(None)
assert not tmpConf.setDataPath(os.path.join("somewhere", "over", "the", "rainbow"))
assert tmpConf.setDataPath(tmpDir)
assert tmpConf.dataPath == tmpDir
assert not tmpConf.confChanged
# Last Path
assert tmpConf.setLastPath(None)
assert tmpConf.lastPath == ""
assert tmpConf.setLastPath(os.path.join(tmpDir, "file.tmp"))
assert tmpConf.lastPath == tmpDir
assert tmpConf.setLastPath("")
assert tmpConf.lastPath == ""
# END Test testBaseConfig_SetPath
@pytest.mark.base
def testBaseConfig_SettersGetters(tmpConf, tmpDir, outDir, refDir):
"""Set various sizes and positions
"""
confFile = os.path.join(tmpDir, "novelwriter.conf")
testFile = os.path.join(outDir, "baseConfig_novelwriter.conf")
compFile = os.path.join(refDir, "baseConfig_novelwriter.conf")
# GUI Scaling
# ===========
tmpConf.guiScale = 1.0
assert tmpConf.pxInt(10) == 10
assert tmpConf.pxInt(13) == 13
assert tmpConf.rpxInt(10) == 10
assert tmpConf.rpxInt(13) == 13
tmpConf.guiScale = 2.0
assert tmpConf.pxInt(10) == 20
assert tmpConf.pxInt(13) == 26
assert tmpConf.rpxInt(10) == 5
assert tmpConf.rpxInt(13) == 6
# Setter + Getter Combos
# ======================
# Window Size
tmpConf.guiScale = 1.0
assert tmpConf.setWinSize(1205, 655)
assert not tmpConf.confChanged
tmpConf.guiScale = 2.0
assert tmpConf.setWinSize(70, 70)
assert tmpConf.getWinSize() == [70, 70]
assert tmpConf.winGeometry == [35, 35]
tmpConf.guiScale = 1.0
assert tmpConf.setWinSize(70, 70)
assert tmpConf.getWinSize() == [70, 70]
assert tmpConf.winGeometry == [70, 70]
assert tmpConf.setWinSize(1200, 650)
# Project Tree Columns
tmpConf.guiScale = 2.0
assert tmpConf.setTreeColWidths([10, 20, 25])
assert tmpConf.getTreeColWidths() == [10, 20, 24]
assert tmpConf.treeColWidth == [5, 10, 12]
tmpConf.guiScale = 1.0
assert tmpConf.setTreeColWidths([10, 20, 25])
assert tmpConf.getTreeColWidths() == [10, 20, 25]
assert tmpConf.treeColWidth == [10, 20, 25]
assert tmpConf.setTreeColWidths([200, 50, 30])
# Novel Tree Columns
tmpConf.guiScale = 2.0
assert tmpConf.setNovelColWidths([10, 20])
assert tmpConf.getNovelColWidths() == [10, 20]
assert tmpConf.novelColWidth == [5, 10]
tmpConf.guiScale = 1.0
assert tmpConf.setNovelColWidths([10, 20])
assert tmpConf.getNovelColWidths() == [10, 20]
assert tmpConf.novelColWidth == [10, 20]
assert tmpConf.setNovelColWidths([200, 50])
# Project Settings Tree Columns
tmpConf.guiScale = 2.0
assert tmpConf.setProjColWidths([10, 20, 30])
assert tmpConf.getProjColWidths() == [10, 20, 30]
assert tmpConf.projColWidth == [5, 10, 15]
tmpConf.guiScale = 1.0
assert tmpConf.setProjColWidths([10, 20, 30])
assert tmpConf.getProjColWidths() == [10, 20, 30]
assert tmpConf.projColWidth == [10, 20, 30]
assert tmpConf.setProjColWidths([200, 60, 140])
# Main Pane Splitter
tmpConf.guiScale = 2.0
assert tmpConf.setMainPanePos([200, 700])
assert tmpConf.getMainPanePos() == [200, 700]
assert tmpConf.mainPanePos == [100, 350]
tmpConf.guiScale = 1.0
assert tmpConf.setMainPanePos([200, 700])
assert tmpConf.getMainPanePos() == [200, 700]
assert tmpConf.mainPanePos == [200, 700]
assert tmpConf.setMainPanePos([300, 800])
# Doc Pane Splitter
tmpConf.guiScale = 2.0
assert tmpConf.setDocPanePos([300, 300])
assert tmpConf.getDocPanePos() == [300, 300]
assert tmpConf.docPanePos == [150, 150]
tmpConf.guiScale = 1.0
assert tmpConf.setDocPanePos([300, 300])
assert tmpConf.getDocPanePos() == [300, 300]
assert tmpConf.docPanePos == [300, 300]
assert tmpConf.setDocPanePos([400, 400])
# View Pane Splitter
tmpConf.guiScale = 2.0
assert tmpConf.setViewPanePos([400, 250])
assert tmpConf.getViewPanePos() == [400, 250]
assert tmpConf.viewPanePos == [200, 125]
tmpConf.guiScale = 1.0
assert tmpConf.setViewPanePos([400, 250])
assert tmpConf.getViewPanePos() == [400, 250]
assert tmpConf.viewPanePos == [400, 250]
assert tmpConf.setViewPanePos([500, 150])
# Outline Pane Splitter
tmpConf.guiScale = 2.0
assert tmpConf.setOutlinePanePos([400, 250])
assert tmpConf.getOutlinePanePos() == [400, 250]
assert tmpConf.outlnPanePos == [200, 125]
tmpConf.guiScale = 1.0
assert tmpConf.setOutlinePanePos([400, 250])
assert tmpConf.getOutlinePanePos() == [400, 250]
assert tmpConf.outlnPanePos == [400, 250]
assert tmpConf.setOutlinePanePos([500, 150])
# Getters Only
# ============
tmpConf.guiScale = 1.0
assert tmpConf.getTextWidth() == 600
assert tmpConf.getTextMargin() == 40
assert tmpConf.getTabWidth() == 40
assert tmpConf.getFocusWidth() == 800
tmpConf.guiScale = 2.0
assert tmpConf.getTextWidth() == 1200
assert tmpConf.getTextMargin() == 80
assert tmpConf.getTabWidth() == 80
assert tmpConf.getFocusWidth() == 1600
# Flag Setters
# ============
assert not tmpConf.setShowRefPanel(False)
assert not tmpConf.showRefPanel
assert tmpConf.setShowRefPanel(True)
assert not tmpConf.setViewComments(False)
assert not tmpConf.viewComments
assert tmpConf.setViewComments(True)
assert not tmpConf.setViewSynopsis(False)
assert not tmpConf.viewSynopsis
assert tmpConf.setViewSynopsis(True)
# Check Final File
# ================
assert tmpConf.confChanged
assert tmpConf.saveConfig()
assert not tmpConf.confChanged
copyfile(confFile, testFile)
assert cmpFiles(testFile, compFile, [2, 9])
# END Test testBaseConfig_SettersGetters
@pytest.mark.base
def testBaseConfig_Internal(monkeypatch, tmpConf):
"""Check internal functions.
"""
# Function _packList
assert tmpConf._packList(["A", 1, 2.0, None, False]) == "A, 1, 2.0, None, False"
# Function _unpackList
assert tmpConf._unpackList("1, 2, 3", [0, 0, 0], tmpConf.CNF_I_LST) == [1, 2, 3]
assert tmpConf._unpackList("1, 2 ", [0, 0, 0], tmpConf.CNF_I_LST) == [1, 2, 0]
assert tmpConf._unpackList("A, B, C", [0, 0, 0], tmpConf.CNF_I_LST) == [0, 0, 0]
assert tmpConf._unpackList("1, 2, 3", ["X", "Y", "Z"], tmpConf.CNF_S_LST) == ["1", "2", "3"]
assert tmpConf._unpackList("A, B ", ["X", "Y", "Z"], tmpConf.CNF_S_LST) == ["A", "B", "Z"]
assert tmpConf._unpackList("A, B, C", ["X", "Y", "Z"], tmpConf.CNF_S_LST) == ["A", "B", "C"]
assert tmpConf._unpackList("A, B, C", ["X", "Y", "Z"], tmpConf.CNF_STR) == ["X", "Y", "Z"]
# Function _parseLine
cnfParse = configparser.ConfigParser()
cnfParse.read_string(
"[Main]\n"
"val_string = dummy\n"
"val_int = 123\n"
"val_bool = True\n"
"val_list_string = A, B, C\n"
"val_list_int = 1, 2, 3\n"
)
assert tmpConf._parseLine(
cnfParse, "Main", "val_string", tmpConf.CNF_STR, "default"
) == "dummy"
assert tmpConf._parseLine(
cnfParse, "Main", "nope", tmpConf.CNF_STR, "default"
) == "default"
assert tmpConf._parseLine(
cnfParse, "Main", "val_int", tmpConf.CNF_INT, "0"
) == 123
assert tmpConf._parseLine(
cnfParse, "Main", "nope", tmpConf.CNF_INT, 0
) == 0
assert tmpConf._parseLine(
cnfParse, "Main", "val_string", tmpConf.CNF_INT, 0
) == 0
assert tmpConf._parseLine(
cnfParse, "Main", "val_bool", tmpConf.CNF_BOOL, False
) is True
assert tmpConf._parseLine(
cnfParse, "Main", "nope", tmpConf.CNF_BOOL, False
) is False
assert tmpConf._parseLine(
cnfParse, "Main", "val_string", tmpConf.CNF_BOOL, False
) is False
assert tmpConf._parseLine(
cnfParse, "Main", "val_list_string", tmpConf.CNF_S_LST, ["W", "X", "Y", "Z"]
) == ["A", "B", "C", "Z"]
assert tmpConf._parseLine(
cnfParse, "Main", "nope", tmpConf.CNF_S_LST, ["W", "X", "Y", "Z"]
) == ["W", "X", "Y", "Z"]
assert tmpConf._parseLine(
cnfParse, "Main", "val_list_int", tmpConf.CNF_I_LST, [6, 7, 8, 9]
) == [1, 2, 3, 9]
assert tmpConf._parseLine(
cnfParse, "Main", "nope", tmpConf.CNF_S_LST, [6, 7, 8, 9]
) == [6, 7, 8, 9]
# Function _checkNone
assert tmpConf._checkNone(None) is None
assert tmpConf._checkNone("None") is None
assert tmpConf._checkNone("stuff") == "stuff"
# Function _checkOptionalPackages
# (Assumes enchant package exists ans is importable)
tmpConf._checkOptionalPackages()
assert tmpConf.hasEnchant is True
monkeypatch.setitem(sys.modules, "enchant", None)
tmpConf._checkOptionalPackages()
assert tmpConf.hasEnchant is False
monkeypatch.undo()
monkeypatch.setattr("shutil.which", lambda *args: "dummy")
tmpConf._checkOptionalPackages()
assert tmpConf.hasAssistant is True
monkeypatch.undo()
monkeypatch.setattr("shutil.which", lambda *args: None)
tmpConf._checkOptionalPackages()
assert tmpConf.hasAssistant is False
monkeypatch.undo()
# END Test testBaseConfig_Internal
+115
View File
@@ -0,0 +1,115 @@
# -*- coding: utf-8 -*-
"""
novelWriter Error Tester
==========================
This file is a part of novelWriter
Copyright 20182021, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
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 nw
import pytest
from PyQt5.QtWidgets import qApp
from dummy import causeException
from nw.error import NWErrorMessage, exceptionHandler
@pytest.mark.base
def testBaseError_Dialog(qtbot, monkeypatch, fncDir, tmpDir):
"""Test the error dialog.
"""
qApp.closeAllWindows()
nwGUI = nw.main(["--testmode", "--config=%s" % fncDir, "--data=%s" % tmpDir])
qtbot.addWidget(nwGUI)
nwGUI.show()
qtbot.waitForWindowShown(nwGUI)
nwErr = NWErrorMessage(nwGUI)
qtbot.addWidget(nwErr)
nwErr.show()
# Invalid Error Message
nwErr.setMessage(Exception, "Faulty Error", 123)
assert nwErr.msgBody.toPlainText() == "Failed to generate error report ..."
# Valid Error Message
monkeypatch.setattr("PyQt5.QtCore.QSysInfo.kernelVersion", lambda: "1.2.3")
nwErr.setMessage(Exception, "Fine Error", None)
theMessage = nwErr.msgBody.toPlainText()
assert theMessage
assert "Fine Error" in theMessage
assert "Exception" in theMessage
assert "(1.2.3)" in theMessage
monkeypatch.undo()
# No kernel version retrieved
monkeypatch.setattr("PyQt5.QtCore.QSysInfo.kernelVersion", causeException)
nwErr.setMessage(Exception, "Almost Fine Error", None)
theMessage = nwErr.msgBody.toPlainText()
assert theMessage
assert "(Unknown)" in theMessage
monkeypatch.undo()
nwErr._doClose()
nwErr.close()
nwGUI.closeMain()
# END Test testBaseError_Dialog
@pytest.mark.base
def testBaseError_Handler(qtbot, monkeypatch, fncDir, tmpDir):
"""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.
"""
qApp.closeAllWindows()
nwGUI = nw.main(["--testmode", "--config=%s" % fncDir, "--data=%s" % tmpDir])
qtbot.addWidget(nwGUI)
nwGUI.show()
qtbot.waitForWindowShown(nwGUI)
# Normal shutdown
monkeypatch.setattr(NWErrorMessage, "exec_", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.exit", lambda *args: None)
exceptionHandler(Exception, "Error Message", None)
monkeypatch.undo()
# Should not crash when no GUI is found
monkeypatch.setattr(NWErrorMessage, "exec_", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.exit", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.topLevelWidgets", lambda: [])
exceptionHandler(Exception, "Error Message", None)
monkeypatch.undo()
# Should handle qApp failing
monkeypatch.setattr(NWErrorMessage, "exec_", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.exit", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.topLevelWidgets", causeException)
exceptionHandler(Exception, "Error Message", None)
monkeypatch.undo()
# Should handle failing to close main GUI
monkeypatch.setattr(NWErrorMessage, "exec_", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.qApp.exit", lambda *args: None)
monkeypatch.setattr(nwGUI, "closeMain", causeException)
exceptionHandler(Exception, "Error Message", None)
monkeypatch.undo()
nwGUI.closeMain()
# END Test testBaseError_Handler
+180
View File
@@ -0,0 +1,180 @@
# -*- coding: utf-8 -*-
"""
novelWriter Main Init Tester
==============================
This file is a part of novelWriter
Copyright 20182021, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
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 nw
import pytest
import logging
import sys
from dummy import DummyMain
@pytest.mark.base
def testBaseInit_Launch(caplog, monkeypatch, tmpDir):
"""Check launching the main GUI.
"""
monkeypatch.setattr("nw.guimain.GuiMain", DummyMain)
# Testmode launch
nwGUI = nw.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert isinstance(nwGUI, DummyMain)
# Darwin launch
monkeypatch.setitem(sys.modules, "Foundation", None)
osDarwin = nw.CONFIG.osDarwin
nw.CONFIG.osDarwin = True
nwGUI = nw.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert isinstance(nwGUI, DummyMain)
assert "Foundation" in caplog.messages[1]
nw.CONFIG.osDarwin = osDarwin
# Normal launch
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.__init__", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.setApplicationName", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.setApplicationVersion", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.setWindowIcon", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.setOrganizationDomain", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.exec_", lambda *args: 0)
with pytest.raises(SystemExit) as ex:
nw.main(["--config=%s" % tmpDir, "--data=%s" % tmpDir])
assert ex.value.code == 0
monkeypatch.undo()
# END Test testBaseInit_Launch
@pytest.mark.base
def testBaseInit_Options(monkeypatch, tmpDir):
"""Test command line options for logging level.
"""
monkeypatch.setattr("nw.guimain.GuiMain", DummyMain)
monkeypatch.setattr(sys, "argv", [
"novelWriter.py", "--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir
])
# Defaults w/None Args
nwGUI = nw.main()
assert nw.logger.getEffectiveLevel() == logging.WARNING
assert nw.CONFIG.debugInfo is False
assert nwGUI.closeMain() == "closeMain"
# Defaults
nwGUI = nw.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir, "--style=Fusion"]
)
assert nw.logger.getEffectiveLevel() == logging.WARNING
assert nw.CONFIG.debugInfo is False
assert nwGUI.closeMain() == "closeMain"
# Log Levels
nwGUI = nw.main(
["--testmode", "--info", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nw.logger.getEffectiveLevel() == logging.INFO
assert nw.CONFIG.debugInfo is False
assert nwGUI.closeMain() == "closeMain"
nwGUI = nw.main(
["--testmode", "--debug", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nw.logger.getEffectiveLevel() == logging.DEBUG
assert nw.CONFIG.debugInfo is True
assert nwGUI.closeMain() == "closeMain"
nwGUI = nw.main(
["--testmode", "--verbose", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nw.logger.getEffectiveLevel() == 5
assert nw.CONFIG.debugInfo is True
assert nwGUI.closeMain() == "closeMain"
# Help and Version
with pytest.raises(SystemExit) as ex:
nwGUI = nw.main(
["--testmode", "--help", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 0
with pytest.raises(SystemExit) as ex:
nwGUI = nw.main(
["--testmode", "--version", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 0
# Invalid options
with pytest.raises(SystemExit) as ex:
nwGUI = nw.main(
["--testmode", "--invalid", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert nwGUI.closeMain() == "closeMain"
assert ex.value.code == 2
# Project Path
nwGUI = nw.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir, "sample/"]
)
assert nw.CONFIG.cmdOpen == "sample/"
assert nwGUI.closeMain() == "closeMain"
monkeypatch.undo()
# END Test testBaseInit_Options
@pytest.mark.base
def testBaseInit_Imports(caplog, monkeypatch, tmpDir):
"""Check import error handling.
"""
monkeypatch.setattr("nw.guimain.GuiMain", DummyMain)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.__init__", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QApplication.exec_", lambda *args: 0)
monkeypatch.setattr("PyQt5.QtWidgets.QErrorMessage.__init__", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QErrorMessage.resize", lambda *args: None)
monkeypatch.setattr("PyQt5.QtWidgets.QErrorMessage.showMessage", lambda *args: None)
monkeypatch.setitem(sys.modules, "lxml", None)
monkeypatch.setattr("sys.hexversion", 0x0)
monkeypatch.setattr("nw.CONFIG.verQtValue", 50000)
monkeypatch.setattr("nw.CONFIG.verPyQtValue", 50000)
with pytest.raises(SystemExit) as ex:
_ = nw.main(
["--testmode", "--config=%s" % tmpDir, "--data=%s" % tmpDir]
)
assert ex.value.code & 4 == 4 # Python version not satisfied
assert ex.value.code & 8 == 8 # Qt version not satisfied
assert ex.value.code & 16 == 16 # PyQt version not satisfied
assert ex.value.code & 32 == 32 # lxml package missing
assert "At least Python" in caplog.messages[0]
assert "At least Qt5" in caplog.messages[1]
assert "At least PyQt5" in caplog.messages[2]
assert "lxml" in caplog.messages[3]
monkeypatch.undo()
# END Test testBaseInit_Imports