From 76c5f33059fdaa0921d58df58c148f17bcd5bb6f Mon Sep 17 00:00:00 2001 From: Irina Truong Date: Sun, 27 Apr 2025 21:28:45 -0700 Subject: [PATCH] Ruff format. --- .pre-commit-config.yaml | 4 +- README.rst | 1 + pgcli/auth.py | 8 +- pgcli/completion_refresher.py | 8 +- pgcli/key_bindings.py | 3 +- pgcli/packages/formatter/sqlformatter.py | 13 +-- pgcli/packages/parseutils/__init__.py | 4 +- pgcli/packages/parseutils/meta.py | 10 +-- pgcli/packages/parseutils/tables.py | 25 ++---- pgcli/packages/parseutils/utils.py | 4 +- pgcli/pgexecute.py | 31 ++------ pgcli/pgstyle.py | 4 +- pgcli/pgtoolbar.py | 16 +--- pgcli/pyev.py | 48 +++-------- pyproject.toml | 3 +- release.py | 8 +- tests/features/steps/basic_commands.py | 8 +- tests/features/steps/crud_table.py | 4 +- tests/features/steps/iocommands.py | 12 +-- tests/metadata.py | 76 ++++-------------- tests/parseutils/test_function_metadata.py | 12 +-- tests/parseutils/test_parseutils.py | 8 +- tests/test_application_name.py | 4 +- tests/test_auth.py | 8 +- tests/test_init_commands_simple.py | 12 +-- tests/test_naive_completion.py | 93 ++++++++-------------- tests/test_pgcompleter.py | 12 +-- tests/test_sqlcompletion.py | 88 +++++--------------- tests/test_ssh_tunnel.py | 26 ++---- tox.ini | 3 +- 30 files changed, 144 insertions(+), 412 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f44dd5c09..41cef209b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,5 +6,5 @@ repos: # Run the linter. - id: ruff args: [ --fix ] - # Run the formatter. TODO: uncomment when the rest of the code is ruff-formatted - # - id: ruff-format + # Run the formatter. + - id: ruff-format diff --git a/README.rst b/README.rst index 8b7ea0854..6dc4f9e8a 100644 --- a/README.rst +++ b/README.rst @@ -158,6 +158,7 @@ get this running in a development setup. https://github.com/dbcli/pgcli/blob/main/CONTRIBUTING.rst Please feel free to reach out to us if you need help. + * Amjith, pgcli author: amjith.r@gmail.com, Twitter: `@amjithr `_ * Irina, pgcli maintainer: i.chernyavska@gmail.com, Twitter: `@irinatruong `_ diff --git a/pgcli/auth.py b/pgcli/auth.py index 2f1e55265..513097a31 100644 --- a/pgcli/auth.py +++ b/pgcli/auth.py @@ -26,9 +26,7 @@ def keyring_initialize(keyring_enabled, *, logger): try: keyring = importlib.import_module("keyring") - except ( - ModuleNotFoundError - ) as e: # ImportError for Python 2, ModuleNotFoundError for Python 3 + except ModuleNotFoundError as e: # ImportError for Python 2, ModuleNotFoundError for Python 3 logger.warning("import keyring failed: %r.", e) @@ -40,9 +38,7 @@ def keyring_get_password(key): passwd = keyring.get_password("pgcli", key) or "" except Exception as e: click.secho( - keyring_error_message.format( - "Load your password from keyring returned:", str(e) - ), + keyring_error_message.format("Load your password from keyring returned:", str(e)), err=True, fg="red", ) diff --git a/pgcli/completion_refresher.py b/pgcli/completion_refresher.py index c887cb632..34771b8a2 100644 --- a/pgcli/completion_refresher.py +++ b/pgcli/completion_refresher.py @@ -40,18 +40,14 @@ def refresh(self, executor, special, callbacks, history=None, settings=None): ) self._completer_thread.daemon = True self._completer_thread.start() - return [ - (None, None, None, "Auto-completion refresh started in the background.") - ] + return [(None, None, None, "Auto-completion refresh started in the background.")] def is_refreshing(self): return self._completer_thread and self._completer_thread.is_alive() def _bg_refresh(self, pgexecute, special, callbacks, history=None, settings=None): settings = settings or {} - completer = PGCompleter( - smart_completion=True, pgspecial=special, settings=settings - ) + completer = PGCompleter(smart_completion=True, pgspecial=special, settings=settings) if settings.get("single_connection"): executor = pgexecute diff --git a/pgcli/key_bindings.py b/pgcli/key_bindings.py index 9c016f7ff..11855df74 100644 --- a/pgcli/key_bindings.py +++ b/pgcli/key_bindings.py @@ -107,8 +107,7 @@ def _(event): # history search, and one of several conditions are True @kb.add( "enter", - filter=~(completion_is_selected | is_searching) - & buffer_should_be_handled(pgcli), + filter=~(completion_is_selected | is_searching) & buffer_should_be_handled(pgcli), ) def _(event): _logger.debug("Detected enter key.") diff --git a/pgcli/packages/formatter/sqlformatter.py b/pgcli/packages/formatter/sqlformatter.py index 5224eff63..6c4973db7 100644 --- a/pgcli/packages/formatter/sqlformatter.py +++ b/pgcli/packages/formatter/sqlformatter.py @@ -52,16 +52,11 @@ def adapter(data, headers, table_format=None, **kwargs): yield 'UPDATE "{}" SET'.format(table_name) prefix = " " for i, v in enumerate(d[keys:], keys): - yield '{}"{}" = {}'.format( - prefix, headers[i], escape_for_sql_statement(v) - ) + yield '{}"{}" = {}'.format(prefix, headers[i], escape_for_sql_statement(v)) if prefix == " ": prefix = ", " f = '"{}" = {}' - where = ( - f.format(headers[i], escape_for_sql_statement(d[i])) - for i in range(keys) - ) + where = (f.format(headers[i], escape_for_sql_statement(d[i])) for i in range(keys)) yield "WHERE {};".format(" AND ".join(where)) @@ -69,6 +64,4 @@ def register_new_formatter(TabularOutputFormatter): global formatter formatter = TabularOutputFormatter for sql_format in supported_formats: - TabularOutputFormatter.register_new_formatter( - sql_format, adapter, preprocessors, {"table_format": sql_format} - ) + TabularOutputFormatter.register_new_formatter(sql_format, adapter, preprocessors, {"table_format": sql_format}) diff --git a/pgcli/packages/parseutils/__init__.py b/pgcli/packages/parseutils/__init__.py index 023e13be3..76a930ce0 100644 --- a/pgcli/packages/parseutils/__init__.py +++ b/pgcli/packages/parseutils/__init__.py @@ -29,9 +29,7 @@ def is_destructive(queries, keywords): for query in sqlparse.split(queries): if query: formatted_sql = sqlparse.format(query.lower(), strip_comments=True).strip() - if "unconditional_update" in keywords and query_is_unconditional_update( - formatted_sql - ): + if "unconditional_update" in keywords and query_is_unconditional_update(formatted_sql): return True if query_starts_with(formatted_sql, keywords): return True diff --git a/pgcli/packages/parseutils/meta.py b/pgcli/packages/parseutils/meta.py index 333cab559..df41cf4ee 100644 --- a/pgcli/packages/parseutils/meta.py +++ b/pgcli/packages/parseutils/meta.py @@ -1,8 +1,6 @@ from collections import namedtuple -_ColumnMetadata = namedtuple( - "ColumnMetadata", ["name", "datatype", "foreignkeys", "default", "has_default"] -) +_ColumnMetadata = namedtuple("ColumnMetadata", ["name", "datatype", "foreignkeys", "default", "has_default"]) def ColumnMetadata(name, datatype, foreignkeys=None, default=None, has_default=False): @@ -143,11 +141,7 @@ def arg(name, typ, num): num_args = len(args) num_defaults = len(self.arg_defaults) has_default = num + num_defaults >= num_args - default = ( - self.arg_defaults[num - num_args + num_defaults] - if has_default - else None - ) + default = self.arg_defaults[num - num_args + num_defaults] if has_default else None return ColumnMetadata(name, typ, [], default, has_default) return [arg(name, typ, num) for num, (name, typ) in enumerate(args)] diff --git a/pgcli/packages/parseutils/tables.py b/pgcli/packages/parseutils/tables.py index 909811590..bf67df09c 100644 --- a/pgcli/packages/parseutils/tables.py +++ b/pgcli/packages/parseutils/tables.py @@ -3,16 +3,9 @@ from sqlparse.sql import IdentifierList, Identifier, Function from sqlparse.tokens import Keyword, DML, Punctuation -TableReference = namedtuple( - "TableReference", ["schema", "name", "alias", "is_function"] -) +TableReference = namedtuple("TableReference", ["schema", "name", "alias", "is_function"]) TableReference.ref = property( - lambda self: self.alias - or ( - self.name - if self.name.islower() or self.name[0] == '"' - else '"' + self.name + '"' - ) + lambda self: self.alias or (self.name if self.name.islower() or self.name[0] == '"' else '"' + self.name + '"') ) @@ -53,11 +46,7 @@ def extract_from_part(parsed, stop_at_punctuation=True): # Also 'SELECT * FROM abc JOIN def' will trigger this elif # condition. So we need to ignore the keyword JOIN and its variants # INNER JOIN, FULL OUTER JOIN, etc. - elif ( - item.ttype is Keyword - and (not item.value.upper() == "FROM") - and (not item.value.upper().endswith("JOIN")) - ): + elif item.ttype is Keyword and (not item.value.upper() == "FROM") and (not item.value.upper().endswith("JOIN")): tbl_prefix_seen = False else: yield item @@ -116,15 +105,11 @@ def parse_identifier(item): try: schema_name = identifier.get_parent_name() real_name = identifier.get_real_name() - is_function = allow_functions and _identifier_is_function( - identifier - ) + is_function = allow_functions and _identifier_is_function(identifier) except AttributeError: continue if real_name: - yield TableReference( - schema_name, real_name, identifier.get_alias(), is_function - ) + yield TableReference(schema_name, real_name, identifier.get_alias(), is_function) elif isinstance(item, Identifier): schema_name, real_name, alias = parse_identifier(item) is_function = allow_functions and _identifier_is_function(item) diff --git a/pgcli/packages/parseutils/utils.py b/pgcli/packages/parseutils/utils.py index 034c96e92..6d577430a 100644 --- a/pgcli/packages/parseutils/utils.py +++ b/pgcli/packages/parseutils/utils.py @@ -79,9 +79,7 @@ def find_prev_keyword(sql, n_skip=0): logical_operators = ("AND", "OR", "NOT", "BETWEEN") for t in reversed(flattened): - if t.value == "(" or ( - t.is_keyword and (t.value.upper() not in logical_operators) - ): + if t.value == "(" or (t.is_keyword and (t.value.upper() not in logical_operators)): # Find the location of token t in the original parsed statement # We can't use parsed.token_index(t) because t may be a child token # inside a TokenList, in which case token_index throws an error diff --git a/pgcli/pgexecute.py b/pgcli/pgexecute.py index 4e7c637d3..b82157ce1 100644 --- a/pgcli/pgexecute.py +++ b/pgcli/pgexecute.py @@ -13,9 +13,7 @@ _logger = logging.getLogger(__name__) -ViewDef = namedtuple( - "ViewDef", "nspname relname relkind viewdef reloptions checkoption" -) +ViewDef = namedtuple("ViewDef", "nspname relname relkind viewdef reloptions checkoption") # we added this funcion to strip beginning comments @@ -51,9 +49,7 @@ def register_typecasters(connection): "json", "jsonb", ]: - connection.adapters.register_loader( - forced_text_type, psycopg.types.string.TextLoader - ) + connection.adapters.register_loader(forced_text_type, psycopg.types.string.TextLoader) # pg3: I don't know what is this @@ -219,9 +215,7 @@ def connect( new_params = {"dsn": new_params["dsn"], "password": new_params["password"]} if new_params["password"]: - new_params["dsn"] = make_conninfo( - new_params["dsn"], password=new_params.pop("password") - ) + new_params["dsn"] = make_conninfo(new_params["dsn"], password=new_params.pop("password")) conn_params.update({k: v for k, v in new_params.items() if v}) @@ -262,11 +256,7 @@ def connect( self.extra_args = kwargs if not self.host: - self.host = ( - "pgbouncer" - if self.is_virtual_database() - else self.get_socket_directory() - ) + self.host = "pgbouncer" if self.is_virtual_database() else self.get_socket_directory() self.pid = conn.info.backend_pid self.superuser = conn.info.parameter_status("is_superuser") in ("on", "1") @@ -306,10 +296,7 @@ def failed_transaction(self): def valid_transaction(self): status = self.conn.info.transaction_status - return ( - status == psycopg.pq.TransactionStatus.ACTIVE - or status == psycopg.pq.TransactionStatus.INTRANS - ) + return status == psycopg.pq.TransactionStatus.ACTIVE or status == psycopg.pq.TransactionStatus.INTRANS def run( self, @@ -649,9 +636,7 @@ def is_protocol_error(self): def get_socket_directory(self): with self.conn.cursor() as cur: - _logger.debug( - "Socket directory Query. sql: %r", self.socket_directory_query - ) + _logger.debug("Socket directory Query. sql: %r", self.socket_directory_query) cur.execute(self.socket_directory_query) result = cur.fetchone() return result[0] if result else "" @@ -889,8 +874,6 @@ def get_timezone(self) -> str: return cur.fetchone()[0] def set_timezone(self, timezone: str): - query = psycopg.sql.SQL("set time zone {}").format( - psycopg.sql.Identifier(timezone) - ) + query = psycopg.sql.SQL("set time zone {}").format(psycopg.sql.Identifier(timezone)) with self.conn.cursor() as cur: cur.execute(query) diff --git a/pgcli/pgstyle.py b/pgcli/pgstyle.py index 77874f40e..450f2c8b9 100644 --- a/pgcli/pgstyle.py +++ b/pgcli/pgstyle.py @@ -87,9 +87,7 @@ def style_factory(name, cli_style): prompt_styles.append((token, cli_style[token])) override_style = Style([("bottom-toolbar", "noreverse")]) - return merge_styles( - [style_from_pygments_cls(style), override_style, Style(prompt_styles)] - ) + return merge_styles([style_from_pygments_cls(style), override_style, Style(prompt_styles)]) def style_factory_output(name, cli_style): diff --git a/pgcli/pgtoolbar.py b/pgcli/pgtoolbar.py index 4a12ff4e5..ae8bc67c9 100644 --- a/pgcli/pgtoolbar.py +++ b/pgcli/pgtoolbar.py @@ -37,14 +37,10 @@ def get_toolbar_tokens(): if pgcli.multiline_mode == "safe": result.append(("class:bottom-toolbar", " ([Esc] [Enter] to execute]) ")) else: - result.append( - ("class:bottom-toolbar", " (Semi-colon [;] will end the line) ") - ) + result.append(("class:bottom-toolbar", " (Semi-colon [;] will end the line) ")) if pgcli.vi_mode: - result.append( - ("class:bottom-toolbar", "[F4] Vi-mode (" + _get_vi_mode() + ") ") - ) + result.append(("class:bottom-toolbar", "[F4] Vi-mode (" + _get_vi_mode() + ") ")) else: result.append(("class:bottom-toolbar", "[F4] Emacs-mode ")) @@ -54,14 +50,10 @@ def get_toolbar_tokens(): result.append(("class:bottom-toolbar", "[F5] Explain: OFF ")) if pgcli.pgexecute.failed_transaction(): - result.append( - ("class:bottom-toolbar.transaction.failed", " Failed transaction") - ) + result.append(("class:bottom-toolbar.transaction.failed", " Failed transaction")) if pgcli.pgexecute.valid_transaction(): - result.append( - ("class:bottom-toolbar.transaction.valid", " Transaction") - ) + result.append(("class:bottom-toolbar.transaction.valid", " Transaction")) if pgcli.completion_refresher.is_refreshing(): result.append(("class:bottom-toolbar", " Refreshing completions...")) diff --git a/pgcli/pyev.py b/pgcli/pyev.py index 2886c9c88..322060fa6 100644 --- a/pgcli/pyev.py +++ b/pgcli/pyev.py @@ -99,17 +99,13 @@ def calculate_planner_estimate(self, plan): return plan if plan["Plan Rows"] != 0: - plan["Planner Row Estimate Factor"] = ( - plan["Actual Rows"] / plan["Plan Rows"] - ) + plan["Planner Row Estimate Factor"] = plan["Actual Rows"] / plan["Plan Rows"] if plan["Planner Row Estimate Factor"] < 10: plan["Planner Row Estimate Factor"] = 0 plan["Planner Row Estimate Direction"] = "Over" if plan["Actual Rows"] != 0: - plan["Planner Row Estimate Factor"] = ( - plan["Plan Rows"] / plan["Actual Rows"] - ) + plan["Planner Row Estimate Factor"] = plan["Plan Rows"] / plan["Actual Rows"] return plan # @@ -119,9 +115,7 @@ def calculate_actuals(self, plan): for child in plan.get("Plans", []): if child["Node Type"] != "CTEScan": - plan["Actual Duration"] = ( - plan["Actual Duration"] - child["Actual Total Time"] - ) + plan["Actual Duration"] = plan["Actual Duration"] - child["Actual Total Time"] plan["Actual Cost"] = plan["Actual Cost"] - child["Total Cost"] if plan["Actual Cost"] < 0: @@ -243,9 +237,7 @@ def output_fn(self, current_prefix, string): def create_lines(self, plan, prefix, depth, width, last_child): current_prefix = prefix - self.string_lines.append( - self.output_fn(current_prefix, self.prefix_format("│")) - ) + self.string_lines.append(self.output_fn(current_prefix, self.prefix_format("│"))) joint = "├" if last_child: @@ -277,9 +269,7 @@ def create_lines(self, plan, prefix, depth, width, last_child): DESCRIPTIONS.get(plan["Node Type"], "Not found : %s" % plan["Node Type"]), cols, ): - self.string_lines.append( - self.output_fn(current_prefix, "%s" % self.muted_format(line)) - ) + self.string_lines.append(self.output_fn(current_prefix, "%s" % self.muted_format(line))) # if plan.get("Actual Duration"): self.string_lines.append( @@ -289,8 +279,7 @@ def create_lines(self, plan, prefix, depth, width, last_child): % ( "Duration:", self.duration_to_string(plan["Actual Duration"]), - (plan["Actual Duration"] / self.explain["Execution Time"]) - * 100, + (plan["Actual Duration"] / self.explain["Execution Time"]) * 100, ), ) ) @@ -361,9 +350,7 @@ def create_lines(self, plan, prefix, depth, width, last_child): % ( self.muted_format("filter"), plan["Filter"], - self.muted_format( - "[-%s rows]" % self.intcomma(plan["Rows Removed by Filter"]) - ), + self.muted_format("[-%s rows]" % self.intcomma(plan["Rows Removed by Filter"])), ), ) ) @@ -377,9 +364,7 @@ def create_lines(self, plan, prefix, depth, width, last_child): ) if plan.get("CTE Name"): - self.string_lines.append( - self.output_fn(current_prefix, "CTE %s" % plan["CTE Name"]) - ) + self.string_lines.append(self.output_fn(current_prefix, "CTE %s" % plan["CTE Name"])) if plan.get("Planner Row Estimate Factor") != 0: self.string_lines.append( @@ -398,29 +383,22 @@ def create_lines(self, plan, prefix, depth, width, last_child): current_prefix = prefix if len(plan.get("Output", [])) > 0: - for index, line in enumerate( - self.wrap_string(" + ".join(plan["Output"]), cols) - ): + for index, line in enumerate(self.wrap_string(" + ".join(plan["Output"]), cols)): self.string_lines.append( self.output_fn( current_prefix, - self.prefix_format(self.get_terminator(index, plan)) - + self.output_format(line), + self.prefix_format(self.get_terminator(index, plan)) + self.output_format(line), ) ) for index, nested_plan in enumerate(plan.get("Plans", [])): - self.create_lines( - nested_plan, prefix, depth + 1, width, index == len(plan["Plans"]) - 1 - ) + self.create_lines(nested_plan, prefix, depth + 1, width, index == len(plan["Plans"]) - 1) def generate_lines(self): self.string_lines = [ "○ Total Cost: %s" % self.intcomma(self.explain["Total Cost"]), - "○ Planning Time: %s" - % self.duration_to_string(self.explain["Planning Time"]), - "○ Execution Time: %s" - % self.duration_to_string(self.explain["Execution Time"]), + "○ Planning Time: %s" % self.duration_to_string(self.explain["Planning Time"]), + "○ Execution Time: %s" % self.duration_to_string(self.explain["Execution Time"]), self.prefix_format("┬"), ] self.create_lines( diff --git a/pyproject.toml b/pyproject.toml index f8458291a..a7facac8e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,7 @@ requires-python = ">=3.9" dependencies = [ "pgspecial>=2.0.0", "click >= 4.1,<8.1.8", - "Pygments>=2.0", # Pygments has to be Capitalcased. WTF? + "Pygments>=2.0", # Pygments has to be Capitalcased. # We still need to use pt-2 unless pt-3 released on Fedora32 # see: https://github.com/dbcli/pgcli/pull/1197 "prompt_toolkit>=2.0.6,<4.0.0", @@ -120,7 +120,6 @@ force-sort-within-sections = true known-first-party = [ 'pgcli', 'tests', - 'steps', ] [tool.ruff.format] diff --git a/release.py b/release.py index ad6a9574a..929393796 100644 --- a/release.py +++ b/release.py @@ -45,9 +45,7 @@ def run_step(*args): def version(version_file): - _version_re = re.compile( - r'__version__\s+=\s+(?P[\'"])(?P.*)(?P=quote)' - ) + _version_re = re.compile(r'__version__\s+=\s+(?P[\'"])(?P.*)(?P=quote)') with io.open(version_file, encoding="utf-8") as f: ver = _version_re.search(f.read()).group("version") @@ -108,9 +106,7 @@ def checklist(questions): action="store_true", dest="confirm_steps", default=False, - help=( - "Confirm every step. If the step is not " "confirmed, it will be skipped." - ), + help=("Confirm every step. If the step is not confirmed, it will be skipped."), ) parser.add_option( "-d", diff --git a/tests/features/steps/basic_commands.py b/tests/features/steps/basic_commands.py index 2aaf2b291..24c7e1e2f 100644 --- a/tests/features/steps/basic_commands.py +++ b/tests/features/steps/basic_commands.py @@ -62,9 +62,7 @@ def step_run_cli_using_arg(context, arg): arg = "service=mock_postgres --password" prompt_check = False currentdb = "postgres" - wrappers.run_cli( - context, run_args=[arg], prompt_check=prompt_check, currentdb=currentdb - ) + wrappers.run_cli(context, run_args=[arg], prompt_check=prompt_check, currentdb=currentdb) @when("we wait for prompt") @@ -188,9 +186,7 @@ def step_send_source_command(context): @when("we run query to check application_name") def step_check_application_name(context): - context.cli.sendline( - "SELECT 'found' FROM pg_stat_activity WHERE application_name = 'pgcli' HAVING COUNT(*) > 0;" - ) + context.cli.sendline("SELECT 'found' FROM pg_stat_activity WHERE application_name = 'pgcli' HAVING COUNT(*) > 0;") @then("we see found") diff --git a/tests/features/steps/crud_table.py b/tests/features/steps/crud_table.py index 27d543e74..114e3edf5 100644 --- a/tests/features/steps/crud_table.py +++ b/tests/features/steps/crud_table.py @@ -34,9 +34,7 @@ def step_update_table(context): """ Send insert into table. """ - context.cli.sendline( - f"""update a set x = '{UPDATED_DATA}' where x = '{INITIAL_DATA}';""" - ) + context.cli.sendline(f"""update a set x = '{UPDATED_DATA}' where x = '{INITIAL_DATA}';""") @when("we select from table") diff --git a/tests/features/steps/iocommands.py b/tests/features/steps/iocommands.py index a614490a7..615eecbb1 100644 --- a/tests/features/steps/iocommands.py +++ b/tests/features/steps/iocommands.py @@ -8,15 +8,11 @@ @when("we start external editor providing a file name") def step_edit_file(context): """Edit file with external editor.""" - context.editor_file_name = os.path.join( - context.package_root, "test_file_{0}.sql".format(context.conf["vi"]) - ) + context.editor_file_name = os.path.join(context.package_root, "test_file_{0}.sql".format(context.conf["vi"])) if os.path.exists(context.editor_file_name): os.remove(context.editor_file_name) context.cli.sendline(r"\e {}".format(os.path.basename(context.editor_file_name))) - wrappers.expect_exact( - context, 'Entering Ex mode. Type "visual" to go to Normal mode.', timeout=2 - ) + wrappers.expect_exact(context, 'Entering Ex mode. Type "visual" to go to Normal mode.', timeout=2) wrappers.expect_exact(context, ":", timeout=2) @@ -48,9 +44,7 @@ def step_edit_done_sql(context): @when("we tee output") def step_tee_ouptut(context): - context.tee_file_name = os.path.join( - context.package_root, "tee_file_{0}.sql".format(context.conf["vi"]) - ) + context.tee_file_name = os.path.join(context.package_root, "tee_file_{0}.sql".format(context.conf["vi"])) if os.path.exists(context.tee_file_name): os.remove(context.tee_file_name) context.cli.sendline(r"\o {}".format(os.path.basename(context.tee_file_name))) diff --git a/tests/metadata.py b/tests/metadata.py index 4ebcccd07..3ab88a719 100644 --- a/tests/metadata.py +++ b/tests/metadata.py @@ -23,16 +23,12 @@ def completion(display_meta, text, pos=0): def function(text, pos=0, display=None): - return Completion( - text, display=display or text, start_position=pos, display_meta="function" - ) + return Completion(text, display=display or text, start_position=pos, display_meta="function") def get_result(completer, text, position=None): position = len(text) if position is None else position - return completer.get_completions( - Document(text=text, cursor_position=position), Mock() - ) + return completer.get_completions(Document(text=text, cursor_position=position), Mock()) def result_set(completer, text, position=None): @@ -73,10 +69,7 @@ def keywords(self, pos=0): return [keyword(kw, pos) for kw in self.completer.keywords_tree.keys()] def specials(self, pos=0): - return [ - Completion(text=k, start_position=pos, display_meta=v.description) - for k, v in self.completer.pgspecial.commands.items() - ] + return [Completion(text=k, start_position=pos, display_meta=v.description) for k, v in self.completer.pgspecial.commands.items()] def columns(self, tbl, parent="public", typ="tables", pos=0): if typ == "functions": @@ -87,42 +80,23 @@ def columns(self, tbl, parent="public", typ="tables", pos=0): return [column(escape(col), pos) for col in cols] def datatypes(self, parent="public", pos=0): - return [ - datatype(escape(x), pos) - for x in self.metadata.get("datatypes", {}).get(parent, []) - ] + return [datatype(escape(x), pos) for x in self.metadata.get("datatypes", {}).get(parent, [])] def tables(self, parent="public", pos=0): - return [ - table(escape(x), pos) - for x in self.metadata.get("tables", {}).get(parent, []) - ] + return [table(escape(x), pos) for x in self.metadata.get("tables", {}).get(parent, [])] def views(self, parent="public", pos=0): - return [ - view(escape(x), pos) for x in self.metadata.get("views", {}).get(parent, []) - ] + return [view(escape(x), pos) for x in self.metadata.get("views", {}).get(parent, [])] def functions(self, parent="public", pos=0): return [ function( escape(x[0]) + "(" - + ", ".join( - arg_name + " := " - for (arg_name, arg_mode) in zip(x[1], x[3]) - if arg_mode in ("b", "i") - ) + + ", ".join(arg_name + " := " for (arg_name, arg_mode) in zip(x[1], x[3]) if arg_mode in ("b", "i")) + ")", pos, - escape(x[0]) - + "(" - + ", ".join( - arg_name - for (arg_name, arg_mode) in zip(x[1], x[3]) - if arg_mode in ("b", "i") - ) - + ")", + escape(x[0]) + "(" + ", ".join(arg_name for (arg_name, arg_mode) in zip(x[1], x[3]) if arg_mode in ("b", "i")) + ")", ) for x in self.metadata.get("functions", {}).get(parent, []) ] @@ -132,24 +106,14 @@ def schemas(self, pos=0): return [schema(escape(s), pos=pos) for s in schemas] def functions_and_keywords(self, parent="public", pos=0): - return ( - self.functions(parent, pos) - + self.builtin_functions(pos) - + self.keywords(pos) - ) + return self.functions(parent, pos) + self.builtin_functions(pos) + self.keywords(pos) # Note that the filtering parameters here only apply to the columns def columns_functions_and_keywords(self, tbl, parent="public", typ="tables", pos=0): - return self.functions_and_keywords(pos=pos) + self.columns( - tbl, parent, typ, pos - ) + return self.functions_and_keywords(pos=pos) + self.columns(tbl, parent, typ, pos) def from_clause_items(self, parent="public", pos=0): - return ( - self.functions(parent, pos) - + self.views(parent, pos) - + self.tables(parent, pos) - ) + return self.functions(parent, pos) + self.views(parent, pos) + self.tables(parent, pos) def schemas_and_from_clause_items(self, parent="public", pos=0): return self.from_clause_items(parent, pos) + self.schemas(pos) @@ -205,9 +169,7 @@ def get_completer(self, settings=None, casing=None): from pgcli.pgcompleter import PGCompleter from pgspecial import PGSpecial - comp = PGCompleter( - smart_completion=True, settings=settings, pgspecial=PGSpecial() - ) + comp = PGCompleter(smart_completion=True, settings=settings, pgspecial=PGSpecial()) schemata, tables, tbl_cols, views, view_cols = [], [], [], [], [] @@ -226,20 +188,12 @@ def get_completer(self, settings=None, casing=None): view_cols.extend([self._make_col(sch, tbl, col) for col in cols]) functions = [ - FunctionMetadata(sch, *func_meta, arg_defaults=None) - for sch, funcs in metadata["functions"].items() - for func_meta in funcs + FunctionMetadata(sch, *func_meta, arg_defaults=None) for sch, funcs in metadata["functions"].items() for func_meta in funcs ] - datatypes = [ - (sch, typ) - for sch, datatypes in metadata["datatypes"].items() - for typ in datatypes - ] + datatypes = [(sch, typ) for sch, datatypes in metadata["datatypes"].items() for typ in datatypes] - foreignkeys = [ - ForeignKey(*fk) for fks in metadata["foreignkeys"].values() for fk in fks - ] + foreignkeys = [ForeignKey(*fk) for fks in metadata["foreignkeys"].values() for fk in fks] comp.extend_schemata(schemata) comp.extend_relations(tables, kind="tables") diff --git a/tests/parseutils/test_function_metadata.py b/tests/parseutils/test_function_metadata.py index 0350e2a17..c4000ab1c 100644 --- a/tests/parseutils/test_function_metadata.py +++ b/tests/parseutils/test_function_metadata.py @@ -2,15 +2,9 @@ def test_function_metadata_eq(): - f1 = FunctionMetadata( - "s", "f", ["x"], ["integer"], [], "int", False, False, False, False, None - ) - f2 = FunctionMetadata( - "s", "f", ["x"], ["integer"], [], "int", False, False, False, False, None - ) - f3 = FunctionMetadata( - "s", "g", ["x"], ["integer"], [], "int", False, False, False, False, None - ) + f1 = FunctionMetadata("s", "f", ["x"], ["integer"], [], "int", False, False, False, False, None) + f2 = FunctionMetadata("s", "f", ["x"], ["integer"], [], "int", False, False, False, False, None) + f3 = FunctionMetadata("s", "g", ["x"], ["integer"], [], "int", False, False, False, False, None) assert f1 == f2 assert f1 != f3 assert not (f1 != f2) diff --git a/tests/parseutils/test_parseutils.py b/tests/parseutils/test_parseutils.py index 8a62cdbc5..90749ebfc 100644 --- a/tests/parseutils/test_parseutils.py +++ b/tests/parseutils/test_parseutils.py @@ -19,9 +19,7 @@ def test_simple_select_single_table(): assert tables == ((None, "abc", None, False),) -@pytest.mark.parametrize( - "sql", ['select * from "abc"."def"', 'select * from abc."def"'] -) +@pytest.mark.parametrize("sql", ['select * from "abc"."def"', 'select * from abc."def"']) def test_simple_select_single_table_schema_qualified_quoted_table(sql): tables = extract_tables(sql) assert tables == (("abc", "def", '"def"', False),) @@ -225,9 +223,7 @@ def test_find_prev_keyword_where(sql): assert kw.value == "where" and stripped == "select * from foo where" -@pytest.mark.parametrize( - "sql", ["create table foo (bar int, baz ", "select * from foo() as bar (baz "] -) +@pytest.mark.parametrize("sql", ["create table foo (bar int, baz ", "select * from foo() as bar (baz "]) def test_find_prev_keyword_open_parens(sql): kw, _ = find_prev_keyword(sql) assert kw.value == "(" diff --git a/tests/test_application_name.py b/tests/test_application_name.py index 5fac5b27f..e50e397a5 100644 --- a/tests/test_application_name.py +++ b/tests/test_application_name.py @@ -10,8 +10,6 @@ def test_application_name_in_env(): runner = CliRunner() app_name = "wonderful_app" with patch.object(PGExecute, "__init__") as mock_pgxecute: - runner.invoke( - cli, ["127.0.0.1:5432/hello", "user"], env={"PGAPPNAME": app_name} - ) + runner.invoke(cli, ["127.0.0.1:5432/hello", "user"], env={"PGAPPNAME": app_name}) kwargs = mock_pgxecute.call_args.kwargs assert kwargs.get("application_name") == app_name diff --git a/tests/test_auth.py b/tests/test_auth.py index a517a893c..13eed58db 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -20,9 +20,7 @@ def test_keyring_get_password_ok(): def test_keyring_get_password_exception(): with mock.patch("pgcli.auth.keyring", return_value=mock.MagicMock()): - with mock.patch( - "pgcli.auth.keyring.get_password", side_effect=Exception("Boom!") - ): + with mock.patch("pgcli.auth.keyring.get_password", side_effect=Exception("Boom!")): assert auth.keyring_get_password("test") == "" @@ -34,7 +32,5 @@ def test_keyring_set_password_ok(): def test_keyring_set_password_exception(): with mock.patch("pgcli.auth.keyring", return_value=mock.MagicMock()): - with mock.patch( - "pgcli.auth.keyring.set_password", side_effect=Exception("Boom!") - ): + with mock.patch("pgcli.auth.keyring.set_password", side_effect=Exception("Boom!")): auth.keyring_set_password("test", "abc123") diff --git a/tests/test_init_commands_simple.py b/tests/test_init_commands_simple.py index 70695dfe8..72b11f3bd 100644 --- a/tests/test_init_commands_simple.py +++ b/tests/test_init_commands_simple.py @@ -37,9 +37,7 @@ def test_init_command_option(dummy_exec): "Test that --init-command triggers execution of the command." runner = CliRunner() # Use a custom init command and --ping to exit the CLI after init commands - result = runner.invoke( - cli, ["--init-command", "SELECT foo", "--ping", "db", "user"] - ) + result = runner.invoke(cli, ["--init-command", "SELECT foo", "--ping", "db", "user"]) assert result.exit_code == 0 # Should print the init command assert "Running init commands: SELECT foo" in result.output @@ -55,15 +53,11 @@ def test_init_commands_from_config(dummy_exec, tmp_path): """ # Create a temporary config file with init-commands config_file = tmp_path / "pgclirc_test" - config_file.write_text( - "[main]\n[init-commands]\nfirst = SELECT foo;\nsecond = SELECT bar;\n" - ) + config_file.write_text("[main]\n[init-commands]\nfirst = SELECT foo;\nsecond = SELECT bar;\n") runner = CliRunner() # Use --ping to exit the CLI after init commands - result = runner.invoke( - cli, ["--pgclirc", str(config_file.absolute()), "--ping", "testdb", "user"] - ) + result = runner.invoke(cli, ["--pgclirc", str(config_file.absolute()), "--ping", "testdb", "user"]) assert result.exit_code == 0 # Should print both init commands in order (note trailing semicolons cause double ';;') assert "Running init commands: SELECT foo;; SELECT bar;" in result.output diff --git a/tests/test_naive_completion.py b/tests/test_naive_completion.py index 5b936619b..ec5034e04 100644 --- a/tests/test_naive_completion.py +++ b/tests/test_naive_completion.py @@ -21,56 +21,38 @@ def complete_event(): def test_empty_string_completion(completer, complete_event): text = "" position = 0 - result = completions_to_set( - completer.get_completions( - Document(text=text, cursor_position=position), complete_event - ) - ) + result = completions_to_set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) assert result == completions_to_set(map(Completion, completer.all_completions)) def test_select_keyword_completion(completer, complete_event): text = "SEL" position = len("SEL") - result = completions_to_set( - completer.get_completions( - Document(text=text, cursor_position=position), complete_event - ) - ) + result = completions_to_set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) assert result == completions_to_set([Completion(text="SELECT", start_position=-3)]) def test_function_name_completion(completer, complete_event): text = "SELECT MA" position = len("SELECT MA") - result = completions_to_set( - completer.get_completions( - Document(text=text, cursor_position=position), complete_event - ) - ) - assert result == completions_to_set( - [ - Completion(text="MATERIALIZED VIEW", start_position=-2), - Completion(text="MAX", start_position=-2), - Completion(text="MAXEXTENTS", start_position=-2), - Completion(text="MAKE_DATE", start_position=-2), - Completion(text="MAKE_TIME", start_position=-2), - Completion(text="MAKE_TIMESTAMPTZ", start_position=-2), - Completion(text="MAKE_INTERVAL", start_position=-2), - Completion(text="MASKLEN", start_position=-2), - Completion(text="MAKE_TIMESTAMP", start_position=-2), - ] - ) + result = completions_to_set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) + assert result == completions_to_set([ + Completion(text="MATERIALIZED VIEW", start_position=-2), + Completion(text="MAX", start_position=-2), + Completion(text="MAXEXTENTS", start_position=-2), + Completion(text="MAKE_DATE", start_position=-2), + Completion(text="MAKE_TIME", start_position=-2), + Completion(text="MAKE_TIMESTAMPTZ", start_position=-2), + Completion(text="MAKE_INTERVAL", start_position=-2), + Completion(text="MASKLEN", start_position=-2), + Completion(text="MAKE_TIMESTAMP", start_position=-2), + ]) def test_column_name_completion(completer, complete_event): text = "SELECT FROM users" position = len("SELECT ") - result = completions_to_set( - completer.get_completions( - Document(text=text, cursor_position=position), complete_event - ) - ) + result = completions_to_set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) assert result == completions_to_set(map(Completion, completer.all_completions)) @@ -84,27 +66,18 @@ def test_alter_well_known_keywords_completion(completer, complete_event): smart_completion=True, ) ) - assert result > completions_to_set( - [ - Completion(text="DATABASE", display_meta="keyword"), - Completion(text="TABLE", display_meta="keyword"), - Completion(text="SYSTEM", display_meta="keyword"), - ] - ) - assert ( - completions_to_set([Completion(text="CREATE", display_meta="keyword")]) - not in result - ) + assert result > completions_to_set([ + Completion(text="DATABASE", display_meta="keyword"), + Completion(text="TABLE", display_meta="keyword"), + Completion(text="SYSTEM", display_meta="keyword"), + ]) + assert completions_to_set([Completion(text="CREATE", display_meta="keyword")]) not in result def test_special_name_completion(completer, complete_event): text = "\\" position = len("\\") - result = completions_to_set( - completer.get_completions( - Document(text=text, cursor_position=position), complete_event - ) - ) + result = completions_to_set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) # Special commands will NOT be suggested during naive completion mode. assert result == completions_to_set([]) @@ -119,15 +92,13 @@ def test_datatype_name_completion(completer, complete_event): smart_completion=True, ) ) - assert result == completions_to_set( - [ - Completion(text="INET", display_meta="datatype"), - Completion(text="INT", display_meta="datatype"), - Completion(text="INT2", display_meta="datatype"), - Completion(text="INT4", display_meta="datatype"), - Completion(text="INT8", display_meta="datatype"), - Completion(text="INTEGER", display_meta="datatype"), - Completion(text="INTERNAL", display_meta="datatype"), - Completion(text="INTERVAL", display_meta="datatype"), - ] - ) + assert result == completions_to_set([ + Completion(text="INET", display_meta="datatype"), + Completion(text="INT", display_meta="datatype"), + Completion(text="INT2", display_meta="datatype"), + Completion(text="INT4", display_meta="datatype"), + Completion(text="INT8", display_meta="datatype"), + Completion(text="INTEGER", display_meta="datatype"), + Completion(text="INTERNAL", display_meta="datatype"), + Completion(text="INTERVAL", display_meta="datatype"), + ]) diff --git a/tests/test_pgcompleter.py b/tests/test_pgcompleter.py index 4b2d9d0dc..a9f390d76 100644 --- a/tests/test_pgcompleter.py +++ b/tests/test_pgcompleter.py @@ -39,9 +39,7 @@ def test_generate_alias_uses_upper_case_letters_from_name(table_name, alias): ("sometable", "s"), ], ) -def test_generate_alias_uses_first_char_and_every_preceded_by_underscore( - table_name, alias -): +def test_generate_alias_uses_first_char_and_every_preceded_by_underscore(table_name, alias): assert pgcompleter.generate_alias(table_name) == alias @@ -49,9 +47,7 @@ def test_generate_alias_uses_first_char_and_every_preceded_by_underscore( "table_name, alias_map, alias", [ ("some_table", {"some_table": "my_alias"}, "my_alias"), - pytest.param( - "some_other_table", {"some_table": "my_alias"}, "sot", id="no_match_in_map" - ), + pytest.param("some_other_table", {"some_table": "my_alias"}, "sot", id="no_match_in_map"), ], ) def test_generate_alias_can_use_alias_map(table_name, alias_map, alias): @@ -83,9 +79,7 @@ def test_pgcompleter_alias_uses_configured_alias_map(table_name, alias_map, alia ("SomeTable", {"SomeTable": "my_alias"}, "my_alias"), ], ) -def test_generate_alias_prefers_alias_over_upper_case_name( - table_name, alias_map, alias -): +def test_generate_alias_prefers_alias_over_upper_case_name(table_name, alias_map, alias): assert pgcompleter.generate_alias(table_name, alias_map) == alias diff --git a/tests/test_sqlcompletion.py b/tests/test_sqlcompletion.py index f53e4bea6..3f99d6a32 100644 --- a/tests/test_sqlcompletion.py +++ b/tests/test_sqlcompletion.py @@ -18,9 +18,7 @@ import pytest -def cols_etc( - table, schema=None, alias=None, is_function=False, parent=None, last_keyword=None -): +def cols_etc(table, schema=None, alias=None, is_function=False, parent=None, last_keyword=None): """Returns the expected select-clause suggestions for a single-table select.""" return { @@ -117,9 +115,7 @@ def test_select_suggests_cols_and_funcs(): } -@pytest.mark.parametrize( - "expression", ["INSERT INTO ", "COPY ", "UPDATE ", "DESCRIBE "] -) +@pytest.mark.parametrize("expression", ["INSERT INTO ", "COPY ", "UPDATE ", "DESCRIBE "]) def test_suggests_tables_views_and_schemas(expression): suggestions = suggest_type(expression, expression) assert set(suggestions) == {Table(schema=None), View(schema=None), Schema()} @@ -148,9 +144,7 @@ def test_suggest_after_join_with_two_tables(expression): } -@pytest.mark.parametrize( - "expression", ["SELECT * FROM foo JOIN ", "SELECT * FROM foo JOIN bar"] -) +@pytest.mark.parametrize("expression", ["SELECT * FROM foo JOIN ", "SELECT * FROM foo JOIN bar"]) def test_suggest_after_join_with_one_table(expression): suggestions = suggest_type(expression, expression) tables = ((None, "foo", None, False),) @@ -161,9 +155,7 @@ def test_suggest_after_join_with_one_table(expression): } -@pytest.mark.parametrize( - "expression", ["INSERT INTO sch.", "COPY sch.", "DESCRIBE sch."] -) +@pytest.mark.parametrize("expression", ["INSERT INTO sch.", "COPY sch.", "DESCRIBE sch."]) def test_suggest_qualified_tables_and_views(expression): suggestions = suggest_type(expression, expression) assert set(suggestions) == {Table(schema="sch"), View(schema="sch")} @@ -210,9 +202,7 @@ def test_truncate_suggests_qualified_tables(): assert set(suggestions) == {Table(schema="sch")} -@pytest.mark.parametrize( - "text", ["SELECT DISTINCT ", "INSERT INTO foo SELECT DISTINCT "] -) +@pytest.mark.parametrize("text", ["SELECT DISTINCT ", "INSERT INTO foo SELECT DISTINCT "]) def test_distinct_suggests_cols(text): suggestions = suggest_type(text, text) assert set(suggestions) == { @@ -233,9 +223,7 @@ def test_distinct_suggests_cols(text): ), ], ) -def test_distinct_and_order_by_suggestions_with_aliases( - text, text_before, last_keyword -): +def test_distinct_and_order_by_suggestions_with_aliases(text, text_before, last_keyword): suggestions = suggest_type(text, text_before) assert set(suggestions) == { Column( @@ -309,34 +297,24 @@ def test_into_suggests_tables_and_schemas(): assert set(suggestion) == {Table(schema=None), View(schema=None), Schema()} -@pytest.mark.parametrize( - "text", ["INSERT INTO abc (", "INSERT INTO abc () SELECT * FROM hij;"] -) +@pytest.mark.parametrize("text", ["INSERT INTO abc (", "INSERT INTO abc () SELECT * FROM hij;"]) def test_insert_into_lparen_suggests_cols(text): suggestions = suggest_type(text, "INSERT INTO abc (") - assert suggestions == ( - Column(table_refs=((None, "abc", None, False),), context="insert"), - ) + assert suggestions == (Column(table_refs=((None, "abc", None, False),), context="insert"),) def test_insert_into_lparen_partial_text_suggests_cols(): suggestions = suggest_type("INSERT INTO abc (i", "INSERT INTO abc (i") - assert suggestions == ( - Column(table_refs=((None, "abc", None, False),), context="insert"), - ) + assert suggestions == (Column(table_refs=((None, "abc", None, False),), context="insert"),) def test_insert_into_lparen_comma_suggests_cols(): suggestions = suggest_type("INSERT INTO abc (id,", "INSERT INTO abc (id,") - assert suggestions == ( - Column(table_refs=((None, "abc", None, False),), context="insert"), - ) + assert suggestions == (Column(table_refs=((None, "abc", None, False),), context="insert"),) def test_partially_typed_col_name_suggests_col_names(): - suggestions = suggest_type( - "SELECT * FROM tabl WHERE col_n", "SELECT * FROM tabl WHERE col_n" - ) + suggestions = suggest_type("SELECT * FROM tabl WHERE col_n", "SELECT * FROM tabl WHERE col_n") assert set(suggestions) == cols_etc("tabl", last_keyword="WHERE") @@ -389,9 +367,7 @@ def test_dot_suggests_cols_of_an_alias_where(sql): def test_dot_col_comma_suggests_cols_or_schema_qualified_table(): - suggestions = suggest_type( - "SELECT t1.a, t2. FROM tabl1 t1, tabl2 t2", "SELECT t1.a, t2." - ) + suggestions = suggest_type("SELECT t1.a, t2. FROM tabl1 t1, tabl2 t2", "SELECT t1.a, t2.") assert set(suggestions) == { Column(table_refs=((None, "tabl2", "t2", False),)), Table(schema="t2"), @@ -457,9 +433,7 @@ def test_sub_select_table_name_completion_with_outer_table(expression): def test_sub_select_col_name_completion(): - suggestions = suggest_type( - "SELECT * FROM (SELECT FROM abc", "SELECT * FROM (SELECT " - ) + suggestions = suggest_type("SELECT * FROM (SELECT FROM abc", "SELECT * FROM (SELECT ") assert set(suggestions) == { Column(table_refs=((None, "abc", None, False),), qualifiable=True), Function(schema=None), @@ -469,16 +443,12 @@ def test_sub_select_col_name_completion(): @pytest.mark.xfail def test_sub_select_multiple_col_name_completion(): - suggestions = suggest_type( - "SELECT * FROM (SELECT a, FROM abc", "SELECT * FROM (SELECT a, " - ) + suggestions = suggest_type("SELECT * FROM (SELECT a, FROM abc", "SELECT * FROM (SELECT a, ") assert set(suggestions) == cols_etc("abc") def test_sub_select_dot_col_name_completion(): - suggestions = suggest_type( - "SELECT * FROM (SELECT t. FROM tabl t", "SELECT * FROM (SELECT t." - ) + suggestions = suggest_type("SELECT * FROM (SELECT t. FROM tabl t", "SELECT * FROM (SELECT t.") assert set(suggestions) == { Column(table_refs=((None, "tabl", "t", False),)), Table(schema="t"), @@ -627,9 +597,7 @@ def test_on_suggests_tables_and_join_conditions_right_side(sql): ) def test_join_using_suggests_common_columns(text): tables = ((None, "abc", None, False), (None, "def", None, False)) - assert set(suggest_type(text, text)) == { - Column(table_refs=tables, require_last_table=True) - } + assert set(suggest_type(text, text)) == {Column(table_refs=tables, require_last_table=True)} def test_suggest_columns_after_multiple_joins(): @@ -643,14 +611,10 @@ def test_suggest_columns_after_multiple_joins(): def test_2_statements_2nd_current(): - suggestions = suggest_type( - "select * from a; select * from ", "select * from a; select * from " - ) + suggestions = suggest_type("select * from a; select * from ", "select * from a; select * from ") assert set(suggestions) == {FromClauseItem(schema=None), Schema()} - suggestions = suggest_type( - "select * from a; select from b", "select * from a; select " - ) + suggestions = suggest_type("select * from a; select from b", "select * from a; select ") assert set(suggestions) == { Column(table_refs=((None, "b", None, False),), qualifiable=True), Function(schema=None), @@ -658,9 +622,7 @@ def test_2_statements_2nd_current(): } # Should work even if first statement is invalid - suggestions = suggest_type( - "select * from; select * from ", "select * from; select * from " - ) + suggestions = suggest_type("select * from; select * from ", "select * from; select * from ") assert set(suggestions) == {FromClauseItem(schema=None), Schema()} @@ -679,9 +641,7 @@ def test_3_statements_2nd_current(): ) assert set(suggestions) == {FromClauseItem(schema=None), Schema()} - suggestions = suggest_type( - "select * from a; select from b; select * from c", "select * from a; select " - ) + suggestions = suggest_type("select * from a; select from b; select * from c", "select * from a; select ") assert set(suggestions) == cols_etc("b", last_keyword="SELECT") @@ -773,9 +733,7 @@ def test_statements_with_cursor_before_function_body(text): def test_create_db_with_template(): - suggestions = suggest_type( - "create database foo with template ", "create database foo with template " - ) + suggestions = suggest_type("create database foo with template ", "create database foo with template ") assert set(suggestions) == {Database()} @@ -814,9 +772,7 @@ def test_cast_operator_suggests_types(text): } -@pytest.mark.parametrize( - "text", ["SELECT foo::bar.", "SELECT foo::bar.baz", "SELECT (x + y)::bar."] -) +@pytest.mark.parametrize("text", ["SELECT foo::bar.", "SELECT foo::bar.baz", "SELECT (x + y)::bar."]) def test_cast_operator_suggests_schema_qualified_types(text): assert set(suggest_type(text, text)) == { Datatype(schema="bar"), diff --git a/tests/test_ssh_tunnel.py b/tests/test_ssh_tunnel.py index 983212b8a..c8670141b 100644 --- a/tests/test_ssh_tunnel.py +++ b/tests/test_ssh_tunnel.py @@ -12,9 +12,7 @@ @pytest.fixture def mock_ssh_tunnel_forwarder() -> MagicMock: - mock_ssh_tunnel_forwarder = MagicMock( - SSHTunnelForwarder, local_bind_ports=[1111], autospec=True - ) + mock_ssh_tunnel_forwarder = MagicMock(SSHTunnelForwarder, local_bind_ports=[1111], autospec=True) with patch( "pgcli.main.sshtunnel.SSHTunnelForwarder", return_value=mock_ssh_tunnel_forwarder, @@ -28,9 +26,7 @@ def mock_pgexecute() -> MagicMock: yield mock_pgexecute -def test_ssh_tunnel( - mock_ssh_tunnel_forwarder: MagicMock, mock_pgexecute: MagicMock -) -> None: +def test_ssh_tunnel(mock_ssh_tunnel_forwarder: MagicMock, mock_pgexecute: MagicMock) -> None: # Test with just a host tunnel_url = "some.host" db_params = { @@ -103,18 +99,12 @@ def test_ssh_tunnel( mock_pgexecute.reset_mock() # Test with DSN - dsn = ( - f"user={db_params['user']} password={db_params['passwd']} " - f"host={db_params['host']} port={db_params['port']}" - ) + dsn = f"user={db_params['user']} password={db_params['passwd']} host={db_params['host']} port={db_params['port']}" pgcli = PGCli(ssh_tunnel_url=tunnel_url) pgcli.connect(dsn=dsn) - expected_dsn = ( - f"user={db_params['user']} password={db_params['passwd']} " - f"host=127.0.0.1 port={pgcli.ssh_tunnel.local_bind_ports[0]}" - ) + expected_dsn = f"user={db_params['user']} password={db_params['passwd']} host=127.0.0.1 port={pgcli.ssh_tunnel.local_bind_ports[0]}" mock_ssh_tunnel_forwarder.assert_called_once_with(**expected_tunnel_params) mock_pgexecute.assert_called_once() @@ -126,18 +116,14 @@ def test_ssh_tunnel( def test_cli_with_tunnel() -> None: runner = CliRunner() tunnel_url = "mytunnel" - with patch.object( - PGCli, "__init__", autospec=True, return_value=None - ) as mock_pgcli: + with patch.object(PGCli, "__init__", autospec=True, return_value=None) as mock_pgcli: runner.invoke(cli, ["--ssh-tunnel", tunnel_url]) mock_pgcli.assert_called_once() call_args, call_kwargs = mock_pgcli.call_args assert call_kwargs["ssh_tunnel_url"] == tunnel_url -def test_config( - tmpdir: os.PathLike, mock_ssh_tunnel_forwarder: MagicMock, mock_pgexecute: MagicMock -) -> None: +def test_config(tmpdir: os.PathLike, mock_ssh_tunnel_forwarder: MagicMock, mock_pgexecute: MagicMock) -> None: pgclirc = str(tmpdir.join("rcfile")) tunnel_user = "tunnel_user" diff --git a/tox.ini b/tox.ini index 786738460..1b8ea025a 100644 --- a/tox.ini +++ b/tox.ini @@ -16,8 +16,7 @@ passenv = PGHOST skip_install = true deps = ruff commands = ruff check -# TODO: Uncomment the following line to enable ruff formatting -# ruff format --diff + ruff format --diff [testenv:integration] skip_install = true