Skip to content

gh-136523: fix wave.Wave_write emitting an unraisable when open raises #136529

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 13, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Lib/test/support/os_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ def make_bad_fd():
unlink(TESTFN)


@contextlib.contextmanager
def unwritable_filepath():
"""
Create a filepath that is not writable by the current user.
"""
import tempfile
fd, path = tempfile.mkstemp()
original_permissions = stat.S_IMODE(os.lstat(path).st_mode)
os.close(fd)

try:
os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
yield path
finally:
try:
os.chmod(path, original_permissions)
os.remove(path)
except OSError as e:
pass

_can_symlink = None


Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_wave.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest
from test import audiotests
from test import support
from test.support.os_helper import unwritable_filepath, skip_unless_working_chmod
import io
import struct
import sys
Expand Down Expand Up @@ -196,6 +197,22 @@ def test_read_wrong_sample_width(self):
with self.assertRaisesRegex(wave.Error, 'bad sample width'):
wave.open(io.BytesIO(b))

@skip_unless_working_chmod
def test_write_to_protected_file(self):
# gh-136523: Wave_write.__del__ should not throw
stderr = io.StringIO()
sys.stderr = stderr
try:
try:
with unwritable_filepath() as path:
with wave.open(path, "wb"):
pass
except PermissionError:
pass
self.assertEqual(stderr.getvalue(), "")
finally:
sys.stderr = sys.__stderr__


if __name__ == '__main__':
unittest.main()
12 changes: 6 additions & 6 deletions Lib/wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,15 +429,15 @@ class Wave_write:

def __init__(self, f):
self._i_opened_the_file = None
if isinstance(f, str):
f = builtins.open(f, 'wb')
self._i_opened_the_file = f
try:
self.initfp(f)
if isinstance(f, str):
f = builtins.open(f, 'wb')
self._i_opened_the_file = f
except:
if self._i_opened_the_file:
f.close()
f = None
raise
finally:
self.initfp(f)

def initfp(self, file):
self._file = file
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix ``wave.Wave_write.__del__`` raising :exc:`AttributeError` when attempting to open an unwritable file.
Loading