diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 73f482297..004b284d3 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -7,6 +7,6 @@ Fixes #(issue) # Checklist (delete if not relevant): - [ ] I have added tests that prove my fix is effective or that my feature works -- [ ] I have updated CHANGELOG.md +- [ ] I have added a changelog fragment to `changelog.d/` (see `changelog.d/README.md`) - [ ] I have made corresponding changes to user documentation for new features - [ ] I have made corresponding changes to library documentation for API changes diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bb036f7f..8238aa4bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,3 @@ -# **Upcoming release** - -- #223 Add regression tests for restructuring and patchedast with `elif(` written without a space (@mcepl) - - # Release 1.16.0 - #859 Fix `find_definition`/Rename not resolving `async def` methods called via `self` (@gadievron) diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..74b3841f4 --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +# Maintenance tasks for rope. +# +# Changelog entries live as individual fragments in changelog.d/ +# (one file per PR, see changelog.d/README.md) and are only merged +# into CHANGELOG.md at release time, so that pull requests do not +# keep conflicting on the top of CHANGELOG.md. The real work is done +# by bin/news; this Makefile is kept portable (GNU make, BSD make). + +NEWS = ./bin/news + +.PHONY: help news changelog-preview changelog docs release + +help: + @echo "make news N= write a changelog fragment in \$$EDITOR" + @echo " (or bin/news )" + @echo "make changelog-preview show the pending changelog entries" + @echo "make changelog fold fragments into CHANGELOG.md" + @echo "make docs build the HTML documentation" + @echo "make release changelog + docs" + +news: + @$(NEWS) add "$$N" "$$TEXT" + +changelog-preview: + @$(NEWS) preview + +changelog: + @$(NEWS) collect + +docs: + cd docs && $(MAKE) html + +release: changelog docs diff --git a/bin/news b/bin/news new file mode 100755 index 000000000..217762c08 --- /dev/null +++ b/bin/news @@ -0,0 +1,132 @@ +#!/bin/sh +# Manage changelog fragments in changelog.d/ (see changelog.d/README.md). +# +# bin/news [add] [text] create changelog.d/.md, +# in $VISUAL/$EDITOR unless text given +# bin/news preview show the pending release section +# bin/news collect fold the fragments into CHANGELOG.md +# +# Deliberately plain POSIX sh, so it works the same on Linux, the BSDs +# and macOS. + +set -eu + +cd "$(dirname "$0")/.." +NEWS_DIR=changelog.d +CHANGELOG=CHANGELOG.md + +die() { + printf '%s\n' "$*" >&2 + exit 1 +} + +usage() { + sed -n '4,7s/^# \{0,1\}//p' "$0" >&2 + exit 2 +} + +version() { + v=$(sed -n "s/^version *= *['\"]\([^'\"]*\)['\"].*/\1/p" pyproject.toml) + [ -n "$v" ] || die "Cannot find version in pyproject.toml" + printf '%s\n' "$v" +} + +# Fragment file names, sorted by issue number. +fragments() { + for f in "$NEWS_DIR"/[0-9]*.md; do + [ -e "$f" ] && basename "$f" + done | sort -n | sed "s|^|$NEWS_DIR/|" +} + +template() { + cat <"$tmp" + else + template "$n" >"$tmp" + # unquoted on purpose: allow e.g. EDITOR='code --wait' + ${VISUAL:-${EDITOR:-vi}} "$tmp" + fi + + # drop comments and leading (and, via $(), trailing) blank lines + entry=$(grep -v -E '^#( |$)' "$tmp" | sed -e '/./,$!d') + rest=$(printf '%s' "$entry" | sed -e "s/^- #$n//" | tr -d '[:space:]') + [ -n "$rest" ] || die "Empty entry, nothing written." + + printf '%s\n' "$entry" >"$f" + printf 'Created %s:\n' "$f" + cat "$f" +} + +cmd_preview() { + files=$(fragments) + [ -n "$files" ] || die "No fragments in $NEWS_DIR/" + printf '# Release %s\n\n' "$(version)" + # shellcheck disable=SC2086 # file names are digits and dashes only + cat $files +} + +cmd_collect() { + v=$(version) + files=$(fragments) + [ -n "$files" ] || die "No fragments in $NEWS_DIR/" + ! grep -q -x -F "# Release $v" "$CHANGELOG" || + die "$CHANGELOG already has 'Release $v';" \ + "bump version in pyproject.toml first" + + tmp=$(mktemp "${TMPDIR:-/tmp}/changelog.XXXXXX") + trap 'rm -f "$tmp"' EXIT + { + cmd_preview + echo + cat "$CHANGELOG" + } >"$tmp" + cat "$tmp" >"$CHANGELOG" + # shellcheck disable=SC2086 + rm -f $files + git add -A "$NEWS_DIR" "$CHANGELOG" + echo "$CHANGELOG updated for $v; review and commit." +} + +[ $# -ge 1 ] || usage +case $1 in + add) shift; cmd_add "$@" ;; + preview) cmd_preview ;; + collect) cmd_collect ;; + -h | --help | help) usage ;; + [0-9]*) cmd_add "$@" ;; + *) usage ;; +esac diff --git a/changelog.d/223.md b/changelog.d/223.md new file mode 100644 index 000000000..0d98c1bac --- /dev/null +++ b/changelog.d/223.md @@ -0,0 +1 @@ +- #223 Add regression tests for restructuring and patchedast with `elif(` written without a space (@mcepl) diff --git a/changelog.d/886.md b/changelog.d/886.md new file mode 100644 index 000000000..47e257672 --- /dev/null +++ b/changelog.d/886.md @@ -0,0 +1 @@ +#886 Track and close SQLite connections created in worker threads in AutoImport (@mcepl) diff --git a/changelog.d/985.md b/changelog.d/985.md new file mode 100644 index 000000000..3453ea80f --- /dev/null +++ b/changelog.d/985.md @@ -0,0 +1 @@ +- #985 create new system for combining CHANGELOG.md from individual snippets for each PR (@mcepl) diff --git a/changelog.d/README.md b/changelog.d/README.md new file mode 100644 index 000000000..c958a198b --- /dev/null +++ b/changelog.d/README.md @@ -0,0 +1,51 @@ +# Changelog fragments + +Instead of editing `CHANGELOG.md` directly (which makes nearly +every pull request conflict with every other one), each pull +request adds a small file to this directory. The fragments are +merged into `CHANGELOG.md` by `make changelog` (part of +`make release`) when a new version is released. + +## How to add an entry + +Create a file named after the issue or pull request number, e.g. +`changelog.d/1234.md`. If you need more than one fragment for the +same number, add a suffix: `1234-docs.md`. The file name **must** +start with a digit and end in `.md`; other files (like this one) +are ignored. + +The easiest way is to run + +```sh +bin/news 1234 # or: make news N=1234 +``` + +which opens `$VISUAL`/`$EDITOR` (falling back to `vi`) with a +template and saves the result as `changelog.d/1234.md`. Leaving +the entry empty aborts without creating anything. + +The content is one or more Markdown list items, in the same style +as the existing `CHANGELOG.md`. Please don't limit yourself to a +terse one-liner: explain what changed, why, and what users of +rope may notice. Wrap long lines and indent continuation lines by +two spaces: + +```markdown +- #1234 Fix renaming of keyword arguments when inlining a method + whose body conflicts with names in the host scope; previously + rope produced `__0__from_lang=` in the result. (@yourname) +``` + +Several related issues may be listed together, e.g. +`- #826, #940 Keep star imports …`. + +For scripts, `bin/news 1234 'Short description (@you)'` (or +`make news N=1234 TEXT='...'`) writes the fragment without +starting an editor. + +Use `bin/news preview` (or `make changelog-preview`) to see what +the next release section will look like. + +`bin/news` is a plain POSIX shell script and the `Makefile` is +portable, so this works with both GNU and BSD make, on Linux, the +BSDs and macOS. diff --git a/docs/Makefile b/docs/Makefile index d4bb2cbb9..b44be6e48 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -12,7 +12,12 @@ BUILDDIR = _build help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -.PHONY: help Makefile +.PHONY: help html Makefile + +# Explicit rule, so that `make html` (used by the top-level +# Makefile) works with BSD make too, which lacks pattern rules. +html: + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). diff --git a/docs/contributing.rst b/docs/contributing.rst index 796699986..ead26066c 100644 --- a/docs/contributing.rst +++ b/docs/contributing.rst @@ -112,6 +112,21 @@ Follow the instructions on GitHub_ on how to setup Git and fork the `python-rope/rope`_ repository. Once your changes are ready, send a `pull request`_ for review. +Please do not edit ``CHANGELOG.md`` directly. Instead, add a small +changelog fragment named after the issue or pull request number to the +``changelog.d/`` directory. Running ``bin/news 1234`` (or +``make news N=1234``) opens your ``$EDITOR`` with a template and +creates ``changelog.d/1234.md``, e.g.:: + + - #1234 Fix renaming of keyword arguments when inlining a method + whose body conflicts with names in the host scope. (@yourname) + +Longer entries explaining what changed and why are welcome. + +The fragments are collected into ``CHANGELOG.md`` at release time, which +avoids merge conflicts between pull requests. See +``changelog.d/README.md`` for details. + Programming Style ----------------- diff --git a/docs/library.rst b/docs/library.rst index 6a62c3e00..c8f512283 100644 --- a/docs/library.rst +++ b/docs/library.rst @@ -853,7 +853,22 @@ by passing memory=False to AutoImport constructor. This default will change in the future, if you want to always store the autoimport cache in-memory, then you need to explicitly pass memory=True. -It must be closed when done with the ``AutoImport.close()`` method. +It must be closed when done with the ``AutoImport.close()`` method. Each +thread uses its own SQLite connection; do not pass connections between threads. +When sharing an instance, stop and join worker threads before calling +``close()``. It raises ``RopeError`` rather than closing a connection owned by +another live thread. Alternatively, workers can release their connections with +``close_thread_connection()`` before shutdown. Connections left by finished +workers are closed when another thread creates a connection or when ``close()`` +runs. +If committing or closing a connection fails, ``close()`` attempts to close +all remaining connections before raising the first SQLite error. + +Assigning to ``AutoImport.connection`` replaces the current thread's +connection without closing the old one. The caller must close the old +connection; ``AutoImport`` only tracks and closes the replacement. If the +assignment is rejected, the supplied connection remains the caller's +responsibility. AutoImport can search for a name from both modules and statements you can import from them. diff --git a/docs/release-process.rst b/docs/release-process.rst index 87c356864..46da53eed 100644 --- a/docs/release-process.rst +++ b/docs/release-process.rst @@ -11,10 +11,12 @@ Release ------- 1. Ensure tickets assigned to Milestones are up to date -2. Update ``CHANGELOG.md`` -3. Close milestone -4. Increment version number in ``pyproject.toml`` -5. `git commit && git push` +2. Close milestone +3. Increment version number in ``pyproject.toml`` +4. Run ``make release``: it folds the fragments from ``changelog.d/`` + into ``CHANGELOG.md`` (``git rm``-ing the fragments) and builds the + documentation; ``make changelog-preview`` shows the result in advance +5. Review ``CHANGELOG.md``, then ``git commit -a && git push`` 6. Tag the release with the tag annotation containing the release information, ``python bin/tag-release.py`` 7. Create Github Release diff --git a/rope/contrib/autoimport/sqlite.py b/rope/contrib/autoimport/sqlite.py index 7ae8fb718..df286d5e1 100644 --- a/rope/contrib/autoimport/sqlite.py +++ b/rope/contrib/autoimport/sqlite.py @@ -15,9 +15,10 @@ from hashlib import sha256 from itertools import chain from pathlib import Path -from threading import local +from threading import Lock, Thread, current_thread, local from typing import ( TYPE_CHECKING, + Dict, Generator, Iterable, Iterator, @@ -93,6 +94,9 @@ class AutoImport: This class maintains a cache of global names in python modules. Note that this cache is not accurate and might be out of date. + Each thread uses its own SQLite connection. Stop and join worker threads, + or have them call ``close_thread_connection()``, before calling ``close()``. + """ memory: bool @@ -142,6 +146,10 @@ def __init__( "`AutoImport(memory=True)` explicitly.", DeprecationWarning, ) + self._closed = False + self._connections: Dict[Thread, sqlite3.Connection] = {} + self._connections_lock = Lock() + self._observer: Optional[resourceobserver.ResourceObserver] = None self.thread_local = local() self.connection = self.create_database_connection( project=project, @@ -149,10 +157,10 @@ def __init__( ) self._setup_db() if observe: - observer = resourceobserver.ResourceObserver( + self._observer = resourceobserver.ResourceObserver( changed=self._changed, moved=self._moved, removed=self._removed ) - project.add_observer(observer) + project.add_observer(self._observer) @classmethod def create_database_connection( @@ -186,28 +194,93 @@ def calculate_project_hash(data: str) -> str: else: project_hash = calculate_project_hash(project.ropefolder.real_path) return sqlite3.connect( - f"file:rope-{project_hash}:?mode=memory&cache=shared", uri=True + f"file:rope-{project_hash}:?mode=memory&cache=shared", + uri=True, + # Allow cleanup from another thread after the owner has exited. + check_same_thread=False, ) else: - return sqlite3.connect(project.ropefolder.pathlib / "autoimport.db") + return sqlite3.connect( + project.ropefolder.pathlib / "autoimport.db", + check_same_thread=False, + ) + + @staticmethod + def _commit_and_close(conn: sqlite3.Connection) -> None: + try: + conn.commit() + except sqlite3.Error: + with contextlib.suppress(sqlite3.Error): + conn.close() + raise + else: + conn.close() + + @classmethod + def _close_connections(cls, connections: Iterable[sqlite3.Connection]) -> None: + first_error: Optional[sqlite3.Error] = None + for conn in connections: + try: + cls._commit_and_close(conn) + except sqlite3.Error as error: + if first_error is None: + first_error = error + if first_error is not None: + raise first_error + + def _close_finished_thread_connections(self) -> None: + """Close finished threads' connections while holding the registry lock.""" + connections = [] + for thread, conn in list(self._connections.items()): + if not thread.is_alive(): + del self._connections[thread] + connections.append(conn) + self._close_connections(connections) + + def _register_connection(self, conn: sqlite3.Connection) -> None: + thread = current_thread() + with self._connections_lock: + if self._closed: + with contextlib.suppress(sqlite3.Error): + conn.close() + raise exceptions.RopeError("AutoImport instance has been closed") + try: + self._close_finished_thread_connections() + except sqlite3.Error: + with contextlib.suppress(sqlite3.Error): + conn.close() + raise + self._connections[thread] = conn @property def connection(self) -> sqlite3.Connection: """ Creates a new connection if called from a new thread. - This makes sure AutoImport can be shared across threads. + This makes sure AutoImport can be shared across threads. Use the returned + connection only in the calling thread. """ + if self._closed: + raise exceptions.RopeError("AutoImport instance has been closed") if not hasattr(self.thread_local, "connection"): - self.thread_local.connection = self.create_database_connection( + conn = self.create_database_connection( project=self.project, memory=self.memory, ) + self._register_connection(conn) + self.thread_local.connection = conn return self.thread_local.connection @connection.setter def connection(self, value: sqlite3.Connection): - self.thread_local.connection = value + """Replace this thread's connection; the caller must close the old one.""" + thread = current_thread() + with self._connections_lock: + if self._closed: + raise exceptions.RopeError("AutoImport instance has been closed") + self._close_finished_thread_connections() + self._connections[thread] = value + self.thread_local.connection = value def _setup_db(self): models.Metadata.create_table(self.connection) @@ -457,10 +530,54 @@ def update_module(self, module: str): self._del_if_exist(module) self.generate_modules_cache([module]) + def close_thread_connection(self): + """Close the SQLite connection owned by the current thread.""" + conn = getattr(self.thread_local, "connection", None) + if conn is not None: + thread = current_thread() + with self._connections_lock: + if self._connections.get(thread) is conn: + del self._connections[thread] + with contextlib.suppress(AttributeError): + del self.thread_local.connection + self._commit_and_close(conn) + def close(self): - """Close the autoimport database.""" - self.connection.commit() - self.connection.close() + """Close the database after all worker threads have stopped. + + Raises ``RopeError`` if another live thread still owns a connection. + SQLite errors are raised after attempting to close every connection. + """ + thread = current_thread() + with self._connections_lock: + if self._closed: + return + active_threads = [ + owner + for owner in self._connections + if owner is not thread and owner.is_alive() + ] + if active_threads: + raise exceptions.RopeError( + "Cannot close AutoImport while other threads own connections; " + "wait for them to finish first" + ) + self._closed = True + connections = list(self._connections.values()) + self._connections.clear() + + if self._observer is not None: + with contextlib.suppress(Exception): + self.project.remove_observer(self._observer) + self._observer = None + + self._close_connections(connections) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() def get_name_locations(self, name): """Return a list of ``(resource, lineno)`` tuples.""" diff --git a/ropetest/contrib/autoimport/autoimporttest.py b/ropetest/contrib/autoimport/autoimporttest.py index 072ab1ed8..406e798fd 100644 --- a/ropetest/contrib/autoimport/autoimporttest.py +++ b/ropetest/contrib/autoimport/autoimporttest.py @@ -2,10 +2,12 @@ from concurrent.futures import ThreadPoolExecutor from contextlib import closing, contextmanager from textwrap import dedent +from threading import Barrier, Event from unittest.mock import ANY, patch import pytest +from rope.base import exceptions from rope.base.project import Project from rope.base.resources import File, Folder from rope.contrib.autoimport import models @@ -46,16 +48,16 @@ def test_autoimport_connection_parameter_with_in_memory( project: Project, autoimport: AutoImport, ): - connection = AutoImport.create_database_connection(memory=True) - assert is_in_memory_database(connection) + with closing(AutoImport.create_database_connection(memory=True)) as connection: + assert is_in_memory_database(connection) def test_autoimport_connection_parameter_with_project( project: Project, autoimport: AutoImport, ): - connection = AutoImport.create_database_connection(project=project) - assert not is_in_memory_database(connection) + with closing(AutoImport.create_database_connection(project=project)) as connection: + assert not is_in_memory_database(connection) def test_autoimport_create_database_connection_conflicting_parameter( @@ -102,25 +104,351 @@ def foo(): def test_multithreading( - autoimport: AutoImport, project: Project, pkg1: Folder, mod1: File, ): mod1_init = pkg1.get_child("__init__.py") - mod1_init.write(dedent("""\ + mod1_init.write( + dedent("""\ def foo(): pass - """)) - mod1.write(dedent("""\ + """) + ) + mod1.write( + dedent("""\ foo - """)) - autoimport = AutoImport(project, memory=False) - autoimport.generate_cache([mod1_init]) + """) + ) + with closing(AutoImport(project, memory=False)) as autoimport: + autoimport.generate_cache([mod1_init]) + + with ThreadPoolExecutor(1) as tp: + results = tp.submit(autoimport.search, "foo", True).result() + assert [("from pkg1 import foo", "foo")] == results + + +def test_multithread_connections_closed_on_close(project: Project): + with AutoImport(project, memory=True) as ai: + main_conn = ai.connection + worker_conns = [] + ready = Barrier(4, timeout=5) + + def worker(): + conn = ai.connection + worker_conns.append(conn) + ready.wait() + return list(ai.search("foo")) + + with ThreadPoolExecutor(3) as tp: + futures = [tp.submit(worker) for _ in range(3)] + ready.wait() + for f in futures: + f.result(timeout=5) + + all_conns = {main_conn} | set(worker_conns) + assert len(all_conns) == 4 + assert all_conns.issubset(ai._connections.values()) + + assert ai._closed + assert len(ai._connections) == 0 + for conn in all_conns: + with pytest.raises(sqlite3.ProgrammingError, match="Cannot operate on a closed database"): + conn.execute("SELECT 1") + + with pytest.raises(exceptions.RopeError, match="AutoImport instance has been closed"): + _ = ai.connection + + +@pytest.mark.parametrize("memory", [True, False]) +def test_finished_thread_connections_are_reaped(project: Project, memory: bool): + ai = AutoImport(project, memory=memory) + worker_connections = [] + + for _ in range(3): + with ThreadPoolExecutor(1) as executor: + worker_connections.append(executor.submit(lambda: ai.connection).result()) + assert len(ai._connections) <= 2 + + for conn in worker_connections[:-1]: + with pytest.raises( + sqlite3.ProgrammingError, match="Cannot operate on a closed database" + ): + conn.execute("SELECT 1") + + ai.close() + for conn in worker_connections: + with pytest.raises( + sqlite3.ProgrammingError, match="Cannot operate on a closed database" + ): + conn.execute("SELECT 1") + + +@pytest.mark.parametrize("memory", [True, False]) +def test_close_rejects_live_worker_connections(project: Project, memory: bool): + with AutoImport(project, memory=memory) as ai: + started = Event() + finish = Event() + + def worker(): + conn = ai.connection + started.set() + assert finish.wait(timeout=5) + return conn.execute("SELECT 1").fetchone() + + with ThreadPoolExecutor(1) as executor: + future = executor.submit(worker) + try: + assert started.wait(timeout=5) + connections = dict(ai._connections) + observer = ai._observer + with pytest.raises(exceptions.RopeError, match="wait for them to finish"): + ai.close() + assert not ai._closed + assert ai._connections == connections + assert ai._observer is observer + assert ai.connection.execute("SELECT 1").fetchone() == (1,) + finally: + finish.set() + assert future.result(timeout=5) == (1,) + + assert ai._closed + + +@pytest.mark.parametrize("memory", [True, False]) +def test_close_allows_live_worker_after_releasing_connection( + project: Project, memory: bool +): + released = Event() + finish = Event() + with AutoImport(project, memory=memory) as ai: + def worker(): + conn = ai.connection + ai.close_thread_connection() + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + conn.execute("SELECT 1") + released.set() + assert finish.wait(timeout=5) + with pytest.raises(exceptions.RopeError, match="instance has been closed"): + _ = ai.connection + + with ThreadPoolExecutor(1) as executor: + future = executor.submit(worker) + try: + assert released.wait(timeout=5) + assert not future.done() + ai.close() + assert ai._closed + assert not ai._connections + finally: + finish.set() + future.result(timeout=5) + + +def test_close_thread_connection(project: Project): + with AutoImport(project, memory=True) as ai: + worker_conn = None + + def worker(): + nonlocal worker_conn + worker_conn = ai.connection + assert worker_conn in ai._connections.values() + ai.close_thread_connection() + assert worker_conn not in ai._connections.values() + with pytest.raises(sqlite3.ProgrammingError, match="Cannot operate on a closed database"): + worker_conn.execute("SELECT 1") + new_conn = ai.connection + assert new_conn is not worker_conn + assert new_conn in ai._connections.values() + + with ThreadPoolExecutor(1) as tp: + tp.submit(worker).result() + + +def test_close_idempotent(project: Project): + ai = AutoImport(project, memory=True) + conn = ai.connection + ai.close() + assert ai._closed + ai.close() + with pytest.raises(sqlite3.ProgrammingError, match="Cannot operate on a closed database"): + conn.execute("SELECT 1") + + +@pytest.mark.parametrize( + "fail_commit, fail_close", [(True, False), (False, True), (True, True)] +) +def test_close_reports_errors_after_closing_all_connections( + project: Project, fail_commit: bool, fail_close: bool +): + commit_error = sqlite3.OperationalError("commit failed") + close_error = sqlite3.OperationalError("close failed") + + class FailingConnection(sqlite3.Connection): + def commit(self): + if fail_commit: + raise commit_error + super().commit() + + def close(self): + super().close() + if fail_close: + raise close_error + + with AutoImport(project, memory=True) as ai: + with closing(ai.connection): + conn = sqlite3.connect(":memory:", factory=FailingConnection) + ai.connection = conn + with ThreadPoolExecutor(1) as executor: + worker_conn = executor.submit(lambda: ai.connection).result(timeout=5) + + with pytest.raises(sqlite3.OperationalError) as raised: + ai.close() + assert raised.value is (commit_error if fail_commit else close_error) + assert ai._closed + assert not ai._connections + assert ai._observer is None + for connection in (conn, worker_conn): + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + connection.execute("SELECT 1") + ai.close() + + +def test_registration_closes_new_connection_when_reaping_fails(project: Project): + error = sqlite3.OperationalError("commit failed") + + class FailingConnection(sqlite3.Connection): + def commit(self): + raise error + + with AutoImport(project, memory=True) as ai: + failing_conn = sqlite3.connect( + ":memory:", factory=FailingConnection, check_same_thread=False + ) + ready = Barrier(3, timeout=5) + + def worker(connection=None): + if connection is not None: + ai.connection = connection + conn = ai.connection + ready.wait() + return conn + + with ThreadPoolExecutor(2) as executor: + failing_future = executor.submit(worker, failing_conn) + other_future = executor.submit(worker) + ready.wait() + assert failing_future.result(timeout=5) is failing_conn + other_conn = other_future.result(timeout=5) + + created = [] + create_connection = ai.create_database_connection + + def create(**kwargs): + conn = create_connection(**kwargs) + created.append(conn) + return conn + + with patch.object(ai, "create_database_connection", side_effect=create): + with ThreadPoolExecutor(1) as executor: + future = executor.submit(lambda: ai.connection) + with pytest.raises(sqlite3.OperationalError) as raised: + future.result(timeout=5) + assert raised.value is error + assert len(created) == 1 + for conn in [failing_conn, other_conn, *created]: + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + conn.execute("SELECT 1") + assert list(ai._connections.values()) == [ai.connection] + assert ai.connection.execute("SELECT 1").fetchone() == (1,) + + +@pytest.mark.parametrize("registration_wins", [True, False]) +def test_connection_registration_races_with_close( + project: Project, registration_wins: bool +): + paused = Event() + resume = Event() + created = [] + + with AutoImport(project, memory=True) as ai: + register_connection = ai._register_connection + + def register(conn): + created.append(conn) + if registration_wins: + register_connection(conn) + paused.set() + assert resume.wait(timeout=5) + if not registration_wins: + register_connection(conn) + + def worker(): + return ai.connection.execute("SELECT 1").fetchone() + + with patch.object(ai, "_register_connection", side_effect=register): + with ThreadPoolExecutor(1) as executor: + future = executor.submit(worker) + try: + assert paused.wait(timeout=5) + if registration_wins: + with pytest.raises( + exceptions.RopeError, match="wait for them to finish" + ): + ai.close() + assert not ai._closed + assert created[0] in ai._connections.values() + else: + ai.close() + assert ai._closed + assert not ai._connections + finally: + resume.set() + if registration_wins: + assert future.result(timeout=5) == (1,) + else: + with pytest.raises( + exceptions.RopeError, match="AutoImport instance has been closed" + ): + future.result(timeout=5) + assert len(created) == 1 + + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + created[0].execute("SELECT 1") + + +def test_register_connection_after_close(project: Project): + ai = AutoImport(project, memory=True) + ai.close() + conn = AutoImport.create_database_connection(memory=True) + with pytest.raises(exceptions.RopeError, match="AutoImport instance has been closed"): + ai._register_connection(conn) + assert conn not in ai._connections.values() + with pytest.raises(sqlite3.ProgrammingError, match="Cannot operate on a closed database"): + conn.execute("SELECT 1") - tp = ThreadPoolExecutor(1) - results = tp.submit(autoimport.search, "foo", True).result() - assert [("from pkg1 import foo", "foo")] == results + +def test_connection_setter_after_close(project: Project): + ai = AutoImport(project, memory=True) + ai.close() + with closing(AutoImport.create_database_connection(memory=True)) as conn: + with pytest.raises(exceptions.RopeError, match="AutoImport instance has been closed"): + ai.connection = conn + assert conn.execute("SELECT 1").fetchone() == (1,) + + +def test_connection_setter_replaces_existing(project: Project): + with AutoImport(project, memory=True) as ai: + with closing(ai.connection) as old_conn: + assert old_conn in ai._connections.values() + conn = AutoImport.create_database_connection(memory=True) + ai.connection = conn + assert ai.connection is conn + assert conn in ai._connections.values() + assert old_conn not in ai._connections.values() + assert old_conn.execute("SELECT 1").fetchone() == (1,) + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + conn.execute("SELECT 1") def test_connection(project: Project, project2: Project): diff --git a/ropetest/contrib/autoimport/modeltest.py b/ropetest/contrib/autoimport/modeltest.py index 0044434cc..8eef06d35 100644 --- a/ropetest/contrib/autoimport/modeltest.py +++ b/ropetest/contrib/autoimport/modeltest.py @@ -8,7 +8,9 @@ @pytest.fixture def empty_db(): - return sqlite3.connect(":memory:") + conn = sqlite3.connect(":memory:") + yield conn + conn.close() class TestQuery: diff --git a/ropetest/contrib/autoimporttest.py b/ropetest/contrib/autoimporttest.py index d42ec14f7..ebf21af56 100644 --- a/ropetest/contrib/autoimporttest.py +++ b/ropetest/contrib/autoimporttest.py @@ -15,6 +15,7 @@ def setUp(self): self.importer = autoimport.AutoImport(self.project, observe=False) def tearDown(self): + self.importer.close() testutils.remove_project(self.project) super().tearDown() @@ -178,12 +179,12 @@ def test_skipping_directories_not_accessible_because_of_permission_error(self): def test_search_submodule(project, external_fixturepkg): - importer = autoimport.AutoImport(project, observe=False) - importer.update_module("external_fixturepkg") - import_statement = ("from external_fixturepkg import mod1", "mod1") - assert import_statement in importer.search("mod1", exact_match=True) - assert import_statement in importer.search("mo") - assert import_statement in importer.search("mod1") + with autoimport.AutoImport(project, observe=False) as importer: + importer.update_module("external_fixturepkg") + import_statement = ("from external_fixturepkg import mod1", "mod1") + assert import_statement in importer.search("mod1", exact_match=True) + assert import_statement in importer.search("mo") + assert import_statement in importer.search("mod1") class AutoImportObservingTest(unittest.TestCase): @@ -196,6 +197,7 @@ def setUp(self): self.importer = autoimport.AutoImport(self.project, observe=True) def tearDown(self): + self.importer.close() testutils.remove_project(self.project) super().tearDown()