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)
def test_raises_doesnt(self):
raises(IOError, int, "3")
raises(OSError, int, "3")
def test_raise(self):
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>
def test_raises_doesnt(self):
> raises(IOError, int, "3")
> raises(OSError, int, "3")
E Failed: DID NOT RAISE <class 'OSError'>
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():
"""Simple retrieval function.
Returns lowercase USER or raises EnvironmentError."""
Returns lowercase USER or raises OSError."""
username = os.getenv("USER")
if username is None:
@ -293,7 +293,7 @@ both paths can be safely tested without impacting the running environment:
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)
with pytest.raises(OSError):

View File

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

View File

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

View File

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

View File

@ -689,7 +689,7 @@ class DontReadFromInput:
encoding = None
def read(self, *args):
raise IOError(
raise OSError(
"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
def exists(path, ignore=EnvironmentError):
def exists(path, ignore=OSError):
try:
return path.check()
except ignore:

View File

@ -715,7 +715,7 @@ class FixtureLookupError(LookupError):
fspath, lineno = getfslineno(function)
try:
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"
addline(error_msg % (fspath, lineno + 1))
else:

View File

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

View File

@ -463,7 +463,7 @@ class TestGeneralUsage:
p = testdir.makepyfile(
"""
def raise_error(obj):
raise IOError('source code not available')
raise OSError('source code not available')
import inspect
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
# 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):

View File

@ -971,7 +971,7 @@ class TestAssertionRewriteHookDetails:
@contextmanager
def atomic_write_failed(fn, mode="r", overwrite=False):
e = IOError()
e = OSError()
e.errno = 10
raise e
yield
@ -981,10 +981,10 @@ class TestAssertionRewriteHookDetails:
)
else:
def raise_ioerror(*args):
raise IOError()
def raise_oserror(*args):
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)

View File

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

View File

@ -264,7 +264,7 @@ class TestNumberedDir:
from _pytest.pathlib import create_cleanup_lock
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)
lockfile.unlink()