refactor: Fix flake8 violations under tests/ directory

This commit is contained in:
Takeshi KOMIYA 2020-11-15 17:03:26 +09:00
parent 5a42348fd7
commit 21a3bd4127
15 changed files with 43 additions and 40 deletions

View File

@ -20,7 +20,7 @@ from test_build_html import ENV_WARNINGS
from sphinx.builders.latex import default_latex_documents
from sphinx.config import Config
from sphinx.errors import SphinxError, ThemeError
from sphinx.errors import SphinxError
from sphinx.testing.util import strip_escseq
from sphinx.util import docutils
from sphinx.util.osutil import cd, ensuredir
@ -763,7 +763,7 @@ def test_reference_in_caption_and_codeblock_in_footnote(app, status, warning):
assert ('\\caption{This is the figure caption with a footnote to '
'\\sphinxfootnotemark[7].}\\label{\\detokenize{index:id29}}\\end{figure}\n'
'%\n\\begin{footnotetext}[7]\\sphinxAtStartFootnote\n'
'Footnote in caption\n%\n\\end{footnotetext}')in result
'Footnote in caption\n%\n\\end{footnotetext}') in result
assert ('\\sphinxcaption{footnote \\sphinxfootnotemark[8] in '
'caption of normal table}\\label{\\detokenize{index:id30}}') in result
assert ('\\caption{footnote \\sphinxfootnotemark[9] '

View File

@ -10,9 +10,7 @@
import http.server
import json
import re
import textwrap
from unittest import mock
import pytest
import requests
@ -59,7 +57,7 @@ def test_defaults_json(app):
assert len(rows) == 10
# the output order of the rows is not stable
# due to possible variance in network latency
rowsby = {row["uri"]:row for row in rows}
rowsby = {row["uri"]: row for row in rows}
assert rowsby["https://www.google.com#!bar"] == {
'filename': 'links.txt',
'lineno': 10,
@ -112,6 +110,7 @@ def test_anchors_ignored(app):
# expect all ok when excluding #top
assert not content
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-anchor', freshenv=True)
def test_raises_for_invalid_status(app):
class InternalServerErrorHandler(http.server.BaseHTTPRequestHandler):
@ -137,6 +136,7 @@ class HeadersDumperHandler(http.server.BaseHTTPRequestHandler):
self.end_headers()
print(self.headers.as_string())
@pytest.mark.sphinx(
'linkcheck', testroot='linkcheck-localserver', freshenv=True,
confoverrides={'linkcheck_auth': [
@ -212,6 +212,7 @@ def test_linkcheck_request_headers_default(app, capsys):
assert "Accepts: application/json\n" not in stdout
assert "X-Secret: open sesami\n" in stdout
def make_redirect_handler(*, support_head):
class RedirectOnceHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
@ -235,6 +236,7 @@ def make_redirect_handler(*, support_head):
return RedirectOnceHandler
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver', freshenv=True)
def test_follows_redirects_on_HEAD(app, capsys):
with http_server(make_redirect_handler(support_head=True)):
@ -252,6 +254,7 @@ def test_follows_redirects_on_HEAD(app, capsys):
"""
)
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver', freshenv=True)
def test_follows_redirects_on_GET(app, capsys):
with http_server(make_redirect_handler(support_head=False)):
@ -280,6 +283,7 @@ class OKHandler(http.server.BaseHTTPRequestHandler):
self.do_HEAD()
self.wfile.write(b"ok\n")
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_invalid_ssl(app):
# Link indicates SSL should be used (https) but the server does not handle it.
@ -294,6 +298,7 @@ def test_invalid_ssl(app):
assert content["uri"] == "https://localhost:7777/"
assert "SSLError" in content["info"]
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_connect_to_selfsigned_fails(app):
with https_server(OKHandler):
@ -307,6 +312,7 @@ def test_connect_to_selfsigned_fails(app):
assert content["uri"] == "https://localhost:7777/"
assert "[SSL: CERTIFICATE_VERIFY_FAILED]" in content["info"]
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_connect_to_selfsigned_with_tls_verify_false(app):
app.config.tls_verify = False
@ -324,6 +330,7 @@ def test_connect_to_selfsigned_with_tls_verify_false(app):
"info": "",
}
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_connect_to_selfsigned_with_tls_cacerts(app):
app.config.tls_cacerts = CERT_FILE
@ -341,10 +348,11 @@ def test_connect_to_selfsigned_with_tls_cacerts(app):
"info": "",
}
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_connect_to_selfsigned_with_requests_env_var(app):
with modify_env(REQUESTS_CA_BUNDLE=CERT_FILE), https_server(OKHandler):
app.builder.build_all()
app.builder.build_all()
with open(app.outdir / 'output.json') as fp:
content = json.load(fp)
@ -357,6 +365,7 @@ def test_connect_to_selfsigned_with_requests_env_var(app):
"info": "",
}
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver-https', freshenv=True)
def test_connect_to_selfsigned_nonexistent_cert_file(app):
app.config.tls_cacerts = "does/not/exist"

View File

@ -75,12 +75,12 @@ def _check(name, input, idDict, output, key, asTextOutput):
idExpected.append(idExpected[i - 1])
idActual = [None]
for i in range(1, _max_id + 1):
#try:
# try:
id = ast.get_id(version=i)
assert id is not None
idActual.append(id[len(_id_prefix[i]):])
#except NoOldIdError:
# idActual.append(None)
# except NoOldIdError:
# idActual.append(None)
res = [True]
for i in range(1, _max_id + 1):
@ -94,7 +94,7 @@ def _check(name, input, idDict, output, key, asTextOutput):
print("Error in id version %d." % i)
print("result: %s" % idActual[i])
print("expected: %s" % idExpected[i])
#print(rootSymbol.dump(0))
# print(rootSymbol.dump(0))
raise DefinitionError("")
@ -106,7 +106,7 @@ def check(name, input, idDict, output=None, key=None, asTextOutput=None):
if name != 'macro':
# Second, check with semicolon
_check(name, input + ' ;', idDict, output + ';', key,
asTextOutput + ';' if asTextOutput is not None else None)
asTextOutput + ';' if asTextOutput is not None else None)
def test_expressions():
@ -482,7 +482,7 @@ def test_attributes():
# style: user-defined paren
check('member', 'paren_attr() int f', {1: 'f'})
check('member', 'paren_attr(a) int f', {1: 'f'})
check('member', 'paren_attr("") int f',{1: 'f'})
check('member', 'paren_attr("") int f', {1: 'f'})
check('member', 'paren_attr(()[{}][]{}) int f', {1: 'f'})
with pytest.raises(DefinitionError):
parse('member', 'paren_attr(() int f')
@ -521,7 +521,7 @@ def test_attributes():
def filter_warnings(warning, file):
lines = warning.getvalue().split("\n");
lines = warning.getvalue().split("\n")
res = [l for l in lines if "domain-c" in l and "{}.rst".format(file) in l and
"WARNING: document isn't included in any toctree" not in l]
print("Filtered warnings for file '{}':".format(file))
@ -602,6 +602,7 @@ def _get_obj(app, queryName):
return (docname, anchor, objectType)
return (queryName, "not", "found")
def test_cfunction(app):
text = (".. c:function:: PyObject* "
"PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)")

View File

@ -182,9 +182,9 @@ def test_expressions():
expr = i + l + u
exprCheck(expr, 'L' + expr + 'E')
decimalFloats = ['5e42', '5e+42', '5e-42',
'5.', '5.e42', '5.e+42', '5.e-42',
'.5', '.5e42', '.5e+42', '.5e-42',
'5.0', '5.0e42', '5.0e+42', '5.0e-42']
'5.', '5.e42', '5.e+42', '5.e-42',
'.5', '.5e42', '.5e+42', '.5e-42',
'5.0', '5.0e42', '5.0e+42', '5.0e-42']
hexFloats = ['ApF', 'Ap+F', 'Ap-F',
'A.', 'A.pF', 'A.p+F', 'A.p-F',
'.A', '.ApF', '.Ap+F', '.Ap-F',
@ -425,9 +425,9 @@ def test_member_definitions():
check('member', 'int b : 8 = 42', {1: 'b__i', 2: '1b'})
check('member', 'int b : 8{42}', {1: 'b__i', 2: '1b'})
# TODO: enable once the ternary operator is supported
#check('member', 'int b : true ? 8 : a = 42', {1: 'b__i', 2: '1b'})
# check('member', 'int b : true ? 8 : a = 42', {1: 'b__i', 2: '1b'})
# TODO: enable once the ternary operator is supported
#check('member', 'int b : (true ? 8 : a) = 42', {1: 'b__i', 2: '1b'})
# check('member', 'int b : (true ? 8 : a) = 42', {1: 'b__i', 2: '1b'})
check('member', 'int b : 1 || new int{0}', {1: 'b__i', 2: '1b'})
@ -537,8 +537,8 @@ def test_function_definitions():
check('function', 'int foo(const A*...)', {1: "foo__ACPDp", 2: "3fooDpPK1A"})
check('function', 'int foo(const int A::*... a)', {2: "3fooDpM1AKi"})
check('function', 'int foo(const int A::*...)', {2: "3fooDpM1AKi"})
#check('function', 'int foo(int (*a)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
#check('function', 'int foo(int (*)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
# check('function', 'int foo(int (*a)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
# check('function', 'int foo(int (*)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
check('function', 'virtual void f()', {1: "f", 2: "1fv"})
# test for ::nestedName, from issue 1738
check("function", "result(int val, ::std::error_category const &cat)",
@ -707,7 +707,6 @@ def test_class_definitions():
check('class', 'template<class T> {key}has_var<T, std::void_t<decltype(&T::var)>>',
{2: 'I0E7has_varI1TNSt6void_tIDTadN1T3varEEEEE'})
check('class', 'template<typename ...Ts> {key}T<int (*)(Ts)...>',
{2: 'IDpE1TIJPFi2TsEEE'})
check('class', 'template<int... Is> {key}T<(Is)...>',
@ -1250,4 +1249,4 @@ def test_mix_decl_duplicate(app, warning):
assert "Declaration is '.. cpp:function:: void A()'." in ws[1]
assert "index.rst:3: WARNING: Duplicate C++ declaration, also defined at index:1." in ws[2]
assert "Declaration is '.. cpp:struct:: A'." in ws[3]
assert ws[4] == ""
assert ws[4] == ""

View File

@ -333,7 +333,7 @@ def test_multiple_cmdoptions(app):
def test_productionlist(app, status, warning):
app.builder.build_all()
warnings = warning.getvalue().split("\n");
warnings = warning.getvalue().split("\n")
assert len(warnings) == 2
assert warnings[-1] == ''
assert "Dup2.rst:4: WARNING: duplicate token description of Dup, other instance in Dup1" in warnings[0]

View File

@ -177,7 +177,6 @@ def test_format_signature(app):
for C in (D, E):
assert formatsig('class', 'D', C, None, None) == '()'
class SomeMeta(type):
def __call__(cls, a, b=None):
return type.__call__(cls, a, b)
@ -209,7 +208,6 @@ def test_format_signature(app):
assert formatsig('class', 'C', C, None, None) == '(a, b=None)'
assert formatsig('class', 'C', D, 'a, b', 'X') == '(a, b) -> X'
class ListSubclass(list):
pass
@ -219,7 +217,6 @@ def test_format_signature(app):
else:
assert formatsig('class', 'C', ListSubclass, None, None) == ''
class ExceptionSubclass(Exception):
pass
@ -227,7 +224,6 @@ def test_format_signature(app):
if getattr(Exception, '__text_signature__', None) is None:
assert formatsig('class', 'C', ExceptionSubclass, None, None) == ''
# __init__ have signature at first line of docstring
directive.env.config.autoclass_content = 'both'

View File

@ -11,7 +11,6 @@
import http.server
import os
import unittest
from io import BytesIO
from unittest import mock
import pytest

View File

@ -1070,7 +1070,7 @@ Methods:
description
"""
""" # NOQA
config = Config()
actual = str(GoogleDocstring(docstring, config=config, app=None, what='module',
options={'noindex': True}))
@ -2222,7 +2222,7 @@ definition_after_normal_text : int
["{", "'F'", ", ", "'C'", ", ", "'N or C'", "}", ", ", "default", " ", "'F'"],
["str", ", ", "default", ": ", "'F or C'"],
["int", ", ", "default", ": ", "None"],
["int", ", " , "default", " ", "None"],
["int", ", ", "default", " ", "None"],
["int", ", ", "default", " ", ":obj:`None`"],
['"ma{icious"'],
[r"'with \'quotes\''"],

View File

@ -17,7 +17,6 @@ from docutils.parsers.rst import Parser as RstParser
from sphinx import addnodes
from sphinx.builders.html.transforms import KeyboardTransform
from sphinx.builders.latex import LaTeXBuilder
from sphinx.builders.latex.theming import ThemeFactory
from sphinx.roles import XRefRole
from sphinx.testing.util import Struct, assert_node
from sphinx.transforms import SphinxSmartQuotes

View File

@ -13,7 +13,6 @@ from collections import OrderedDict
import pytest
from sphinx.project import Project
from sphinx.testing.comparer import PathComparer
def test_project_discover(rootdir):

View File

@ -19,6 +19,7 @@ from sphinx.pycode import ModuleAnalyzer
SPHINX_MODULE_PATH = os.path.splitext(sphinx.__file__)[0] + '.py'
def test_ModuleAnalyzer_get_module_source():
assert ModuleAnalyzer.get_module_source('sphinx') == (sphinx.__file__, sphinx.__loader__.get_source('sphinx'))

View File

@ -14,8 +14,7 @@ from unittest.mock import patch
import pytest
import sphinx
from sphinx.errors import ExtensionError, PycodeError
from sphinx.errors import ExtensionError
from sphinx.testing.util import strip_escseq
from sphinx.util import (SkipProgressMessage, display_chunk, encode_uri, ensuredir,
import_object, logging, parselinenos, progress_message,

View File

@ -19,7 +19,7 @@ import _testcapi
import pytest
from sphinx.util import inspect
from sphinx.util.inspect import is_builtin_class_method, stringify_signature
from sphinx.util.inspect import stringify_signature
def test_signature():

View File

@ -10,8 +10,7 @@
import sys
from numbers import Integral
from typing import (Any, Callable, Dict, Generator, Generic, List, Optional, Tuple, TypeVar,
Union)
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, TypeVar, Union
import pytest
@ -25,8 +24,10 @@ class MyClass1:
class MyClass2(MyClass1):
__qualname__ = '<MyClass2>'
T = TypeVar('T')
class MyList(List[T]):
pass
@ -132,8 +133,8 @@ def test_stringify_type_hints_containers():
@pytest.mark.skipif(sys.version_info < (3, 9), reason='python 3.9+ is required.')
def test_stringify_Annotated():
from typing import Annotated
assert stringify(Annotated[str, "foo", "bar"]) == "str"
from typing import Annotated # type: ignore
assert stringify(Annotated[str, "foo", "bar"]) == "str" # NOQA
def test_stringify_type_hints_string():

View File

@ -77,7 +77,7 @@ def f14() -> Any:
pass
def f15(x: "Unknown", y: "int") -> Any:
def f15(x: "Unknown", y: "int") -> Any: # type: ignore # NOQA
pass