From f2094ad8e00b8b359a5a325bdcec363d09b0c0e0 Mon Sep 17 00:00:00 2001 From: danieleades <33452915+danieleades@users.noreply.github.com> Date: Tue, 30 Nov 2021 07:50:16 +0000 Subject: [PATCH] lint using flake8-simplify (#417) * migrate to pre-commit for linting+formatting * use flake8-simplify for linting --- .flake8 | 1 + .pre-commit-config.yaml | 1 + performance/performance_test.py | 12 +++++----- sphinxcontrib/needs/api/configuration.py | 4 ++-- sphinxcontrib/needs/api/need.py | 23 +++++++++--------- sphinxcontrib/needs/config.py | 6 ++--- sphinxcontrib/needs/directives/need.py | 11 ++++----- sphinxcontrib/needs/directives/needextract.py | 2 +- sphinxcontrib/needs/directives/needflow.py | 8 +++---- sphinxcontrib/needs/directives/needgantt.py | 2 +- sphinxcontrib/needs/directives/needimport.py | 4 ++-- sphinxcontrib/needs/directives/needlist.py | 6 ++--- sphinxcontrib/needs/directives/needtable.py | 23 +++++++++--------- sphinxcontrib/needs/external_needs.py | 2 +- sphinxcontrib/needs/filter_common.py | 11 +++++---- sphinxcontrib/needs/functions/functions.py | 6 ++--- sphinxcontrib/needs/layout.py | 5 ++-- sphinxcontrib/needs/needs.py | 5 ++-- sphinxcontrib/needs/needsfile.py | 4 ++-- sphinxcontrib/needs/roles/need_incoming.py | 2 +- sphinxcontrib/needs/roles/need_outgoing.py | 4 ++-- sphinxcontrib/needs/roles/need_part.py | 4 ++-- sphinxcontrib/needs/services/github.py | 24 +++++++------------ sphinxcontrib/needs/services/manager.py | 2 +- sphinxcontrib/needs/utils.py | 9 ++++--- sphinxcontrib/needs/warnings.py | 5 ++-- tests/test_export_id.py | 8 +++---- tests/test_import.py | 2 +- tests/test_needtable.py | 2 +- tests/test_official_doc.py | 6 +---- tests/test_title_optional.py | 2 +- tests/util.py | 2 +- 32 files changed, 95 insertions(+), 113 deletions(-) diff --git a/.flake8 b/.flake8 index f005fbdcd..ca42ab234 100644 --- a/.flake8 +++ b/.flake8 @@ -2,3 +2,4 @@ max-line-length = 120 per-file-ignores = tests/data/service_github.py: E501 +extend-ignore = SIM106 \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6402a5e41..de2c49584 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,6 +11,7 @@ repos: additional_dependencies: - flake8-bugbear - pep8-naming + - flake8-simplify - repo: https://github.com/pycqa/isort rev: 5.9.3 diff --git a/performance/performance_test.py b/performance/performance_test.py index 9b36b05d8..e82a0806d 100644 --- a/performance/performance_test.py +++ b/performance/performance_test.py @@ -8,6 +8,8 @@ import tempfile import time import webbrowser +from contextlib import suppress +from pathlib import Path import click from jinja2 import Template @@ -34,7 +36,7 @@ def start( # Render conf.py source_tmp_path_conf = os.path.join(source_tmp_path, "conf.template") source_tmp_path_conf_final = os.path.join(source_tmp_path, "conf.py") - template = Template(open(source_tmp_path_conf).read()) + template = Template(Path(source_tmp_path_conf).read_text()) rendered = template.render( pages=pages, needs=needs, @@ -52,7 +54,7 @@ def start( # Render index files source_tmp_path_index = os.path.join(source_tmp_path, "index.template") source_tmp_path_index_final = os.path.join(source_tmp_path, "index.rst") - template = Template(open(source_tmp_path_index).read()) + template = Template(Path(source_tmp_path_index).read_text()) title = "Index" rendered = template.render( pages=pages, @@ -73,7 +75,7 @@ def start( for p in range(pages): source_tmp_path_page = os.path.join(source_tmp_path, "page.template") source_tmp_path_page_final = os.path.join(source_tmp_path, f"page_{p}.rst") - template = Template(open(source_tmp_path_page).read()) + template = Template(Path(source_tmp_path_page).read_text()) title = f"Page {p}" rendered = template.render( page=p, @@ -151,10 +153,8 @@ def start( result_time = end_time - start_time if browser: - try: + with suppress(Exception): webbrowser.open_new_tab(project_path) - except Exception: - pass print(f" Duration: {result_time:.2f} seconds") diff --git a/sphinxcontrib/needs/api/configuration.py b/sphinxcontrib/needs/api/configuration.py index 0dbb3b4df..8a8f52c99 100644 --- a/sphinxcontrib/needs/api/configuration.py +++ b/sphinxcontrib/needs/api/configuration.py @@ -84,7 +84,7 @@ def add_extra_option(app, name): extra_options = NEEDS_CONFIG.create_or_get("extra_options", dict) - if name in extra_options.keys(): + if name in extra_options: raise NeedsApiConfigWarning("Option {} already registered.".format(name)) NEEDS_CONFIG.add("extra_options", {name: directives.unchanged}, dict, append=True) @@ -142,7 +142,7 @@ def add_warning(app, name, function=None, filter_string=None): warning_check = function or filter_string - if name in warnings_option.keys(): + if name in warnings_option: raise NeedsApiConfigException(f"Warning {name} already registered.") # warnings_option[name] = warning_check diff --git a/sphinxcontrib/needs/api/need.py b/sphinxcontrib/needs/api/need.py index e4ee7615b..71148e5b1 100644 --- a/sphinxcontrib/needs/api/need.py +++ b/sphinxcontrib/needs/api/need.py @@ -178,11 +178,10 @@ def run(): # Handle status # Check if status is in needs_statuses. If not raise an error. - if env.app.config.needs_statuses: - if status not in [stat["name"] for stat in env.app.config.needs_statuses]: - raise NeedsStatusNotAllowed( - "Status {0} of need id {1} is not allowed " "by config value 'needs_statuses'.".format(status, need_id) - ) + if env.app.config.needs_statuses and status not in [stat["name"] for stat in env.app.config.needs_statuses]: + raise NeedsStatusNotAllowed( + "Status {0} of need id {1} is not allowed " "by config value 'needs_statuses'.".format(status, need_id) + ) if tags is None: tags = [] @@ -220,7 +219,7 @@ def run(): if not hasattr(env, "needs_all_needs"): env.needs_all_needs = {} - if need_id in env.needs_all_needs.keys(): + if need_id in env.needs_all_needs: if id: raise NeedsDuplicatedId( "A need with ID {} already exists! " @@ -300,11 +299,11 @@ def run(): for link_type in env.config.needs_extra_links: # Check, if specific link-type got some arguments during method call - if link_type["option"] not in list(kwargs.keys()) and link_type["option"] not in needs_global_options.keys(): + if link_type["option"] not in kwargs and link_type["option"] not in needs_global_options: # if not we set no links, but entry in needS_info must be there links = [] - elif link_type["option"] in needs_global_options.keys() and ( - link_type["option"] not in list(kwargs.keys()) or len(str(kwargs[link_type["option"]])) == 0 + elif link_type["option"] in needs_global_options and ( + link_type["option"] not in kwargs or len(str(kwargs[link_type["option"]])) == 0 ): # If it is in global option, value got already set during prior handling of them links_string = needs_info[link_type["option"]] @@ -317,7 +316,7 @@ def run(): needs_info[link_type["option"]] = links needs_info["{}_back".format(link_type["option"])] = [] - if "copy" not in link_type.keys(): + if "copy" not in link_type: link_type["copy"] = False if link_type["copy"] and link_type["option"] != "links": @@ -401,7 +400,7 @@ def del_need(app, id): :param app: Sphinx application object. :param id: Sphinx need id. """ - if id in app.env.needs_all_needs.keys(): + if id in app.env.needs_all_needs: del app.env.needs_all_needs[id] else: logger.warning("Given need id {} not exists!".format(id)) @@ -609,7 +608,7 @@ def _merge_global_options(app, needs_info, global_options): for key, value in global_options.items(): # If key already exists in needs_info, this global_option got overwritten manually in current need - if key in needs_info.keys() and needs_info[key]: + if key in needs_info and needs_info[key]: continue if isinstance(value, tuple): diff --git a/sphinxcontrib/needs/config.py b/sphinxcontrib/needs/config.py index 28a61b87a..f872a08e1 100644 --- a/sphinxcontrib/needs/config.py +++ b/sphinxcontrib/needs/config.py @@ -12,7 +12,7 @@ def __init__(self): self.configs = {} def add(self, name, value, option_type=str, append=False, overwrite=False): - if name not in self.configs.keys(): + if name not in self.configs: self.configs[name] = option_type() elif not isinstance(self.configs[name], option_type): raise Exception( @@ -28,12 +28,12 @@ def add(self, name, value, option_type=str, append=False, overwrite=False): self.configs[name] += value def create(self, name, option_type=str, overwrite=False): - if name in self.configs.keys() and not overwrite: + if name in self.configs and not overwrite: raise Exception(f"option {name} exists.") self.configs[name] = option_type() def create_or_get(self, name, option_type=str): - if name not in self.configs.keys(): + if name not in self.configs: self.configs[name] = option_type() return self.configs.get(name, None) diff --git a/sphinxcontrib/needs/directives/need.py b/sphinxcontrib/needs/directives/need.py index 183afdb0b..3d48d9466 100644 --- a/sphinxcontrib/needs/directives/need.py +++ b/sphinxcontrib/needs/directives/need.py @@ -62,7 +62,7 @@ def run(self): else: raise Exception("collapse attribute must be true or false") - hide = True if "hide" in self.options.keys() else False + hide = "hide" in self.options id = self.options.get("id", None) content = "\n".join(self.content) @@ -363,11 +363,10 @@ def create_back_links(env, option): needs[link_main][option_back].append(key) # Handling of links to need_parts inside a need - if link_part: - if link_part in needs[link_main]["parts"]: - if option_back not in needs[link_main]["parts"][link_part].keys(): - needs[link_main]["parts"][link_part][option_back] = [] - needs[link_main]["parts"][link_part][option_back].append(key) + if link_part and link_part in needs[link_main]["parts"]: + if option_back not in needs[link_main]["parts"][link_part].keys(): + needs[link_main]["parts"][link_part][option_back] = [] + needs[link_main]["parts"][link_part][option_back].append(key) env.needs_workflow["backlink_creation_{}".format(option)] = True diff --git a/sphinxcontrib/needs/directives/needextract.py b/sphinxcontrib/needs/directives/needextract.py index 3232d5159..f31dd3f6e 100644 --- a/sphinxcontrib/needs/directives/needextract.py +++ b/sphinxcontrib/needs/directives/needextract.py @@ -52,7 +52,7 @@ def run(self): "export_id": self.options.get("export_id", ""), "layout": self.options.get("layout", None), "style": self.options.get("style", None), - "show_filters": True if self.options.get("show_filters", False) is None else False, + "show_filters": self.options.get("show_filters", False) is None, } env.need_all_needextracts[targetid].update(self.collect_filter_attributes()) diff --git a/sphinxcontrib/needs/directives/needflow.py b/sphinxcontrib/needs/directives/needflow.py index c8a0bdfcc..9e8380ee4 100644 --- a/sphinxcontrib/needs/directives/needflow.py +++ b/sphinxcontrib/needs/directives/needflow.py @@ -281,7 +281,7 @@ def process_needflow(app, doctree, fromdocname): else: comment = "" - if "style_part" in link_type.keys() and link_type["style_part"]: + if "style_part" in link_type and link_type["style_part"]: link_style = "[{style}]".format(style=link_type["style_part"]) else: link_style = "[dotted]" @@ -292,7 +292,7 @@ def process_needflow(app, doctree, fromdocname): else: comment = "" - if "style" in link_type.keys() and link_type["style"]: + if "style" in link_type and link_type["style"]: link_style = "[{style}]".format(style=link_type["style"]) else: link_style = "" @@ -303,12 +303,12 @@ def process_needflow(app, doctree, fromdocname): ]: continue - if "style_start" in link_type.keys() and link_type["style_start"]: + if "style_start" in link_type and link_type["style_start"]: style_start = link_type["style_start"] else: style_start = "-" - if "style_end" in link_type.keys() and link_type["style_end"]: + if "style_end" in link_type and link_type["style_end"]: style_end = link_type["style_end"] else: style_end = "->" diff --git a/sphinxcontrib/needs/directives/needgantt.py b/sphinxcontrib/needs/directives/needgantt.py index bd96cc67a..039ef8e78 100644 --- a/sphinxcontrib/needs/directives/needgantt.py +++ b/sphinxcontrib/needs/directives/needgantt.py @@ -89,7 +89,7 @@ def run(self): else: timeline = None # Timeline/scale not set later - no_color = "no_color" in self.options.keys() + no_color = "no_color" in self.options duration_option = self.options.get("duration_option", env.app.config.needs_duration_option) completion_option = self.options.get("completion_option", env.app.config.needs_completion_option) diff --git a/sphinxcontrib/needs/directives/needimport.py b/sphinxcontrib/needs/directives/needimport.py index 344dc0c9a..55533e54d 100644 --- a/sphinxcontrib/needs/directives/needimport.py +++ b/sphinxcontrib/needs/directives/needimport.py @@ -130,7 +130,7 @@ def run(self): for id in needs_ids: # Manipulate links in all link types for extra_link in env.config.needs_extra_links: - if extra_link["option"] in need.keys() and id in need[extra_link["option"]]: + if extra_link["option"] in need and id in need[extra_link["option"]]: for n, link in enumerate(need[extra_link["option"]]): if id == link: need[extra_link["option"]][n] = "".join([id_prefix, id]) @@ -151,7 +151,7 @@ def run(self): need["layout"] = self.options.get("layout", getattr(need, "layout", None)) need["style"] = self.options.get("style", getattr(need, "style", None)) need["style"] = self.options.get("style", getattr(need, "style", None)) - if "hide" in self.options.keys(): + if "hide" in self.options: need["hide"] = True else: need["hide"] = getattr(need, "hide", None) diff --git a/sphinxcontrib/needs/directives/needlist.py b/sphinxcontrib/needs/directives/needlist.py index 8ddb15dfd..b4932922a 100644 --- a/sphinxcontrib/needs/directives/needlist.py +++ b/sphinxcontrib/needs/directives/needlist.py @@ -48,9 +48,9 @@ def run(self): "docname": env.docname, "lineno": self.lineno, "target_node": targetnode, - "show_tags": True if self.options.get("show_tags", False) is None else False, - "show_status": True if self.options.get("show_status", False) is None else False, - "show_filters": True if self.options.get("show_filters", False) is None else False, + "show_tags": self.options.get("show_tags", False) is None, + "show_status": self.options.get("show_status", False) is None, + "show_filters": self.options.get("show_filters", False) is None, "export_id": self.options.get("export_id", ""), "env": env, } diff --git a/sphinxcontrib/needs/directives/needtable.py b/sphinxcontrib/needs/directives/needtable.py index 3aaf2cb87..9ccb2c71b 100644 --- a/sphinxcontrib/needs/directives/needtable.py +++ b/sphinxcontrib/needs/directives/needtable.py @@ -81,8 +81,8 @@ def run(self): "sort": sort, # As the following options are flags, the content is None, if set. # If not set, the options.get() method returns False - "show_filters": True if self.options.get("show_filters", False) is None else False, - "show_parts": True if self.options.get("show_parts", False) is None else False, + "show_filters": self.options.get("show_filters", False) is None, + "show_parts": self.options.get("show_parts", False) is None, "env": env, } env.need_all_needtables[targetid].update(self.collect_filter_attributes()) @@ -223,13 +223,9 @@ def sort(need): ) elif option == "TITLE": row += row_col_maker(app, fromdocname, env.needs_all_needs, temp_need, "title", prefix=prefix) - elif option in link_type_list.keys(): + elif option in link_type_list: link_type = link_type_list[option] - if ( - option == "INCOMING" - or option == link_type["option"].upper() + "_BACK" - or option == link_type["incoming"].upper() - ): + if option in ["INCOMING", link_type["option"].upper() + "_BACK", link_type["incoming"].upper()]: row += row_col_maker( app, fromdocname, @@ -279,10 +275,13 @@ def sort(need): "content", prefix=app.config.needs_part_prefix, ) - elif option in link_type_list.keys() and ( - option == "INCOMING" - or option == link_type_list[option]["option"].upper() + "_BACK" - or option == link_type_list[option]["incoming"].upper() + elif option in link_type_list and ( + option + in [ + "INCOMING", + link_type_list[option]["option"].upper() + "_BACK", + link_type_list[option]["incoming"].upper(), + ] ): row += row_col_maker( app, diff --git a/sphinxcontrib/needs/external_needs.py b/sphinxcontrib/needs/external_needs.py index 6d40f4edb..259a5c21c 100644 --- a/sphinxcontrib/needs/external_needs.py +++ b/sphinxcontrib/needs/external_needs.py @@ -90,7 +90,7 @@ def load_external_needs(app, env, _docname): # check if external needs already exist ext_need_id = need_params["id"] - if ext_need_id in env.needs_all_needs.keys(): + if ext_need_id in env.needs_all_needs: # check need_params for more detail if ( env.needs_all_needs[ext_need_id]["is_external"] diff --git a/sphinxcontrib/needs/filter_common.py b/sphinxcontrib/needs/filter_common.py index 33d26db20..ae51c827b 100644 --- a/sphinxcontrib/needs/filter_common.py +++ b/sphinxcontrib/needs/filter_common.py @@ -121,11 +121,12 @@ def process_filters(app, all_needs, current_needlist, include_external=True): if bool(current_needlist["status"] or current_needlist["tags"] or current_needlist["types"]): for need_info in all_needs_incl_parts: status_filter_passed = False - if not current_needlist["status"]: - # Filtering for status was not requested - status_filter_passed = True - elif need_info["status"] and need_info["status"] in current_needlist["status"]: - # Match was found + if ( + not current_needlist["status"] + or need_info["status"] + and need_info["status"] in current_needlist["status"] + ): + # Filtering for status was not requested or match was found status_filter_passed = True tags_filter_passed = False diff --git a/sphinxcontrib/needs/functions/functions.py b/sphinxcontrib/needs/functions/functions.py index 107eb36a3..1196715e0 100644 --- a/sphinxcontrib/needs/functions/functions.py +++ b/sphinxcontrib/needs/functions/functions.py @@ -42,7 +42,7 @@ def register_func(need_function, name=None): else: func_name = name - if func_name in NEEDS_FUNCTIONS.keys(): + if func_name in NEEDS_FUNCTIONS: # We can not throw an exception here, as using sphinx-needs in different sphinx-projects with the # same python interpreter session does not clean NEEDS_FUNCTIONS. # This is mostly the case during tet runs. @@ -303,9 +303,7 @@ def _analyze_func_string(func_string, need): for arg in func_call.args: if isinstance(arg, ast.Num): func_args.append(arg.n) - elif isinstance(arg, ast.Str): - func_args.append(arg.s) - elif isinstance(arg, ast.BoolOp): + elif isinstance(arg, (ast.Str, ast.BoolOp)): func_args.append(arg.s) elif isinstance(arg, ast.List): arg_list = [] diff --git a/sphinxcontrib/needs/layout.py b/sphinxcontrib/needs/layout.py index d9ebf654c..53127ea30 100644 --- a/sphinxcontrib/needs/layout.py +++ b/sphinxcontrib/needs/layout.py @@ -5,6 +5,7 @@ """ import os import re +from contextlib import suppress from urllib.parse import urlparse import requests @@ -749,10 +750,8 @@ def image(self, url, height=None, width=None, align=None, no_link=False, prefix= # Download only, if file not downloaded yet if not os.path.exists(file_path): - try: + with suppress(FileExistsError): os.mkdir(path) - except FileExistsError: - pass response = requests.get(url) if response.status_code == 200: with open(file_path, "wb") as f: diff --git a/sphinxcontrib/needs/needs.py b/sphinxcontrib/needs/needs.py index f8643b88a..256792877 100644 --- a/sphinxcontrib/needs/needs.py +++ b/sphinxcontrib/needs/needs.py @@ -455,12 +455,11 @@ def prepare_env(app, env, _docname): # Register user defined services for name, service in app.config.needs_services.items(): - if name not in app.needs_services.services.keys(): + if name not in app.needs_services.services and "class" in service and "class_init" in service: # We found a not yet registered service # But only register, if service-config contains class and class_init. # Otherwise the service may get registered later by an external sphinx-needs extension - if "class" in service and "class_init" in service: - app.needs_services.register(name, service["class"], **service["class_init"]) + app.needs_services.register(name, service["class"], **service["class_init"]) needs_functions = app.config.needs_functions diff --git a/sphinxcontrib/needs/needsfile.py b/sphinxcontrib/needs/needsfile.py index d304840d0..530d9a218 100644 --- a/sphinxcontrib/needs/needsfile.py +++ b/sphinxcontrib/needs/needsfile.py @@ -90,7 +90,7 @@ def add_filter(self, version, need_filter): self.needs_list["versions"][version]["filters_amount"] = len(self.needs_list["versions"][version]["filters"]) def wipe_version(self, version): - if version in self.needs_list["versions"].keys(): + if version in self.needs_list["versions"]: del self.needs_list["versions"][version] def write_json(self, needs_file="needs.json"): @@ -159,7 +159,7 @@ def check_needs_file(path): # In future there may be additional types of validations. # So lets already use a dict for all errors errors = {"schema": schema_errors} - errors["has_errors"] = True if any([bool(errors) for errors in errors.values()]) else False + errors["has_errors"] = any([bool(errors) for errors in errors.values()]) return errors diff --git a/sphinxcontrib/needs/roles/need_incoming.py b/sphinxcontrib/needs/roles/need_incoming.py index c63c185c1..ba19c5ad6 100644 --- a/sphinxcontrib/needs/roles/need_incoming.py +++ b/sphinxcontrib/needs/roles/need_incoming.py @@ -19,7 +19,7 @@ def process_need_incoming(app, doctree, fromdocname): ref_need = env.needs_all_needs[node_need_backref["reftarget"]] # Lets check if NeedIncoming shall follow a specific link type - if "link_type" in node_need_backref.attributes.keys(): + if "link_type" in node_need_backref.attributes: links_back = ref_need[node_need_backref.attributes["link_type"]] # if not, follow back to default links else: diff --git a/sphinxcontrib/needs/roles/need_outgoing.py b/sphinxcontrib/needs/roles/need_outgoing.py index fb060d03f..bd91afab7 100644 --- a/sphinxcontrib/needs/roles/need_outgoing.py +++ b/sphinxcontrib/needs/roles/need_outgoing.py @@ -23,7 +23,7 @@ def process_need_outgoing(app, doctree, fromdocname): ref_need = env.needs_all_needs[node_need_ref["reftarget"]] # Lets check if NeedIncoming shall follow a specific link type - if "link_type" in node_need_ref.attributes.keys(): + if "link_type" in node_need_ref.attributes: links = ref_need[node_need_ref.attributes["link_type"]] link_type = node_need_ref.attributes["link_type"] # if not, follow back to default links @@ -45,7 +45,7 @@ def process_need_outgoing(app, doctree, fromdocname): ): try: target_need = env.needs_all_needs[link] - if link_part and link_part in target_need["parts"].keys(): + if link_part and link_part in target_need["parts"]: part_content = target_need["parts"][link_part]["content"] target_title = part_content if len(part_content) < 30 else part_content[:27] + "..." target_id = ".".join([link, link_part]) diff --git a/sphinxcontrib/needs/roles/need_part.py b/sphinxcontrib/needs/roles/need_part.py index 836db45c0..a4bd2c166 100644 --- a/sphinxcontrib/needs/roles/need_part.py +++ b/sphinxcontrib/needs/roles/need_part.py @@ -38,10 +38,10 @@ def update_need_with_parts(env, need, part_nodes): part_content = content inline_id = hashlib.sha1(part_content.encode("UTF-8")).hexdigest().upper()[:3] - if "parts" not in need.keys(): + if "parts" not in need: need["parts"] = {} - if inline_id in need["parts"].keys(): + if inline_id in need["parts"]: log.warning( "part_need id {} in need {} is already taken. need_part may get overridden.".format( inline_id, need["id"] diff --git a/sphinxcontrib/needs/services/github.py b/sphinxcontrib/needs/services/github.py index 27ba637d7..52bcc60ce 100644 --- a/sphinxcontrib/needs/services/github.py +++ b/sphinxcontrib/needs/services/github.py @@ -1,6 +1,7 @@ import os import textwrap import time +from contextlib import suppress from urllib.parse import urlparse import requests @@ -48,20 +49,13 @@ def __init__(self, app, name, config, **kwargs): "commit": {"url": "search/commits", "query": "", "need_type": "commit"}, } - try: + with suppress(NeedsApiConfigException): + # Issue already exists, so we are fine add_need_type(self.app, "issue", "Issue", "IS_", "#cccccc", "card") - except NeedsApiConfigException: - pass # Issue already exists, so we are fine - - try: + # PR already exists, so we are fine add_need_type(self.app, "pr", "PullRequest", "PR_", "#aaaaaa", "card") - except NeedsApiConfigException: - pass # PR already exists, so we are fine - - try: + # Commit already exists, so we are fine add_need_type(self.app, "commit", "Commit", "C_", "#888888", "card") - except NeedsApiConfigException: - pass # Commit already exists, so we are fine if "gh_type" in kwargs: self.gh_type = kwargs["gh_type"] @@ -163,8 +157,8 @@ def request(self, options=None): specific = True response = self._send(query, options, specific=specific) - if "items" not in response.keys(): - if "errors" in response.keys(): + if "items" not in response: + if "errors" in response: raise NeedGithubServiceException( "GitHub service query error: {}\n" "Used query: {}".format(response["errors"][0]["message"], query) ) @@ -276,10 +270,8 @@ def _get_avatar(self, avatar_url): if self.download_avatars: # Download only, if file not downloaded yet if not os.path.exists(avatar_file_path): - try: + with suppress(FileExistsError): os.mkdir(path) - except FileExistsError: - pass if self.username and self.token: auth = (self.username, self.token) else: diff --git a/sphinxcontrib/needs/services/manager.py b/sphinxcontrib/needs/services/manager.py index 3a2276899..25809c3ef 100644 --- a/sphinxcontrib/needs/services/manager.py +++ b/sphinxcontrib/needs/services/manager.py @@ -36,7 +36,7 @@ def register(self, name, clazz, **kwargs): self.services[name] = clazz(self.app, name, config, **kwargs) def get(self, name): - if name in self.services.keys(): + if name in self.services: return self.services[name] else: raise NeedsServiceException( diff --git a/sphinxcontrib/needs/utils.py b/sphinxcontrib/needs/utils.py index e7753045f..2ab5b4722 100644 --- a/sphinxcontrib/needs/utils.py +++ b/sphinxcontrib/needs/utils.py @@ -102,10 +102,9 @@ def row_col_maker( link_list.append(link_type["option"]) link_list.append(link_type["option"] + "_back") - if need_key in link_list: - if "." in datum: - link_id = datum.split(".")[0] - link_part = datum.split(".")[1] + if need_key in link_list and "." in datum: + link_id = datum.split(".")[0] + link_part = datum.split(".")[1] datum_text = prefix + str(datum) text_col = nodes.Text(datum_text, datum_text) @@ -178,7 +177,7 @@ def import_prefix_link_edit(needs: Dict[str, Any], id_prefix: str, needs_extra_l for id in needs_ids: # Manipulate links in all link types for extra_link in needs_extra_links: - if extra_link["option"] in need.keys() and id in need[extra_link["option"]]: + if extra_link["option"] in need and id in need[extra_link["option"]]: for n, link in enumerate(need[extra_link["option"]]): if id == link: need[extra_link["option"]][n] = f"{id_prefix}{id}" diff --git a/sphinxcontrib/needs/warnings.py b/sphinxcontrib/needs/warnings.py index c2d916ca9..a6b5533c3 100644 --- a/sphinxcontrib/needs/warnings.py +++ b/sphinxcontrib/needs/warnings.py @@ -78,9 +78,8 @@ def process_warnings(app, exception): # see deatils in https://github.com/sphinx-doc/sphinx/blob/81a4fd973d4cfcb25d01a7b0be62cdb28f82406d/sphinx/application.py#L345 # noqa # To be clear, app.keep_going = -W and --keep-going, and will overrite -W after # see details in https://github.com/sphinx-doc/sphinx/blob/4.x/sphinx/application.py#L182 - if app.statuscode == 0: - if app.keep_going or app.warningiserror: - app.statuscode = 1 + if app.statuscode == 0 and (app.keep_going or app.warningiserror): + app.statuscode = 1 # get the text for used filter, either from filter string or function name if callable(warning_filter): diff --git a/tests/test_export_id.py b/tests/test_export_id.py index db32d0a57..f7198f953 100644 --- a/tests/test_export_id.py +++ b/tests/test_export_id.py @@ -13,10 +13,10 @@ def test_export_id(app, status, warning): content_obj = json.loads(content) assert content_obj is not None - assert "created" in content_obj.keys() - assert "FLOW_1" in content_obj["versions"]["1.0"]["filters"].keys() - assert "TABLE_1" in content_obj["versions"]["1.0"]["filters"].keys() - assert "LIST_1" in content_obj["versions"]["1.0"]["filters"].keys() + assert "created" in content_obj + assert "FLOW_1" in content_obj["versions"]["1.0"]["filters"] + assert "TABLE_1" in content_obj["versions"]["1.0"]["filters"] + assert "LIST_1" in content_obj["versions"]["1.0"]["filters"] @with_app(buildername="html", srcdir="doc_test/doc_export_id") diff --git a/tests/test_import.py b/tests/test_import.py index 8eb2b3cd8..4be8323d5 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -59,7 +59,7 @@ def test_import_builder(app, status, warning): app.build() needs_text = Path(app.outdir, "needs.json").read_text() needs = json.loads(needs_text) - assert "created" in needs.keys() + assert "created" in needs need = needs["versions"]["1.0"]["needs"]["REQ_1"] check_keys = [ diff --git a/tests/test_needtable.py b/tests/test_needtable.py index ab89a2b5c..3a9afa055 100644 --- a/tests/test_needtable.py +++ b/tests/test_needtable.py @@ -35,7 +35,7 @@ def test_doc_build_html(app, status, warning): assert len(tree.xpath("//table/caption")) == 1 # check needtable has correct caption - assert "Test table caption" == tree.xpath("//table/caption/span")[0].text + assert tree.xpath("//table/caption/span")[0].text == "Test table caption" @with_app(buildername="html", srcdir="doc_test/doc_needtable") diff --git a/tests/test_official_doc.py b/tests/test_official_doc.py index a7f47675d..7c0536fec 100644 --- a/tests/test_official_doc.py +++ b/tests/test_official_doc.py @@ -26,11 +26,7 @@ def random_data_callback(request): if re.match(r"/search/issues", request.path_url): data = GITHUB_ISSUE_SEARCH_ANSWER data["items"][0]["number"] = randrange(10000) - elif re.match(r"/.+/issue/.+", request.path_url): - data = GITHUB_SPECIFIC_ISSUE_ANSWER - data["number"] = randrange(10000) - elif re.match(r"/.+/pulls/.+", request.path_url): - # data = GITHUB_SEARCH_COMMIT_ANSWER + elif re.match(r"/.+/issue/.+", request.path_url) or re.match(r"/.+/pulls/.+", request.path_url): data = GITHUB_SPECIFIC_ISSUE_ANSWER data["number"] = randrange(10000) elif re.match(r"/search/commits", request.path_url): diff --git a/tests/test_title_optional.py b/tests/test_title_optional.py index 29b494ed7..a0ae128d6 100644 --- a/tests/test_title_optional.py +++ b/tests/test_title_optional.py @@ -10,7 +10,7 @@ NS = {"html": "http://www.w3.org/1999/xhtml"} -class HtmlNeed(object): +class HtmlNeed: """Helper class to parse HTML needs""" def __init__(self, need): diff --git a/tests/util.py b/tests/util.py index d9e944f9a..7c04aa80c 100644 --- a/tests/util.py +++ b/tests/util.py @@ -4,7 +4,7 @@ NS = {"html": "http://www.w3.org/1999/xhtml"} -class HtmlNeed(object): +class HtmlNeed: """Helper class to parse HTML needs""" def __init__(self, need):