diff options
author | Miroslav Šedivý <6774676+eumiro@users.noreply.github.com> | 2021-02-12 20:34:56 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-02-12 21:34:56 +0200 |
commit | 762fb4b8da98fdf6792e6c5586060ed37224f894 (patch) | |
tree | dca17819ff2a516988e2f74691dcef0554637464 /tests | |
parent | 87ffae295edf4fb2a9c33c552b12f09921def29f (diff) |
Modernize code to Python 3.6+ (#1229)
1. `class A(object)` can be written as `class A:`
2. replace `dict([…])` and `set([…])` with `{…}`
3. use f-strings or compact `.format`
4. use `yield from` instead of `yield` in a `for` loop
5. import `mock` from `unittest`
6. expect `OSError` instead of `IOError` or `select` error
7. use Python3 defaults for file reading or `super()`
8. remove redundant parenthesis (keep those in tuples though)
9. shorten set intersection instead of creating lists
10. backslashes in strings do not have to be escaped if prepended with `r`
Diffstat (limited to 'tests')
-rw-r--r-- | tests/features/db_utils.py | 4 | ||||
-rw-r--r-- | tests/features/environment.py | 10 | ||||
-rw-r--r-- | tests/features/fixture_utils.py | 2 | ||||
-rw-r--r-- | tests/features/steps/basic_commands.py | 12 | ||||
-rw-r--r-- | tests/features/steps/crud_database.py | 8 | ||||
-rw-r--r-- | tests/features/steps/expanded.py | 2 | ||||
-rw-r--r-- | tests/features/steps/iocommands.py | 6 | ||||
-rw-r--r-- | tests/features/steps/wrappers.py | 2 | ||||
-rw-r--r-- | tests/metadata.py | 6 | ||||
-rw-r--r-- | tests/parseutils/test_parseutils.py | 40 | ||||
-rw-r--r-- | tests/test_completion_refresher.py | 2 | ||||
-rw-r--r-- | tests/test_main.py | 2 | ||||
-rw-r--r-- | tests/test_naive_completion.py | 2 | ||||
-rw-r--r-- | tests/test_pgexecute.py | 116 | ||||
-rw-r--r-- | tests/test_pgspecial.py | 24 | ||||
-rw-r--r-- | tests/test_rowlimit.py | 2 | ||||
-rw-r--r-- | tests/test_smart_completion_multiple_schemata.py | 2 | ||||
-rw-r--r-- | tests/test_smart_completion_public_schema_only.py | 6 | ||||
-rw-r--r-- | tests/test_sqlcompletion.py | 425 | ||||
-rw-r--r-- | tests/utils.py | 4 |
20 files changed, 321 insertions, 356 deletions
diff --git a/tests/features/db_utils.py b/tests/features/db_utils.py index f57bc3b9..6898394e 100644 --- a/tests/features/db_utils.py +++ b/tests/features/db_utils.py @@ -44,7 +44,7 @@ def create_cn(hostname, password, username, dbname, port): host=hostname, user=username, database=dbname, password=password, port=port ) - print("Created connection: {0}.".format(cn.dsn)) + print(f"Created connection: {cn.dsn}.") return cn @@ -75,4 +75,4 @@ def close_cn(cn=None): """ if cn: cn.close() - print("Closed connection: {0}.".format(cn.dsn)) + print(f"Closed connection: {cn.dsn}.") diff --git a/tests/features/environment.py b/tests/features/environment.py index 049c2f23..a8b3e26a 100644 --- a/tests/features/environment.py +++ b/tests/features/environment.py @@ -38,7 +38,7 @@ def before_all(context): vi = "_".join([str(x) for x in sys.version_info[:3]]) db_name = context.config.userdata.get("pg_test_db", "pgcli_behave_tests") - db_name_full = "{0}_{1}".format(db_name, vi) + db_name_full = f"{db_name}_{vi}" # Store get params from config. context.conf = { @@ -122,12 +122,12 @@ def before_all(context): def show_env_changes(env_old, env_new): """Print out all test-specific env values.""" print("--- os.environ changed values: ---") - all_keys = set(list(env_old.keys()) + list(env_new.keys())) + all_keys = env_old.keys() | env_new.keys() for k in sorted(all_keys): old_value = env_old.get(k, "") new_value = env_new.get(k, "") if new_value and old_value != new_value: - print('{}="{}"'.format(k, new_value)) + print(f'{k}="{new_value}"') print("-" * 20) @@ -173,13 +173,13 @@ def after_scenario(context, scenario): # Quit nicely. if not context.atprompt: dbname = context.currentdb - context.cli.expect_exact("{0}> ".format(dbname), timeout=15) + context.cli.expect_exact(f"{dbname}> ", timeout=15) context.cli.sendcontrol("c") context.cli.sendcontrol("d") try: context.cli.expect_exact(pexpect.EOF, timeout=15) except pexpect.TIMEOUT: - print("--- after_scenario {}: kill cli".format(scenario.name)) + print(f"--- after_scenario {scenario.name}: kill cli") context.cli.kill(signal.SIGKILL) if hasattr(context, "tmpfile_sql_help") and context.tmpfile_sql_help: context.tmpfile_sql_help.close() diff --git a/tests/features/fixture_utils.py b/tests/features/fixture_utils.py index 16f123a6..70b603d8 100644 --- a/tests/features/fixture_utils.py +++ b/tests/features/fixture_utils.py @@ -18,7 +18,7 @@ def read_fixture_files(): """Read all files inside fixture_data directory.""" current_dir = os.path.dirname(__file__) fixture_dir = os.path.join(current_dir, "fixture_data/") - print("reading fixture data: {}".format(fixture_dir)) + print(f"reading fixture data: {fixture_dir}") fixture_dict = {} for filename in os.listdir(fixture_dir): if filename not in [".", ".."]: diff --git a/tests/features/steps/basic_commands.py b/tests/features/steps/basic_commands.py index a1fca8b0..07e9ec17 100644 --- a/tests/features/steps/basic_commands.py +++ b/tests/features/steps/basic_commands.py @@ -66,19 +66,19 @@ def step_ctrl_d(context): """ # turn off pager before exiting context.cli.sendcontrol("c") - context.cli.sendline("\pset pager off") + context.cli.sendline(r"\pset pager off") wrappers.wait_prompt(context) context.cli.sendcontrol("d") context.cli.expect(pexpect.EOF, timeout=15) context.exit_sent = True -@when('we send "\?" command') +@when(r'we send "\?" command') def step_send_help(context): - """ + r""" Send \? to see help. """ - context.cli.sendline("\?") + context.cli.sendline(r"\?") @when("we send partial select command") @@ -97,9 +97,9 @@ def step_see_error_message(context): @when("we send source command") def step_send_source_command(context): context.tmpfile_sql_help = tempfile.NamedTemporaryFile(prefix="pgcli_") - context.tmpfile_sql_help.write(b"\?") + context.tmpfile_sql_help.write(br"\?") context.tmpfile_sql_help.flush() - context.cli.sendline("\i {0}".format(context.tmpfile_sql_help.name)) + context.cli.sendline(fr"\i {context.tmpfile_sql_help.name}") wrappers.expect_exact(context, context.conf["pager_boundary"] + "\r\n", timeout=5) diff --git a/tests/features/steps/crud_database.py b/tests/features/steps/crud_database.py index 3fd8b7a1..3f5d0e71 100644 --- a/tests/features/steps/crud_database.py +++ b/tests/features/steps/crud_database.py @@ -14,7 +14,7 @@ def step_db_create(context): """ Send create database. """ - context.cli.sendline("create database {0};".format(context.conf["dbname_tmp"])) + context.cli.sendline("create database {};".format(context.conf["dbname_tmp"])) context.response = {"database_name": context.conf["dbname_tmp"]} @@ -24,7 +24,7 @@ def step_db_drop(context): """ Send drop database. """ - context.cli.sendline("drop database {0};".format(context.conf["dbname_tmp"])) + context.cli.sendline("drop database {};".format(context.conf["dbname_tmp"])) @when("we connect to test database") @@ -33,7 +33,7 @@ def step_db_connect_test(context): Send connect to database. """ db_name = context.conf["dbname"] - context.cli.sendline("\\connect {0}".format(db_name)) + context.cli.sendline(f"\\connect {db_name}") @when("we connect to dbserver") @@ -59,7 +59,7 @@ def step_see_prompt(context): Wait to see the prompt. """ db_name = getattr(context, "currentdb", context.conf["dbname"]) - wrappers.expect_exact(context, "{0}> ".format(db_name), timeout=5) + wrappers.expect_exact(context, f"{db_name}> ", timeout=5) context.atprompt = True diff --git a/tests/features/steps/expanded.py b/tests/features/steps/expanded.py index f34fcf04..265ea39b 100644 --- a/tests/features/steps/expanded.py +++ b/tests/features/steps/expanded.py @@ -31,7 +31,7 @@ def step_prepare_data(context): @when("we set expanded {mode}") def step_set_expanded(context, mode): """Set expanded to mode.""" - context.cli.sendline("\\" + "x {}".format(mode)) + context.cli.sendline("\\" + f"x {mode}") wrappers.expect_exact(context, "Expanded display is", timeout=2) wrappers.wait_prompt(context) diff --git a/tests/features/steps/iocommands.py b/tests/features/steps/iocommands.py index 613aeb29..a614490a 100644 --- a/tests/features/steps/iocommands.py +++ b/tests/features/steps/iocommands.py @@ -13,7 +13,7 @@ def step_edit_file(context): ) if os.path.exists(context.editor_file_name): os.remove(context.editor_file_name) - context.cli.sendline("\e {0}".format(os.path.basename(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 ) @@ -53,7 +53,7 @@ def step_tee_ouptut(context): ) if os.path.exists(context.tee_file_name): os.remove(context.tee_file_name) - context.cli.sendline("\o {0}".format(os.path.basename(context.tee_file_name))) + context.cli.sendline(r"\o {}".format(os.path.basename(context.tee_file_name))) wrappers.expect_exact(context, context.conf["pager_boundary"] + "\r\n", timeout=5) wrappers.expect_exact(context, "Writing to file", timeout=5) wrappers.expect_exact(context, context.conf["pager_boundary"] + "\r\n", timeout=5) @@ -67,7 +67,7 @@ def step_query_select_123456(context): @when("we stop teeing output") def step_notee_output(context): - context.cli.sendline("\o") + context.cli.sendline(r"\o") wrappers.expect_exact(context, "Time", timeout=5) diff --git a/tests/features/steps/wrappers.py b/tests/features/steps/wrappers.py index e0f5a20e..78d76881 100644 --- a/tests/features/steps/wrappers.py +++ b/tests/features/steps/wrappers.py @@ -57,7 +57,7 @@ def run_cli(context, run_args=None, prompt_check=True, currentdb=None): context.cli.logfile = context.logfile context.exit_sent = False context.currentdb = currentdb or context.conf["dbname"] - context.cli.sendline("\pset pager always") + context.cli.sendline(r"\pset pager always") if prompt_check: wait_prompt(context) diff --git a/tests/metadata.py b/tests/metadata.py index 2f89ea28..4ebcccd0 100644 --- a/tests/metadata.py +++ b/tests/metadata.py @@ -3,7 +3,7 @@ from itertools import product from pgcli.packages.parseutils.meta import FunctionMetadata, ForeignKey from prompt_toolkit.completion import Completion from prompt_toolkit.document import Document -from mock import Mock +from unittest.mock import Mock import pytest parametrize = pytest.mark.parametrize @@ -59,7 +59,7 @@ def wildcard_expansion(cols, pos=-1): return Completion(cols, start_position=pos, display_meta="columns", display="*") -class MetaData(object): +class MetaData: def __init__(self, metadata): self.metadata = metadata @@ -128,7 +128,7 @@ class MetaData(object): ] def schemas(self, pos=0): - schemas = set(sch for schs in self.metadata.values() for sch in schs) + schemas = {sch for schs in self.metadata.values() for sch in schs} return [schema(escape(s), pos=pos) for s in schemas] def functions_and_keywords(self, parent="public", pos=0): diff --git a/tests/parseutils/test_parseutils.py b/tests/parseutils/test_parseutils.py index 50bc8896..aaeb3f91 100644 --- a/tests/parseutils/test_parseutils.py +++ b/tests/parseutils/test_parseutils.py @@ -34,12 +34,12 @@ def test_simple_select_single_table_double_quoted(): def test_simple_select_multiple_tables(): tables = extract_tables("select * from abc, def") - assert set(tables) == set([(None, "abc", None, False), (None, "def", None, False)]) + assert set(tables) == {(None, "abc", None, False), (None, "def", None, False)} def test_simple_select_multiple_tables_double_quoted(): tables = extract_tables('select * from "Abc", "Def"') - assert set(tables) == set([(None, "Abc", None, False), (None, "Def", None, False)]) + assert set(tables) == {(None, "Abc", None, False), (None, "Def", None, False)} def test_simple_select_single_table_deouble_quoted_aliased(): @@ -49,14 +49,12 @@ def test_simple_select_single_table_deouble_quoted_aliased(): def test_simple_select_multiple_tables_deouble_quoted_aliased(): tables = extract_tables('select * from "Abc" a, "Def" d') - assert set(tables) == set([(None, "Abc", "a", False), (None, "Def", "d", False)]) + assert set(tables) == {(None, "Abc", "a", False), (None, "Def", "d", False)} def test_simple_select_multiple_tables_schema_qualified(): tables = extract_tables("select * from abc.def, ghi.jkl") - assert set(tables) == set( - [("abc", "def", None, False), ("ghi", "jkl", None, False)] - ) + assert set(tables) == {("abc", "def", None, False), ("ghi", "jkl", None, False)} def test_simple_select_with_cols_single_table(): @@ -71,14 +69,12 @@ def test_simple_select_with_cols_single_table_schema_qualified(): def test_simple_select_with_cols_multiple_tables(): tables = extract_tables("select a,b from abc, def") - assert set(tables) == set([(None, "abc", None, False), (None, "def", None, False)]) + assert set(tables) == {(None, "abc", None, False), (None, "def", None, False)} def test_simple_select_with_cols_multiple_qualified_tables(): tables = extract_tables("select a,b from abc.def, def.ghi") - assert set(tables) == set( - [("abc", "def", None, False), ("def", "ghi", None, False)] - ) + assert set(tables) == {("abc", "def", None, False), ("def", "ghi", None, False)} def test_select_with_hanging_comma_single_table(): @@ -88,14 +84,12 @@ def test_select_with_hanging_comma_single_table(): def test_select_with_hanging_comma_multiple_tables(): tables = extract_tables("select a, from abc, def") - assert set(tables) == set([(None, "abc", None, False), (None, "def", None, False)]) + assert set(tables) == {(None, "abc", None, False), (None, "def", None, False)} def test_select_with_hanging_period_multiple_tables(): tables = extract_tables("SELECT t1. FROM tabl1 t1, tabl2 t2") - assert set(tables) == set( - [(None, "tabl1", "t1", False), (None, "tabl2", "t2", False)] - ) + assert set(tables) == {(None, "tabl1", "t1", False), (None, "tabl2", "t2", False)} def test_simple_insert_single_table(): @@ -126,14 +120,14 @@ def test_simple_update_table_with_schema(): @pytest.mark.parametrize("join_type", ["", "INNER", "LEFT", "RIGHT OUTER"]) def test_join_table(join_type): - sql = "SELECT * FROM abc a {0} JOIN def d ON a.id = d.num".format(join_type) + sql = f"SELECT * FROM abc a {join_type} JOIN def d ON a.id = d.num" tables = extract_tables(sql) - assert set(tables) == set([(None, "abc", "a", False), (None, "def", "d", False)]) + assert set(tables) == {(None, "abc", "a", False), (None, "def", "d", False)} def test_join_table_schema_qualified(): tables = extract_tables("SELECT * FROM abc.def x JOIN ghi.jkl y ON x.id = y.num") - assert set(tables) == set([("abc", "def", "x", False), ("ghi", "jkl", "y", False)]) + assert set(tables) == {("abc", "def", "x", False), ("ghi", "jkl", "y", False)} def test_incomplete_join_clause(): @@ -177,25 +171,25 @@ def test_extract_no_tables(text): @pytest.mark.parametrize("arg_list", ["", "arg1", "arg1, arg2, arg3"]) def test_simple_function_as_table(arg_list): - tables = extract_tables("SELECT * FROM foo({0})".format(arg_list)) + tables = extract_tables(f"SELECT * FROM foo({arg_list})") assert tables == ((None, "foo", None, True),) @pytest.mark.parametrize("arg_list", ["", "arg1", "arg1, arg2, arg3"]) def test_simple_schema_qualified_function_as_table(arg_list): - tables = extract_tables("SELECT * FROM foo.bar({0})".format(arg_list)) + tables = extract_tables(f"SELECT * FROM foo.bar({arg_list})") assert tables == (("foo", "bar", None, True),) @pytest.mark.parametrize("arg_list", ["", "arg1", "arg1, arg2, arg3"]) def test_simple_aliased_function_as_table(arg_list): - tables = extract_tables("SELECT * FROM foo({0}) bar".format(arg_list)) + tables = extract_tables(f"SELECT * FROM foo({arg_list}) bar") assert tables == ((None, "foo", "bar", True),) def test_simple_table_and_function(): tables = extract_tables("SELECT * FROM foo JOIN bar()") - assert set(tables) == set([(None, "foo", None, False), (None, "bar", None, True)]) + assert set(tables) == {(None, "foo", None, False), (None, "bar", None, True)} def test_complex_table_and_function(): @@ -203,9 +197,7 @@ def test_complex_table_and_function(): """SELECT * FROM foo.bar baz JOIN bar.qux(x, y, z) quux""" ) - assert set(tables) == set( - [("foo", "bar", "baz", False), ("bar", "qux", "quux", True)] - ) + assert set(tables) == {("foo", "bar", "baz", False), ("bar", "qux", "quux", True)} def test_find_prev_keyword_using(): diff --git a/tests/test_completion_refresher.py b/tests/test_completion_refresher.py index 6a916a81..34cf5700 100644 --- a/tests/test_completion_refresher.py +++ b/tests/test_completion_refresher.py @@ -1,6 +1,6 @@ import time import pytest -from mock import Mock, patch +from unittest.mock import Mock, patch @pytest.fixture diff --git a/tests/test_main.py b/tests/test_main.py index 9b85a34b..965ff8fa 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,6 +1,6 @@ import os import platform -import mock +from unittest import mock import pytest diff --git a/tests/test_naive_completion.py b/tests/test_naive_completion.py index a6c80a7c..5b936619 100644 --- a/tests/test_naive_completion.py +++ b/tests/test_naive_completion.py @@ -13,7 +13,7 @@ def completer(): @pytest.fixture def complete_event(): - from mock import Mock + from unittest.mock import Mock return Mock() diff --git a/tests/test_pgexecute.py b/tests/test_pgexecute.py index 9273be94..513e6192 100644 --- a/tests/test_pgexecute.py +++ b/tests/test_pgexecute.py @@ -2,7 +2,7 @@ from textwrap import dedent import psycopg2 import pytest -from mock import patch, MagicMock +from unittest.mock import patch, MagicMock from pgspecial.main import PGSpecial, NO_QUERY from utils import run, dbtest, requires_json, requires_jsonb @@ -89,7 +89,7 @@ def test_expanded_slash_G(executor, pgspecial): # Tests whether we reset the expanded output after a \G. run(executor, """create table test(a boolean)""") run(executor, """insert into test values(True)""") - results = run(executor, """select * from test \G""", pgspecial=pgspecial) + results = run(executor, r"""select * from test \G""", pgspecial=pgspecial) assert pgspecial.expanded_output == False @@ -105,31 +105,35 @@ def test_schemata_table_views_and_columns_query(executor): # schemata # don't enforce all members of the schemas since they may include postgres # temporary schemas - assert set(executor.schemata()) >= set( - ["public", "pg_catalog", "information_schema", "schema1", "schema2"] - ) + assert set(executor.schemata()) >= { + "public", + "pg_catalog", + "information_schema", + "schema1", + "schema2", + } assert executor.search_path() == ["pg_catalog", "public"] # tables - assert set(executor.tables()) >= set( - [("public", "a"), ("public", "b"), ("schema1", "c")] - ) - - assert set(executor.table_columns()) >= set( - [ - ("public", "a", "x", "text", False, None), - ("public", "a", "y", "text", False, None), - ("public", "b", "z", "text", False, None), - ("schema1", "c", "w", "text", True, "'meow'::text"), - ] - ) + assert set(executor.tables()) >= { + ("public", "a"), + ("public", "b"), + ("schema1", "c"), + } + + assert set(executor.table_columns()) >= { + ("public", "a", "x", "text", False, None), + ("public", "a", "y", "text", False, None), + ("public", "b", "z", "text", False, None), + ("schema1", "c", "w", "text", True, "'meow'::text"), + } # views - assert set(executor.views()) >= set([("public", "d")]) + assert set(executor.views()) >= {("public", "d")} - assert set(executor.view_columns()) >= set( - [("public", "d", "e", "integer", False, None)] - ) + assert set(executor.view_columns()) >= { + ("public", "d", "e", "integer", False, None) + } @dbtest @@ -142,9 +146,9 @@ def test_foreign_key_query(executor): "create table schema2.child(childid int PRIMARY KEY, motherid int REFERENCES schema1.parent)", ) - assert set(executor.foreignkeys()) >= set( - [("schema1", "parent", "parentid", "schema2", "child", "motherid")] - ) + assert set(executor.foreignkeys()) >= { + ("schema1", "parent", "parentid", "schema2", "child", "motherid") + } @dbtest @@ -175,30 +179,28 @@ def test_functions_query(executor): ) funcs = set(executor.functions()) - assert funcs >= set( - [ - function_meta_data(func_name="func1", return_type="integer"), - function_meta_data( - func_name="func3", - arg_names=["x", "y"], - arg_types=["integer", "integer"], - arg_modes=["t", "t"], - return_type="record", - is_set_returning=True, - ), - function_meta_data( - schema_name="public", - func_name="func4", - arg_names=("x",), - arg_types=("integer",), - return_type="integer", - is_set_returning=True, - ), - function_meta_data( - schema_name="schema1", func_name="func2", return_type="integer" - ), - ] - ) + assert funcs >= { + function_meta_data(func_name="func1", return_type="integer"), + function_meta_data( + func_name="func3", + arg_names=["x", "y"], + arg_types=["integer", "integer"], + arg_modes=["t", "t"], + return_type="record", + is_set_returning=True, + ), + function_meta_data( + schema_name="public", + func_name="func4", + arg_names=("x",), + arg_types=("integer",), + return_type="integer", + is_set_returning=True, + ), + function_meta_data( + schema_name="schema1", func_name="func2", return_type="integer" + ), + } @dbtest @@ -257,8 +259,8 @@ def test_not_is_special(executor, pgspecial): @dbtest def test_execute_from_file_no_arg(executor, pgspecial): - """\i without a filename returns an error.""" - result = list(executor.run("\i", pgspecial=pgspecial)) + r"""\i without a filename returns an error.""" + result = list(executor.run(r"\i", pgspecial=pgspecial)) status, sql, success, is_special = result[0][3:] assert "missing required argument" in status assert success == False @@ -268,12 +270,12 @@ def test_execute_from_file_no_arg(executor, pgspecial): @dbtest @patch("pgcli.main.os") def test_execute_from_file_io_error(os, executor, pgspecial): - """\i with an io_error returns an error.""" - # Inject an IOError. - os.path.expanduser.side_effect = IOError("test") + r"""\i with an os_error returns an error.""" + # Inject an OSError. + os.path.expanduser.side_effect = OSError("test") # Check the result. - result = list(executor.run("\i test", pgspecial=pgspecial)) + result = list(executor.run(r"\i test", pgspecial=pgspecial)) status, sql, success, is_special = result[0][3:] assert status == "test" assert success == False @@ -290,7 +292,7 @@ def test_multiple_queries_same_line(executor): @dbtest def test_multiple_queries_with_special_command_same_line(executor, pgspecial): - result = run(executor, "select 'foo'; \d", pgspecial=pgspecial) + result = run(executor, r"select 'foo'; \d", pgspecial=pgspecial) assert len(result) == 11 # 2 * (output+status) * 3 lines assert "foo" in result[3] # This is a lame check. :( @@ -408,7 +410,7 @@ def test_date_time_types(executor): @pytest.mark.parametrize("value", ["10000000", "10000000.0", "10000000000000"]) def test_large_numbers_render_directly(executor, value): run(executor, "create table numbertest(a numeric)") - run(executor, "insert into numbertest (a) values ({0})".format(value)) + run(executor, f"insert into numbertest (a) values ({value})") assert value in run(executor, "select * from numbertest", join=True) @@ -511,7 +513,7 @@ def test_short_host(executor): assert executor.short_host == "localhost1" -class BrokenConnection(object): +class BrokenConnection: """Mock a connection that failed.""" def cursor(self): diff --git a/tests/test_pgspecial.py b/tests/test_pgspecial.py index eaeaf12f..cd99e321 100644 --- a/tests/test_pgspecial.py +++ b/tests/test_pgspecial.py @@ -13,12 +13,12 @@ from pgcli.packages.sqlcompletion import ( def test_slash_suggests_special(): suggestions = suggest_type("\\", "\\") - assert set(suggestions) == set([Special()]) + assert set(suggestions) == {Special()} def test_slash_d_suggests_special(): suggestions = suggest_type("\\d", "\\d") - assert set(suggestions) == set([Special()]) + assert set(suggestions) == {Special()} def test_dn_suggests_schemata(): @@ -30,24 +30,24 @@ def test_dn_suggests_schemata(): def test_d_suggests_tables_views_and_schemas(): - suggestions = suggest_type("\d ", "\d ") - assert set(suggestions) == set([Schema(), Table(schema=None), View(schema=None)]) + suggestions = suggest_type(r"\d ", r"\d ") + assert set(suggestions) == {Schema(), Table(schema=None), View(schema=None)} - suggestions = suggest_type("\d xxx", "\d xxx") - assert set(suggestions) == set([Schema(), Table(schema=None), View(schema=None)]) + suggestions = suggest_type(r"\d xxx", r"\d xxx") + assert set(suggestions) == {Schema(), Table(schema=None), View(schema=None)} def test_d_dot_suggests_schema_qualified_tables_or_views(): - suggestions = suggest_type("\d myschema.", "\d myschema.") - assert set(suggestions) == set([Table(schema="myschema"), View(schema="myschema")]) + suggestions = suggest_type(r"\d myschema.", r"\d myschema.") + assert set(suggestions) == {Table(schema="myschema"), View(schema="myschema")} - suggestions = suggest_type("\d myschema.xxx", "\d myschema.xxx") - assert set(suggestions) == set([Table(schema="myschema"), View(schema="myschema")]) + suggestions = suggest_type(r"\d myschema.xxx", r"\d myschema.xxx") + assert set(suggestions) == {Table(schema="myschema"), View(schema="myschema")} def test_df_suggests_schema_or_function(): suggestions = suggest_type("\\df xxx", "\\df xxx") - assert set(suggestions) == set([Function(schema=None, usage="special"), Schema()]) + assert set(suggestions) == {Function(schema=None, usage="special"), Schema()} suggestions = suggest_type("\\df myschema.xxx", "\\df myschema.xxx") assert suggestions == (Function(schema="myschema", usage="special"),) @@ -63,7 +63,7 @@ def test_leading_whitespace_ok(): def test_dT_suggests_schema_or_datatypes(): text = "\\dT " suggestions = suggest_type(text, text) - assert set(suggestions) == set([Schema(), Datatype(schema=None)]) + assert set(suggestions) == {Schema(), Datatype(schema=None)} def test_schema_qualified_dT_suggests_datatypes(): diff --git a/tests/test_rowlimit.py b/tests/test_rowlimit.py index e76ea049..947fc80d 100644 --- a/tests/test_rowlimit.py +++ b/tests/test_rowlimit.py @@ -1,5 +1,5 @@ import pytest -from mock import Mock +from unittest.mock import Mock from pgcli.main import PGCli diff --git a/tests/test_smart_completion_multiple_schemata.py b/tests/test_smart_completion_multiple_schemata.py index 805b727c..74768d39 100644 --- a/tests/test_smart_completion_multiple_schemata.py +++ b/tests/test_smart_completion_multiple_schemata.py @@ -193,7 +193,7 @@ def test_suggested_joins(completer, query, tbl): result = get_result(completer, query.format(tbl)) assert completions_to_set(result) == completions_to_set( testdata.schemas_and_from_clause_items() - + [join("custom.shipments ON shipments.user_id = {0}.id".format(tbl))] + + [join(f"custom.shipments ON shipments.user_id = {tbl}.id")] ) diff --git a/tests/test_smart_completion_public_schema_only.py b/tests/test_smart_completion_public_schema_only.py index b9357092..db1fe0a3 100644 --- a/tests/test_smart_completion_public_schema_only.py +++ b/tests/test_smart_completion_public_schema_only.py @@ -53,7 +53,7 @@ metadata = { ], } -metadata = dict((k, {"public": v}) for k, v in metadata.items()) +metadata = {k: {"public": v} for k, v in metadata.items()} testdata = MetaData(metadata) @@ -296,7 +296,7 @@ def test_suggested_cased_always_qualified_column_names(completer): def test_suggested_column_names_in_function(completer): result = get_result(completer, "SELECT MAX( from users", len("SELECT MAX(")) assert completions_to_set(result) == completions_to_set( - (testdata.columns_functions_and_keywords("users")) + testdata.columns_functions_and_keywords("users") ) @@ -316,7 +316,7 @@ def test_suggested_column_names_with_alias(completer): def test_suggested_multiple_column_names(completer): result = get_result(completer, "SELECT id, from users u", len("SELECT id, ")) assert completions_to_set(result) == completions_to_set( - (testdata.columns_functions_and_keywords("users")) + testdata.columns_functions_and_keywords("users") ) diff --git a/tests/test_sqlcompletion.py b/tests/test_sqlcompletion.py index 3cbad0ad..744fadb0 100644 --- a/tests/test_sqlcompletion.py +++ b/tests/test_sqlcompletion.py @@ -23,16 +23,14 @@ def cols_etc( ): """Returns the expected select-clause suggestions for a single-table select.""" - return set( - [ - Column( - table_refs=(TableReference(schema, table, alias, is_function),), - qualifiable=True, - ), - Function(schema=parent), - Keyword(last_keyword), - |