diff --git a/tests/pyathena/filesystem/test_init.py b/tests/pyathena/filesystem/test_init.py index cdff2e2ea..67a7b2a51 100644 --- a/tests/pyathena/filesystem/test_init.py +++ b/tests/pyathena/filesystem/test_init.py @@ -19,6 +19,18 @@ class _DummyFileSystem: pass +def _warnings(caplog): + """Return the captured records of level ``WARNING`` or higher. + + Args: + caplog: The pytest caplog fixture. + + Returns: + The records, of any logger. + """ + return [record for record in caplog.records if record.levelno >= logging.WARNING] + + @pytest.fixture def registry_state(): registry = dict(_registry) @@ -41,15 +53,19 @@ def test_register_s3_filesystem(registry_state): def test_register_s3_filesystem_overwrites_existing_registration(registry_state, caplog): fsspec.register_implementation("s3", _DummyFileSystem, clobber=True) + # Only the s3 registration is replaced. + fsspec.register_implementation("s3a", S3FileSystem, clobber=True) with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"): register_s3_filesystem() # An explicitly registered filesystem class is overwritten with a warning. assert fsspec.registry["s3"] is S3FileSystem - assert "will be overwritten" in caplog.text + assert [(r.name, r.levelno) for r in _warnings(caplog)] == [ + ("pyathena.filesystem", logging.WARNING) + ] # Re-registering PyAthena's own filesystem does not warn. caplog.clear() with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"): register_s3_filesystem() - assert not caplog.text + assert not _warnings(caplog) diff --git a/tests/pyathena/filesystem/test_reader.py b/tests/pyathena/filesystem/test_reader.py index 90ee74fa6..977bcb8e9 100644 --- a/tests/pyathena/filesystem/test_reader.py +++ b/tests/pyathena/filesystem/test_reader.py @@ -28,12 +28,18 @@ def __init__(self, data, short=False, error_at=None, gate=None): self.gated_read_started = threading.Event() self.reads = [] self.closes = 0 + # The offsets of the reads in the order they ended, and "close" when closed. + self.events = [] + # Set when the file is closed, and by signal_close_wait() when close() + # starts to wait for the reads. + self.close_progressed = threading.Event() def read_range(self, offset, size): self.reads.append((offset, size)) if self._gate is not None and offset > 0: self.gated_read_started.set() assert self._gate.wait(EVENT_TIMEOUT) + self.events.append(offset) if offset == self._error_at: raise OSError("read failed") return self._data[offset : offset + size - (1 if self._short else 0)] @@ -43,7 +49,59 @@ def closed(self): return self.closes > 0 def close(self): + self.events.append("close") self.closes += 1 + self.close_progressed.set() + + def assert_closed_after_reads(self, stream): + """Check that closing the stream while the gated reads block closes the file last. + + The stream is closed in a thread, and the reads are released once the + close waits for them (see :meth:`signal_close_wait`) or, if it does not + wait, has closed the file, which then precedes their end. + + Args: + stream: The stream over the file. + """ + errors = [] + + def close(): + try: + stream.close() + except BaseException as e: + errors.append(e) + + closer = threading.Thread(target=close, daemon=True) + closer.start() + assert self.close_progressed.wait(EVENT_TIMEOUT), ( + "close() neither waited for the reads nor closed the file" + ) + self._gate.set() + closer.join(EVENT_TIMEOUT) + assert not closer.is_alive() + assert not errors + # Every read that started ended before the file was closed. + assert self.events[-1] == "close" + assert len(self.events) == len(self.reads) + 1 + + def signal_close_wait(self, monkeypatch, interrupts=0): + """Set ``close_progressed`` when ``ReadAheadStream.close()`` starts to wait for the reads. + + Args: + monkeypatch: The pytest monkeypatch fixture. + interrupts: The number of first waits that raise ``KeyboardInterrupt``. + """ + remaining = interrupts + + def signalling_wait(futures, *args, **kwargs): + nonlocal remaining + if remaining: + remaining -= 1 + raise KeyboardInterrupt + self.close_progressed.set() + return wait(futures, *args, **kwargs) + + monkeypatch.setattr("pyathena.filesystem.reader.wait", signalling_wait) def open_stream(self, **kwargs): """Open a stream over the file that closes it.""" @@ -79,6 +137,18 @@ def _new_future(self): return _InterruptedFuture() +@pytest.fixture +def gate(): + """An event that blocks the gated reads of a ``_RecordingRangeFile`` until set. + + It is set at teardown, so that a test that fails before releasing the reads + does not leave them blocked. + """ + gate = threading.Event() + yield gate + gate.set() + + class TestReadAheadStream: """Tests for reading a file sequentially with parallel range reads.""" @@ -178,96 +248,47 @@ def test_interrupted_wait(self, monkeypatch): assert sorted(file.reads) == [(0, 10), (10, 10), (20, 10)] stream.close() - def test_interrupted_close(self, monkeypatch): + def test_interrupted_close(self, monkeypatch, gate): """An interrupted close leaves the file open, and closing again waits for the running reads before closing the file.""" - gate = threading.Event() file = _RecordingRangeFile(bytes(100), gate=gate) stream = file.open_stream(part_size=10, max_parts=2) - interrupts = [KeyboardInterrupt()] - - def interrupted_wait(futures, *args, **kwargs): - if interrupts: - raise interrupts.pop() - return wait(futures, *args, **kwargs) - - monkeypatch.setattr("pyathena.filesystem.reader.wait", interrupted_wait) - closer = threading.Thread(target=stream.close, daemon=True) - try: - assert stream.read(10) == bytes(10) - assert file.gated_read_started.wait(EVENT_TIMEOUT) - with pytest.raises(KeyboardInterrupt): - stream.close() - assert not file.closed - assert not stream.closed - # The stream reads nothing more once closing started. - with pytest.raises(ValueError, match="I/O operation on closed file"): - stream.read(10) - closer.start() - closer.join(0.2) - # A read of a later part is still blocked, so the retried close has not - # closed the file. - assert closer.is_alive() - assert not file.closed - finally: - gate.set() - if closer.is_alive(): - closer.join(EVENT_TIMEOUT) - assert file.closed + file.signal_close_wait(monkeypatch, interrupts=1) + assert stream.read(10) == bytes(10) + assert file.gated_read_started.wait(EVENT_TIMEOUT) + with pytest.raises(KeyboardInterrupt): + stream.close() + assert not file.closed + assert not stream.closed + # The stream reads nothing more once closing started. + with pytest.raises(ValueError, match="I/O operation on closed file"): + stream.read(10) + file.assert_closed_after_reads(stream) assert stream.closed - def test_close_with_queued_reads(self, monkeypatch): + def test_close_with_queued_reads(self, monkeypatch, gate): """Closing cancels a part that no worker has started and does not wait for it.""" - shut_down = threading.Event() - - class Executor(ThreadPoolExecutor): - def shutdown(self, wait=True, *, cancel_futures=False): - super().shutdown(wait=wait, cancel_futures=cancel_futures) - shut_down.set() - monkeypatch.setattr( "pyathena.filesystem.reader.ThreadPoolExecutor", - lambda max_workers: Executor(max_workers=1), + lambda max_workers: ThreadPoolExecutor(max_workers=1), ) - gate = threading.Event() file = _RecordingRangeFile(bytes(100), gate=gate) stream = file.open_stream(part_size=10, max_parts=2) - closer = threading.Thread(target=stream.close, daemon=True) - try: - # The one worker blocks in the read of the second part, and the third waits. - assert stream.read(10) == bytes(10) - assert file.gated_read_started.wait(EVENT_TIMEOUT) - closer.start() - # The queued third part is cancelled, and close() waits for the second. - assert shut_down.wait(EVENT_TIMEOUT) - closer.join(0.2) - assert closer.is_alive() - finally: - gate.set() - closer.join(EVENT_TIMEOUT) - assert not closer.is_alive() - assert file.closed + file.signal_close_wait(monkeypatch) + # The one worker blocks in the read of the second part, and the third waits. + assert stream.read(10) == bytes(10) + assert file.gated_read_started.wait(EVENT_TIMEOUT) + file.assert_closed_after_reads(stream) assert (20, 10) not in file.reads - def test_close_waits_for_running_reads(self): + def test_close_waits_for_running_reads(self, monkeypatch, gate): """Closing waits for the reads in flight before closing the file.""" - gate = threading.Event() file = _RecordingRangeFile(bytes(100), gate=gate) stream = file.open_stream(part_size=10, max_parts=2) - closer = threading.Thread(target=stream.close) - try: - assert stream.read(10) == bytes(10) - assert file.gated_read_started.wait(EVENT_TIMEOUT) - closer.start() - closer.join(0.2) - # A read of a later part is still blocked, so close() has not returned. - assert closer.is_alive() - assert not file.closed - finally: - gate.set() - if closer.is_alive(): - closer.join(EVENT_TIMEOUT) - assert file.closed + file.signal_close_wait(monkeypatch) + assert stream.read(10) == bytes(10) + assert file.gated_read_started.wait(EVENT_TIMEOUT) + file.assert_closed_after_reads(stream) def test_csv(self): """pyarrow reads a CSV through the stream with its own block size.""" diff --git a/tests/pyathena/filesystem/test_s3_core.py b/tests/pyathena/filesystem/test_s3_core.py index 7bae3f9e6..43aee70c3 100644 --- a/tests/pyathena/filesystem/test_s3_core.py +++ b/tests/pyathena/filesystem/test_s3_core.py @@ -1166,15 +1166,15 @@ def test_abort_multipart_upload_in_stopped_scope(self): assert operation.calls == 2 @pytest.mark.parametrize( - ("method", "args", "missing", "message"), + ("method", "args", "missing"), [ - ("upload_part", (1, b"data"), "Bucket", "no bucket"), - ("upload_part", (1, b"data"), "Key", "no key"), - ("upload_part", (1, b"data"), "UploadId", "no upload ID"), + ("upload_part", (1, b"data"), "Bucket"), + ("upload_part", (1, b"data"), "Key"), + ("upload_part", (1, b"data"), "UploadId"), # The other operations check the same identity. - ("upload_part_copy", (1, S3Path("source", "key")), "UploadId", "no upload ID"), - ("complete_multipart_upload", ([],), "Key", "no key"), - ("abort_multipart_upload", (), "Bucket", "no bucket"), + ("upload_part_copy", (1, S3Path("source", "key")), "UploadId"), + ("complete_multipart_upload", ([],), "Key"), + ("abort_multipart_upload", (), "Bucket"), ], ids=[ "upload_part-Bucket", @@ -1185,12 +1185,14 @@ def test_abort_multipart_upload_in_stopped_scope(self): "abort_multipart_upload-Bucket", ], ) - def test_multipart_upload_requires_identity(self, method, args, missing, message): - core, _ = _make_core() + def test_multipart_upload_requires_identity(self, method, args, missing): + core, stubber = _make_core() response = {"Bucket": "bucket", "Key": "key", "UploadId": "u"} del response[missing] - with pytest.raises(ValueError, match=message): - getattr(core, method)(S3MultipartUpload(response), *args) + upload = S3MultipartUpload(response) + # Rejected before a request: the stub has no response to send. + with stubber, pytest.raises(ValueError): # noqa: PT011 + getattr(core, method)(upload, *args) def test_upload_part_uses_creation_algorithm_and_identity(self): core, stubber = _make_core() @@ -1759,28 +1761,20 @@ def test_put_bucket_acl(self): ) def test_acl_validation(self, method, args): core, stubber = _make_core() - with stubber, pytest.raises(ValueError, match="ACL not in"): + with stubber, pytest.raises(ValueError): # noqa: PT011 getattr(core, method)(*args) @pytest.mark.parametrize( - ("method", "args", "match"), + ("method", "args"), [ - ("head_object", (S3Path("bucket"),), "has no key"), - ("delete_object", (S3Path("bucket"),), "has no key"), - ("put_object", (S3Path("bucket"), b"data"), "has no key"), + ("head_object", (S3Path("bucket"),)), + ("delete_object", (S3Path("bucket"),)), + ("put_object", (S3Path("bucket"), b"data")), # A write replaces the object at the key, not the named version. - ("put_object", (S3Path("bucket", "key", "v1"), b"data"), "Cannot write to a version"), - ( - "put_object", - (S3Path("bucket", "key", "null"), b"data"), - "Cannot write to a version", - ), - ("create_multipart_upload", (S3Path("bucket"),), "has no key"), - ( - "create_multipart_upload", - (S3Path("bucket", "key", "v1"),), - "Cannot write to a version", - ), + ("put_object", (S3Path("bucket", "key", "v1"), b"data")), + ("put_object", (S3Path("bucket", "key", "null"), b"data")), + ("create_multipart_upload", (S3Path("bucket"),)), + ("create_multipart_upload", (S3Path("bucket", "key", "v1"),)), ( "upload_part_copy", ( @@ -1788,31 +1782,34 @@ def test_acl_validation(self, method, args): 1, S3Path("bucket"), ), - "has no key", - ), - ("get_object_tagging", (S3Path("bucket"),), "has no key"), - ("put_object_tagging", (S3Path("bucket"), {}), "has no key"), - ("put_object_acl", (S3Path("bucket"), "private"), "has no key"), - ( - "replace_object_metadata", - (S3Path("bucket"), S3Metadata({}), {}), - "has no key", - ), - ( - "replace_object_metadata", - (S3Path("bucket", "key", "v1"), S3Metadata({}), {}), - "Cannot write to a version", - ), - ( - "replace_object_metadata", - (S3Path("bucket", "key", "null"), S3Metadata({}), {}), - "Cannot write to a version", ), + ("get_object_tagging", (S3Path("bucket"),)), + ("put_object_tagging", (S3Path("bucket"), {})), + ("put_object_acl", (S3Path("bucket"), "private")), + ("replace_object_metadata", (S3Path("bucket"), S3Metadata({}), {})), + ("replace_object_metadata", (S3Path("bucket", "key", "v1"), S3Metadata({}), {})), + ("replace_object_metadata", (S3Path("bucket", "key", "null"), S3Metadata({}), {})), + ], + ids=[ + "head_object-args0-has no key", + "delete_object-args1-has no key", + "put_object-args2-has no key", + "put_object-args3-Cannot write to a version", + "put_object-args4-Cannot write to a version", + "create_multipart_upload-args5-has no key", + "create_multipart_upload-args6-Cannot write to a version", + "upload_part_copy-args7-has no key", + "get_object_tagging-args8-has no key", + "put_object_tagging-args9-has no key", + "put_object_acl-args10-has no key", + "replace_object_metadata-args11-has no key", + "replace_object_metadata-args12-Cannot write to a version", + "replace_object_metadata-args13-Cannot write to a version", ], ) - def test_object_operations_reject_paths(self, method, args, match): + def test_object_operations_reject_paths(self, method, args): core, stubber = _make_core() - with stubber, pytest.raises(ValueError, match=match): + with stubber, pytest.raises(ValueError): # noqa: PT011 getattr(core, method)(*args) def test_replace_object_metadata(self): @@ -1970,8 +1967,9 @@ def test_from_paths(self): assert batches[2].objects == (S3Path("b2", "a", "v1"),) assert S3DeleteBatch.from_paths([]) == [] # A path without a key is rejected, also among other paths. - with pytest.raises(ValueError, match="Not an object of the bucket b1: s3://b1"): - S3DeleteBatch.from_paths([S3Path("b1", "a"), S3Path("b1")]) + mixed = [S3Path("b1", "a"), S3Path("b1")] + with pytest.raises(ValueError): # noqa: PT011 + S3DeleteBatch.from_paths(mixed) @pytest.mark.parametrize( ("objects", "match"), diff --git a/tests/pyathena/filesystem/test_s3_executor.py b/tests/pyathena/filesystem/test_s3_executor.py index 558d84961..9b6a24876 100644 --- a/tests/pyathena/filesystem/test_s3_executor.py +++ b/tests/pyathena/filesystem/test_s3_executor.py @@ -320,6 +320,18 @@ def test_shutdown(self): assert events == ["pending finished"] + @pytest.mark.parametrize("released", [False, True], ids=["unused", "released"]) + def test_shutdown_without_threads(self, released): + # A pool that has no threads, never used or released, rejects calls after + # its shutdown instead of creating threads. + pool = S3ThreadPool(1) + if released: + assert pool.submit(sum, [1, 2]).result(timeout=EVENT_TIMEOUT) == 3 + pool.release() + pool.shutdown() + with pytest.raises(RuntimeError): + pool.submit(sum, [1, 2]) + def test_release_after_calls(self): # GH-1209: release() keeps the threads, and the max_workers bound, # until no call runs or waits, and then ends them. @@ -1025,19 +1037,6 @@ def work(): assert future.result(EVENT_TIMEOUT) == "submitter" assert operation.calls == 1 - def test_submit_to(self): - # The callable's outcome resolves the future of the caller. - with S3ThreadPool(max_workers=1) as executor: - succeeded: Future[int] = Future() - failed: Future[int] = Future() - executor.submit_to(succeeded, sum, [1, 2]) - executor.submit_to(failed, int, "x") - wait([succeeded, failed], timeout=5) - - assert succeeded.result() == 3 - with pytest.raises(ValueError, match="invalid literal"): - failed.result() - def test_submit_to_failure_frees_arguments(self): # GH-1186: the arguments of a failed callable, such as the body of a # part, are freed when it fails, while the error keeps the frames of