Fix linting errors in the tests

This commit is contained in:
Veronica Berglyd Olsen
2025-04-07 17:20:31 +02:00
parent 8ed3bd889d
commit 9b93736985
13 changed files with 57 additions and 65 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ initFile = os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, os.path.dirname(__file__), os.pardir, os.pardir,
"novelwriter", "__init__.py" "novelwriter", "__init__.py"
) )
with open(initFile) as inFile: with open(initFile, encoding="utf-8") as inFile:
for aLine in inFile: for aLine in inFile:
if aLine.startswith("__version__"): if aLine.startswith("__version__"):
release = aLine.split('"')[1].strip() release = aLine.split('"')[1].strip()
+4 -4
View File
@@ -33,10 +33,10 @@ from PyQt6.QtWidgets import QMessageBox
sys.path.insert(1, str(Path(__file__).parent.parent.absolute())) sys.path.insert(1, str(Path(__file__).parent.parent.absolute()))
from novelwriter import CONFIG, SHARED # noqa: E402 from novelwriter import CONFIG, SHARED
from tests.mocked import MockGuiMain, MockTheme # noqa: E402 from tests.mocked import MockGuiMain, MockTheme
from tests.tools import cleanProject # noqa: E402 from tests.tools import cleanProject
_TST_ROOT = Path(__file__).parent _TST_ROOT = Path(__file__).parent
_TMP_ROOT = _TST_ROOT / "temp" _TMP_ROOT = _TST_ROOT / "temp"
@@ -89,7 +89,7 @@ def functionFixture(qtbot):
shutil.rmtree(_TMP_CONF) shutil.rmtree(_TMP_CONF)
_TMP_CONF.mkdir() _TMP_CONF.mkdir()
CONFIG.__init__() CONFIG.__init__() # noqa: PLC2801
CONFIG.initConfig(confPath=_TMP_CONF, dataPath=_TMP_CONF) CONFIG.initConfig(confPath=_TMP_CONF, dataPath=_TMP_CONF)
resetConfigVars() resetConfigVars()
logging.getLogger("novelwriter").setLevel(logging.INFO) logging.getLogger("novelwriter").setLevel(logging.INFO)
+3 -2
View File
@@ -1,4 +1,5 @@
pytest>=6.0.0 coverage>=7.2.0
pytest-timeout
pytest-cov pytest-cov
pytest-qt pytest-qt
pytest-timeout
pytest>=6.0.0
+1 -1
View File
@@ -556,7 +556,7 @@ def testBaseCommon_jsonEncode():
# Correct types # Correct types
assert jsonEncode([1, 2]) == "[\n 1,\n 2\n]" assert jsonEncode([1, 2]) == "[\n 1,\n 2\n]"
assert jsonEncode((1, 2)) == "[\n 1,\n 2\n]" assert jsonEncode((1, 2)) == "[\n 1,\n 2\n]"
assert jsonEncode({1: 2}) == "{\n \"1\": 2\n}" assert jsonEncode({1: 2}) == '{\n "1": 2\n}'
tstDict = { tstDict = {
"null": None, "null": None,
+2 -2
View File
@@ -141,8 +141,8 @@ def testBaseConfig_InitLoadSave(monkeypatch, fncPath, tstPaths):
assert newConf.guiSyntax == "bar" assert newConf.guiSyntax == "bar"
# Test Correcting Quote Settings # Test Correcting Quote Settings
tstConf.fmtDQuoteOpen = "\"" tstConf.fmtDQuoteOpen = '"'
tstConf.fmtDQuoteClose = "\"" tstConf.fmtDQuoteClose = '"'
tstConf.fmtSQuoteOpen = "'" tstConf.fmtSQuoteOpen = "'"
tstConf.fmtSQuoteClose = "'" tstConf.fmtSQuoteClose = "'"
tstConf.doReplaceDQuote = True tstConf.doReplaceDQuote = True
+1 -1
View File
@@ -768,7 +768,7 @@ def testCoreTools_ProjectBuilderSample(monkeypatch, mockGUI, fncPath, tstPaths):
assert builder.buildProject(data) is False assert builder.buildProject(data) is False
# Create and open a defective zip file # Create and open a defective zip file
with open(dstSample, mode="w+") as outFile: with open(dstSample, mode="w+", encoding="utf-8") as outFile:
outFile.write("foo") outFile.write("foo")
assert builder.buildProject(data) is False assert builder.buildProject(data) is False
+8 -6
View File
@@ -42,6 +42,8 @@ from tests.tools import cmpFiles, writeFile
class MockProject: class MockProject:
"""Fake project object.""" """Fake project object."""
data: NWProjectData
def setProjectChanged(self, *a): def setProjectChanged(self, *a):
"""Fake project method.""" """Fake project method."""
pass pass
@@ -219,7 +221,7 @@ def testCoreProjectXML_ReadCurrent(monkeypatch, mockGUI, tstPaths, fncPath):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
item.unpack(entry) item.unpack(entry)
@@ -348,7 +350,7 @@ def testCoreProjectXML_ReadLegacy10(tstPaths, fncPath, mockGUI, mockRnd):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
status = {} status = {}
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
@@ -493,7 +495,7 @@ def testCoreProjectXML_ReadLegacy11(tstPaths, fncPath, mockGUI, mockRnd):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
status = {} status = {}
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
@@ -638,7 +640,7 @@ def testCoreProjectXML_ReadLegacy12(tstPaths, fncPath, mockGUI, mockRnd):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
status = {} status = {}
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
@@ -786,7 +788,7 @@ def testCoreProjectXML_ReadLegacy13(tstPaths, fncPath, mockGUI, mockRnd):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
status = {} status = {}
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
@@ -933,7 +935,7 @@ def testCoreProjectXML_ReadLegacy14(tstPaths, fncPath, mockGUI, mockRnd):
packedContent = [] packedContent = []
mockProject = MockProject() mockProject = MockProject()
mockProject.__setattr__("data", data) mockProject.data = data
status = {} status = {}
for entry in content: for entry in content:
item = NWItem(mockProject, "0000000000000") # type: ignore item = NWItem(mockProject, "0000000000000") # type: ignore
+10 -18
View File
@@ -982,7 +982,7 @@ def testFmtToOdt_SaveFull(mockGUI, fncPath, tstPaths, ipsumText):
def prettifyXml(inFile, outFile): def prettifyXml(inFile, outFile):
with open(outFile, mode="wb") as fStream: with open(outFile, mode="wb") as fStream:
xml = ET.parse(inFile) xml = ET.parse(inFile)
xmlIndent(xml) xmlIndent(xml.getroot())
xml.write(fStream, encoding="utf-8", xml_declaration=True) xml.write(fStream, encoding="utf-8", xml_declaration=True)
prettifyXml(maniOut, maniFile) prettifyXml(maniOut, maniFile)
@@ -1082,10 +1082,6 @@ def testFmtToOdt_ODTParagraphStyle():
assert parStyle._pAttr["text-align"] == ["fo", "end"] assert parStyle._pAttr["text-align"] == ["fo", "end"]
parStyle.setTextAlign("justify") parStyle.setTextAlign("justify")
assert parStyle._pAttr["text-align"] == ["fo", "justify"] assert parStyle._pAttr["text-align"] == ["fo", "justify"]
parStyle.setTextAlign("inside")
assert parStyle._pAttr["text-align"] == ["fo", "inside"]
parStyle.setTextAlign("outside")
assert parStyle._pAttr["text-align"] == ["fo", "outside"]
parStyle.setTextAlign("left") parStyle.setTextAlign("left")
assert parStyle._pAttr["text-align"] == ["fo", "left"] assert parStyle._pAttr["text-align"] == ["fo", "left"]
parStyle.setTextAlign("right") parStyle.setTextAlign("right")
@@ -1099,8 +1095,6 @@ def testFmtToOdt_ODTParagraphStyle():
assert parStyle._pAttr["break-before"] == ["fo", None] assert parStyle._pAttr["break-before"] == ["fo", None]
parStyle.setBreakBefore("auto") parStyle.setBreakBefore("auto")
assert parStyle._pAttr["break-before"] == ["fo", "auto"] assert parStyle._pAttr["break-before"] == ["fo", "auto"]
parStyle.setBreakBefore("column")
assert parStyle._pAttr["break-before"] == ["fo", "column"]
parStyle.setBreakBefore("page") parStyle.setBreakBefore("page")
assert parStyle._pAttr["break-before"] == ["fo", "page"] assert parStyle._pAttr["break-before"] == ["fo", "page"]
parStyle.setBreakBefore("even-page") parStyle.setBreakBefore("even-page")
@@ -1118,8 +1112,6 @@ def testFmtToOdt_ODTParagraphStyle():
assert parStyle._pAttr["break-after"] == ["fo", None] assert parStyle._pAttr["break-after"] == ["fo", None]
parStyle.setBreakAfter("auto") parStyle.setBreakAfter("auto")
assert parStyle._pAttr["break-after"] == ["fo", "auto"] assert parStyle._pAttr["break-after"] == ["fo", "auto"]
parStyle.setBreakAfter("column")
assert parStyle._pAttr["break-after"] == ["fo", "column"]
parStyle.setBreakAfter("page") parStyle.setBreakAfter("page")
assert parStyle._pAttr["break-after"] == ["fo", "page"] assert parStyle._pAttr["break-after"] == ["fo", "page"]
parStyle.setBreakAfter("even-page") parStyle.setBreakAfter("even-page")
@@ -1394,9 +1386,9 @@ def testFmtToOdt_XMLParagraph():
# Plain Text # Plain Text
xmlPar.appendText("Hello World") xmlPar.appendText("Hello World")
assert xmlToText(xRoot) == ( assert xmlToText(xRoot) == (
'<root>' "<root>"
'<text:p>Hello World</text:p>' "<text:p>Hello World</text:p>"
'</root>' "</root>"
) )
# Text Span # Text Span
@@ -1431,9 +1423,9 @@ def testFmtToOdt_XMLParagraph():
# Plain Text w/Line Break # Plain Text w/Line Break
xmlPar.appendText("Hello\nWorld\n!!") xmlPar.appendText("Hello\nWorld\n!!")
assert xmlToText(xRoot) == ( assert xmlToText(xRoot) == (
'<root>' "<root>"
'<text:p>Hello<text:line-break />World<text:line-break />!!</text:p>' "<text:p>Hello<text:line-break />World<text:line-break />!!</text:p>"
'</root>' "</root>"
) )
# Text Span w/Line Break # Text Span w/Line Break
@@ -1467,9 +1459,9 @@ def testFmtToOdt_XMLParagraph():
# Plain Text w/Line Break # Plain Text w/Line Break
xmlPar.appendText("Hello\tWorld\t!!") xmlPar.appendText("Hello\tWorld\t!!")
assert xmlToText(xRoot) == ( assert xmlToText(xRoot) == (
'<root>' "<root>"
'<text:p>Hello<text:tab />World<text:tab />!!</text:p>' "<text:p>Hello<text:tab />World<text:tab />!!</text:p>"
'</root>' "</root>"
) )
# Text Span w/Line Break # Text Span w/Line Break
+1 -1
View File
@@ -763,7 +763,7 @@ def testGuiEditor_Actions(qtbot, nwGUI, projPath, ipsumText, mockRnd):
assert docEditor.getText() == text.replace("consectetur", "\u2018consectetur\u2019") assert docEditor.getText() == text.replace("consectetur", "\u2018consectetur\u2019")
# Replace Double Quotes # Replace Double Quotes
repText = text.replace("consectetur", "\"consectetur\"") repText = text.replace("consectetur", '"consectetur"')
docEditor.replaceText(repText) docEditor.replaceText(repText)
assert docEditor.docAction(nwDocAction.SEL_ALL) is True assert docEditor.docAction(nwDocAction.SEL_ALL) is True
assert docEditor.docAction(nwDocAction.REPL_DBL) is True assert docEditor.docAction(nwDocAction.REPL_DBL) is True
+7 -6
View File
@@ -116,7 +116,8 @@ def testGuiMain_Launch(qtbot, monkeypatch, nwGUI, projPath):
# Check that project open dialog launches # Check that project open dialog launches
nwGUI.postLaunchTasks(None) nwGUI.postLaunchTasks(None)
qtbot.waitUntil(lambda: SHARED.findTopLevelWidget(GuiWelcome) is not None, timeout=1000) qtbot.waitUntil(lambda: SHARED.findTopLevelWidget(GuiWelcome) is not None, timeout=1000)
assert isinstance(welcome := SHARED.findTopLevelWidget(GuiWelcome), GuiWelcome) welcome = SHARED.findTopLevelWidget(GuiWelcome)
assert isinstance(welcome, GuiWelcome)
welcome.show() welcome.show()
welcome.close() welcome.close()
@@ -454,7 +455,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, projPath, tstPaths, mockRnd):
# Dialogue # Dialogue
# ======== # ========
for c in "\"Full line double quoted text.\"": for c in '"Full line double quoted text."':
qtbot.keyClick(docEditor, c, delay=KEY_DELAY) qtbot.keyClick(docEditor, c, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
@@ -469,7 +470,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, projPath, tstPaths, mockRnd):
CONFIG.fmtPadAfter = "\u201c" CONFIG.fmtPadAfter = "\u201c"
docEditor.initEditor() docEditor.initEditor()
for c in "Some \"double quoted text with spaces padded\".": for c in 'Some "double quoted text with spaces padded".':
qtbot.keyClick(docEditor, c, delay=KEY_DELAY) qtbot.keyClick(docEditor, c, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
@@ -533,17 +534,17 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, projPath, tstPaths, mockRnd):
# ================ # ================
nwGUI._switchFocus(nwView.EDITOR) nwGUI._switchFocus(nwView.EDITOR)
for c in "\t\"Tab-indented text\"": for c in '\t"Tab-indented text"':
qtbot.keyClick(docEditor, c, delay=KEY_DELAY) qtbot.keyClick(docEditor, c, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
for c in ">\"Paragraph-indented text\"": for c in '>"Paragraph-indented text"':
qtbot.keyClick(docEditor, c, delay=KEY_DELAY) qtbot.keyClick(docEditor, c, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
for c in ">>\"Right-aligned text\"": for c in '>>"Right-aligned text"':
qtbot.keyClick(docEditor, c, delay=KEY_DELAY) qtbot.keyClick(docEditor, c, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY) qtbot.keyClick(docEditor, Qt.Key.Key_Return, delay=KEY_DELAY)
+4 -4
View File
@@ -279,7 +279,7 @@ def testGuiMainMenu_EditFormat(qtbot, monkeypatch, nwGUI, prjLipsum):
docEditor.setPlainText( docEditor.setPlainText(
"### New Text\n\n" "### New Text\n\n"
"Text with 'single' quotes and 'tricky stuff's'.\n\n" "Text with 'single' quotes and 'tricky stuff's'.\n\n"
"Also text with \"double\" quotes which are \"less tricky\".\n\n" 'Also text with "double" quotes which are "less tricky".\n\n'
) )
mainMenu.aSelectAll.activate(QAction.ActionEvent.Trigger) mainMenu.aSelectAll.activate(QAction.ActionEvent.Trigger)
@@ -287,7 +287,7 @@ def testGuiMainMenu_EditFormat(qtbot, monkeypatch, nwGUI, prjLipsum):
assert docEditor.getText() == ( assert docEditor.getText() == (
"### New Text\n\n" "### New Text\n\n"
"Text with single quotes and tricky stuffs.\n\n" "Text with single quotes and tricky stuffs.\n\n"
"Also text with \"double\" quotes which are \"less tricky\".\n\n" 'Also text with "double" quotes which are "less tricky".\n\n'
) )
mainMenu.aSelectAll.activate(QAction.ActionEvent.Trigger) mainMenu.aSelectAll.activate(QAction.ActionEvent.Trigger)
@@ -347,7 +347,7 @@ def testGuiMainMenu_EditFormat(qtbot, monkeypatch, nwGUI, prjLipsum):
"### New Text\n\n" "### New Text\n\n"
"@tag: Bod\n\n" "@tag: Bod\n\n"
"Text with 'single' quotes and 'tricky stuff's'.\n\n" "Text with 'single' quotes and 'tricky stuff's'.\n\n"
"Also text with \"double\" quotes which are \"less tricky\".\n\n" 'Also text with "double" quotes which are "less tricky".\n\n'
) )
# Cannot Format Tag # Cannot Format Tag
@@ -363,7 +363,7 @@ def testGuiMainMenu_EditFormat(qtbot, monkeypatch, nwGUI, prjLipsum):
"### New Text\n\n" "### New Text\n\n"
"@tag: Bod\n\n" "@tag: Bod\n\n"
"Text with 'single' quotes and 'tricky stuff's'.\n\n" "Text with 'single' quotes and 'tricky stuff's'.\n\n"
"Also text with \"double\" quotes which are \"less tricky\".\n\n" 'Also text with "double" quotes which are "less tricky".\n\n'
) )
# qtbot.stop() # qtbot.stop()
+14 -17
View File
@@ -29,15 +29,12 @@ from novelwriter.constants import nwUnicode
from novelwriter.text.patterns import REGEX_PATTERNS, DialogParser from novelwriter.text.patterns import REGEX_PATTERNS, DialogParser
def allMatches(regEx: re.Pattern, text: str) -> list[list[str]]: def allMatches(regEx: re.Pattern, text: str) -> list[list[tuple[str, int, int]]]:
"""Get all matches for a regex.""" """Get all matches for a regex."""
result = [] return [
for res in regEx.finditer(text): [(res.group(n), res.start(n), res.end(n)) for n in range((res.lastindex or 0) + 1)]
result.append([ for res in regEx.finditer(text)
(res.group(n), res.start(n), res.end(n)) ]
for n in range((res.lastindex or 0) + 1)
])
return result
@pytest.mark.core @pytest.mark.core
@@ -310,7 +307,7 @@ def testTextPatterns_DialogueStyle():
assert allMatches(regEx, "one 'two' three") == [] assert allMatches(regEx, "one 'two' three") == []
# Straight double quotes are ignored # Straight double quotes are ignored
assert allMatches(regEx, "one \"two\" three") == [] assert allMatches(regEx, 'one "two" three') == []
# Check with no whitespace, single quote # Check with no whitespace, single quote
assert allMatches(regEx, "one\u2018two\u2019three") == [ assert allMatches(regEx, "one\u2018two\u2019three") == [
@@ -370,19 +367,19 @@ def testTextPatterns_DialoguePlain():
# ====== # ======
# One double quoted string # One double quoted string
assert allMatches(regEx, "one \"two\" three") == [ assert allMatches(regEx, 'one "two" three') == [
[("\"two\"", 4, 9)] [('"two"', 4, 9)]
] ]
# Two double quoted strings # Two double quoted strings
assert allMatches(regEx, "one \"two\" three \"four\" five") == [ assert allMatches(regEx, 'one "two" three "four" five') == [
[("\"two\"", 4, 9)], [("\"four\"", 16, 22)], [('"two"', 4, 9)], [('"four"', 16, 22)],
] ]
# No space # No space
assert allMatches(regEx, "one\"two\" three") == [] assert allMatches(regEx, 'one"two" three') == []
assert allMatches(regEx, "one \"two\"three") == [] assert allMatches(regEx, 'one "two"three') == []
assert allMatches(regEx, "one\"two\"three") == [] assert allMatches(regEx, 'one"two"three') == []
# Single # Single
# ====== # ======
@@ -595,6 +592,6 @@ def testTextPatterns_DialogParserPolish():
] ]
assert parser( assert parser(
"And so on and so forth. However, \"text in quotation marks\" should not be " 'And so on and so forth. However, "text in quotation marks" should not be '
"highlighted at all, and if so, it should be highlighted differently." "highlighted at all, and if so, it should be highlighted differently."
) == [] ) == []
+1 -2
View File
@@ -83,8 +83,7 @@ def testToolManuscriptBuild_Main(
if item.data(manus.D_KEY) == fmt: if item.data(manus.D_KEY) == fmt:
manus.listFormats.setCurrentItem(item) manus.listFormats.setCurrentItem(item)
return return
else: raise ValueError("No such key in format list")
raise ValueError("No such key in format list")
# Build documents # Build documents
lastFmt = None lastFmt = None