Change EnvironmentError, IOError to OSError - they are aliases

Since Python 3.3, these are aliases for OSError:
https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy
This commit is contained in:
Ran Benita 2020-03-27 18:40:23 +03:00
parent 83e18776f6
commit a785754523
15 changed files with 35 additions and 35 deletions

View File

@ -167,7 +167,7 @@ class TestRaises:
raises(TypeError, int, s) raises(TypeError, int, s)
def test_raises_doesnt(self): def test_raises_doesnt(self):
raises(IOError, int, "3") raises(OSError, int, "3")
def test_raise(self): def test_raise(self):
raise ValueError("demo error") raise ValueError("demo error")

View File

@ -406,7 +406,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
self = <failure_demo.TestRaises object at 0xdeadbeef> self = <failure_demo.TestRaises object at 0xdeadbeef>
def test_raises_doesnt(self): def test_raises_doesnt(self):
> raises(IOError, int, "3") > raises(OSError, int, "3")
E Failed: DID NOT RAISE <class 'OSError'> E Failed: DID NOT RAISE <class 'OSError'>
failure_demo.py:170: Failed failure_demo.py:170: Failed

View File

@ -268,7 +268,7 @@ to do this using the ``setenv`` and ``delenv`` method. Our example code to test:
def get_os_user_lower(): def get_os_user_lower():
"""Simple retrieval function. """Simple retrieval function.
Returns lowercase USER or raises EnvironmentError.""" Returns lowercase USER or raises OSError."""
username = os.getenv("USER") username = os.getenv("USER")
if username is None: if username is None:
@ -293,7 +293,7 @@ both paths can be safely tested without impacting the running environment:
def test_raise_exception(monkeypatch): def test_raise_exception(monkeypatch):
"""Remove the USER env var and assert EnvironmentError is raised.""" """Remove the USER env var and assert OSError is raised."""
monkeypatch.delenv("USER", raising=False) monkeypatch.delenv("USER", raising=False)
with pytest.raises(OSError): with pytest.raises(OSError):

View File

@ -307,7 +307,7 @@ def getfslineno(obj: Any) -> Tuple[Union[str, py.path.local], int]:
if fspath: if fspath:
try: try:
_, lineno = findsource(obj) _, lineno = findsource(obj)
except IOError: except OSError:
pass pass
return fspath, lineno return fspath, lineno
else: else:

View File

@ -284,7 +284,7 @@ if sys.platform == "win32":
try: try:
with atomic_write(fspath(pyc), mode="wb", overwrite=True) as fp: with atomic_write(fspath(pyc), mode="wb", overwrite=True) as fp:
_write_pyc_fp(fp, source_stat, co) _write_pyc_fp(fp, source_stat, co)
except EnvironmentError as e: except OSError as e:
state.trace("error writing pyc file at {}: {}".format(pyc, e)) state.trace("error writing pyc file at {}: {}".format(pyc, e))
# we ignore any failure to write the cache file # we ignore any failure to write the cache file
# there are many reasons, permission-denied, pycache dir being a # there are many reasons, permission-denied, pycache dir being a
@ -299,7 +299,7 @@ else:
proc_pyc = "{}.{}".format(pyc, os.getpid()) proc_pyc = "{}.{}".format(pyc, os.getpid())
try: try:
fp = open(proc_pyc, "wb") fp = open(proc_pyc, "wb")
except EnvironmentError as e: except OSError as e:
state.trace( state.trace(
"error writing pyc file at {}: errno={}".format(proc_pyc, e.errno) "error writing pyc file at {}: errno={}".format(proc_pyc, e.errno)
) )
@ -308,7 +308,7 @@ else:
try: try:
_write_pyc_fp(fp, source_stat, co) _write_pyc_fp(fp, source_stat, co)
os.rename(proc_pyc, fspath(pyc)) os.rename(proc_pyc, fspath(pyc))
except EnvironmentError as e: except OSError as e:
state.trace("error writing pyc file at {}: {}".format(pyc, e)) state.trace("error writing pyc file at {}: {}".format(pyc, e))
# we ignore any failure to write the cache file # we ignore any failure to write the cache file
# there are many reasons, permission-denied, pycache dir being a # there are many reasons, permission-denied, pycache dir being a
@ -338,7 +338,7 @@ def _read_pyc(source, pyc, trace=lambda x: None):
""" """
try: try:
fp = open(fspath(pyc), "rb") fp = open(fspath(pyc), "rb")
except IOError: except OSError:
return None return None
with fp: with fp:
try: try:
@ -346,8 +346,8 @@ def _read_pyc(source, pyc, trace=lambda x: None):
mtime = int(stat_result.st_mtime) mtime = int(stat_result.st_mtime)
size = stat_result.st_size size = stat_result.st_size
data = fp.read(12) data = fp.read(12)
except EnvironmentError as e: except OSError as e:
trace("_read_pyc({}): EnvironmentError {}".format(source, e)) trace("_read_pyc({}): OSError {}".format(source, e))
return None return None
# Check for invalid or out of date pyc file. # Check for invalid or out of date pyc file.
if ( if (

View File

@ -121,7 +121,7 @@ class Cache:
try: try:
with path.open("r") as f: with path.open("r") as f:
return json.load(f) return json.load(f)
except (ValueError, IOError, OSError): except (ValueError, OSError):
return default return default
def set(self, key, value): def set(self, key, value):
@ -140,7 +140,7 @@ class Cache:
else: else:
cache_dir_exists_already = self._cachedir.exists() cache_dir_exists_already = self._cachedir.exists()
path.parent.mkdir(exist_ok=True, parents=True) path.parent.mkdir(exist_ok=True, parents=True)
except (IOError, OSError): except OSError:
self.warn("could not create cache path {path}", path=path) self.warn("could not create cache path {path}", path=path)
return return
if not cache_dir_exists_already: if not cache_dir_exists_already:
@ -148,7 +148,7 @@ class Cache:
data = json.dumps(value, indent=2, sort_keys=True) data = json.dumps(value, indent=2, sort_keys=True)
try: try:
f = path.open("w") f = path.open("w")
except (IOError, OSError): except OSError:
self.warn("cache could not write path {path}", path=path) self.warn("cache could not write path {path}", path=path)
else: else:
with f: with f:

View File

@ -689,7 +689,7 @@ class DontReadFromInput:
encoding = None encoding = None
def read(self, *args): def read(self, *args):
raise IOError( raise OSError(
"pytest: reading from stdin while output is captured! Consider using `-s`." "pytest: reading from stdin while output is captured! Consider using `-s`."
) )

View File

@ -15,7 +15,7 @@ if TYPE_CHECKING:
from . import Config # noqa: F401 from . import Config # noqa: F401
def exists(path, ignore=EnvironmentError): def exists(path, ignore=OSError):
try: try:
return path.check() return path.check()
except ignore: except ignore:

View File

@ -715,7 +715,7 @@ class FixtureLookupError(LookupError):
fspath, lineno = getfslineno(function) fspath, lineno = getfslineno(function)
try: try:
lines, _ = inspect.getsourcelines(get_real_func(function)) lines, _ = inspect.getsourcelines(get_real_func(function))
except (IOError, IndexError, TypeError): except (OSError, IndexError, TypeError):
error_msg = "file %s, line %s: source code not available" error_msg = "file %s, line %s: source code not available"
addline(error_msg % (fspath, lineno + 1)) addline(error_msg % (fspath, lineno + 1))
else: else:

View File

@ -178,7 +178,7 @@ def make_numbered_dir(root: Path, prefix: str) -> Path:
_force_symlink(root, prefix + "current", new_path) _force_symlink(root, prefix + "current", new_path)
return new_path return new_path
else: else:
raise EnvironmentError( raise OSError(
"could not create numbered dir with prefix " "could not create numbered dir with prefix "
"{prefix} in {root} after 10 tries".format(prefix=prefix, root=root) "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
) )
@ -190,14 +190,14 @@ def create_cleanup_lock(p: Path) -> Path:
try: try:
fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except FileExistsError as e: except FileExistsError as e:
raise EnvironmentError("cannot create lockfile in {path}".format(path=p)) from e raise OSError("cannot create lockfile in {path}".format(path=p)) from e
else: else:
pid = os.getpid() pid = os.getpid()
spid = str(pid).encode() spid = str(pid).encode()
os.write(fd, spid) os.write(fd, spid)
os.close(fd) os.close(fd)
if not lock_path.is_file(): if not lock_path.is_file():
raise EnvironmentError("lock path got renamed after successful creation") raise OSError("lock path got renamed after successful creation")
return lock_path return lock_path
@ -212,7 +212,7 @@ def register_cleanup_lock_removal(lock_path: Path, register=atexit.register):
return return
try: try:
lock_path.unlink() lock_path.unlink()
except (OSError, IOError): except OSError:
pass pass
return register(cleanup_on_exit) return register(cleanup_on_exit)
@ -228,7 +228,7 @@ def maybe_delete_a_numbered_dir(path: Path) -> None:
garbage = parent.joinpath("garbage-{}".format(uuid.uuid4())) garbage = parent.joinpath("garbage-{}".format(uuid.uuid4()))
path.rename(garbage) path.rename(garbage)
rm_rf(garbage) rm_rf(garbage)
except (OSError, EnvironmentError): except OSError:
# known races: # known races:
# * other process did a cleanup at the same time # * other process did a cleanup at the same time
# * deletable folder was found # * deletable folder was found
@ -240,7 +240,7 @@ def maybe_delete_a_numbered_dir(path: Path) -> None:
if lock_path is not None: if lock_path is not None:
try: try:
lock_path.unlink() lock_path.unlink()
except (OSError, IOError): except OSError:
pass pass

View File

@ -463,7 +463,7 @@ class TestGeneralUsage:
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
def raise_error(obj): def raise_error(obj):
raise IOError('source code not available') raise OSError('source code not available')
import inspect import inspect
inspect.getsourcelines = raise_error inspect.getsourcelines = raise_error

View File

@ -20,7 +20,7 @@ def equal_with_bash(prefix, ffc, fc, out=None):
# copied from argcomplete.completers as import from there # copied from argcomplete.completers as import from there
# also pulls in argcomplete.__init__ which opens filedescriptor 9 # also pulls in argcomplete.__init__ which opens filedescriptor 9
# this gives an IOError at the end of testrun # this gives an OSError at the end of testrun
def _wrapcall(*args, **kargs): def _wrapcall(*args, **kargs):

View File

@ -971,7 +971,7 @@ class TestAssertionRewriteHookDetails:
@contextmanager @contextmanager
def atomic_write_failed(fn, mode="r", overwrite=False): def atomic_write_failed(fn, mode="r", overwrite=False):
e = IOError() e = OSError()
e.errno = 10 e.errno = 10
raise e raise e
yield yield
@ -981,10 +981,10 @@ class TestAssertionRewriteHookDetails:
) )
else: else:
def raise_ioerror(*args): def raise_oserror(*args):
raise IOError() raise OSError()
monkeypatch.setattr("os.rename", raise_ioerror) monkeypatch.setattr("os.rename", raise_oserror)
assert not _write_pyc(state, [1], os.stat(source_path), pycpath) assert not _write_pyc(state, [1], os.stat(source_path), pycpath)

View File

@ -829,10 +829,10 @@ def test_dontreadfrominput():
f = DontReadFromInput() f = DontReadFromInput()
assert f.buffer is f assert f.buffer is f
assert not f.isatty() assert not f.isatty()
pytest.raises(IOError, f.read) pytest.raises(OSError, f.read)
pytest.raises(IOError, f.readlines) pytest.raises(OSError, f.readlines)
iter_f = iter(f) iter_f = iter(f)
pytest.raises(IOError, next, iter_f) pytest.raises(OSError, next, iter_f)
pytest.raises(UnsupportedOperation, f.fileno) pytest.raises(UnsupportedOperation, f.fileno)
f.close() # just for completeness f.close() # just for completeness
@ -1083,7 +1083,7 @@ class TestStdCapture:
print("XXX which indicates an error in the underlying capturing") print("XXX which indicates an error in the underlying capturing")
print("XXX mechanisms") print("XXX mechanisms")
with self.getcapture(): with self.getcapture():
pytest.raises(IOError, sys.stdin.read) pytest.raises(OSError, sys.stdin.read)
class TestTeeStdCapture(TestStdCapture): class TestTeeStdCapture(TestStdCapture):
@ -1356,7 +1356,7 @@ def test_crash_on_closing_tmpfile_py27(testdir):
result = testdir.runpytest_subprocess(str(p)) result = testdir.runpytest_subprocess(str(p))
assert result.ret == 0 assert result.ret == 0
assert result.stderr.str() == "" assert result.stderr.str() == ""
result.stdout.no_fnmatch_line("*IOError*") result.stdout.no_fnmatch_line("*OSError*")
def test_global_capture_with_live_logging(testdir): def test_global_capture_with_live_logging(testdir):

View File

@ -264,7 +264,7 @@ class TestNumberedDir:
from _pytest.pathlib import create_cleanup_lock from _pytest.pathlib import create_cleanup_lock
lockfile = create_cleanup_lock(d) lockfile = create_cleanup_lock(d)
with pytest.raises(EnvironmentError, match="cannot create lockfile in .*"): with pytest.raises(OSError, match="cannot create lockfile in .*"):
create_cleanup_lock(d) create_cleanup_lock(d)
lockfile.unlink() lockfile.unlink()