1# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). 2# Licensed under the Apache License, Version 2.0 (see LICENSE). 3 4import errno 5import os 6from contextlib import contextmanager 7 8import pytest 9 10from pex.common import rename_if_empty 11 12try: 13 from unittest import mock 14except ImportError: 15 import mock 16 17 18@contextmanager 19def maybe_raises(exception=None): 20 @contextmanager 21 def noop(): 22 yield 23 24 with (noop() if exception is None else pytest.raises(exception)): 25 yield 26 27 28def rename_if_empty_test(errno, expect_raises=None): 29 with mock.patch('os.rename', spec_set=True, autospec=True) as mock_rename: 30 mock_rename.side_effect = OSError(errno, os.strerror(errno)) 31 with maybe_raises(expect_raises): 32 rename_if_empty('from.dir', 'to.dir') 33 34 35def test_rename_if_empty_eexist(): 36 rename_if_empty_test(errno.EEXIST) 37 38 39def test_rename_if_empty_enotempty(): 40 rename_if_empty_test(errno.ENOTEMPTY) 41 42 43def test_rename_if_empty_eperm(): 44 rename_if_empty_test(errno.EPERM, expect_raises=OSError) 45