Skip to content

Commit 25b526a

Browse files
committed
test: refactor fdopen mock into callable class
To placate type checkers and because it is more readable and pythonic. Signed-off-by: Kevin Locke <[email protected]>
1 parent 8911cb6 commit 25b526a

File tree

1 file changed

+15
-23
lines changed

1 file changed

+15
-23
lines changed

tests/test_argcomplete.py

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,35 @@
44
import sys
55

66
from io import StringIO
7-
from typing import Any, Callable
7+
from typing import cast
88
from unittest.mock import Mock, mock_open, patch
99

1010
from packagename import cli
1111

1212

13-
def _make_fdopen_mock() -> Callable[..., Any]:
14-
"""
15-
Create a function which returns a Mock only for a given file.
13+
class ArgcompleteFdopenMock: # pylint: disable=too-few-public-methods
14+
"""A callable object for mocking os.fdopen for argcomplete."""
1615

17-
:param for_file: file for which a Mock should be returned.
16+
def __init__(self) -> None:
17+
self.completion_file: Mock = mock_open().return_value
18+
self.error_file: Mock = mock_open().return_value
1819

19-
:return: side_effect function which returns a Mock when called with
20-
for_file and delegates to open() otherwise.
21-
"""
22-
23-
def maybe_mock_fdopen(fd: int, mode: str) -> Any:
20+
def __call__(self, fd: int, mode: str) -> Mock:
2421
r"""
25-
Open a file or create a Mock for the file.
22+
Open a mock file descriptor.
2623
2724
:param fd: file descriptor to open
2825
:param mode: mode in which the file descriptor is opened
2926
30-
:return: a Mock if file is 8 or 9 and mode is "w".
27+
:return: a file Mock.
3128
"""
32-
assert fd in (8, 9)
33-
assert mode == 'w'
34-
3529
if fd == 8:
36-
return maybe_mock_fdopen.completion_file
30+
return self.completion_file
3731

38-
return maybe_mock_fdopen.error_file
32+
if fd == 9:
33+
return self.error_file
3934

40-
# Save created Mocks so the caller can test them
41-
maybe_mock_fdopen.completion_file = mock_open().return_value
42-
maybe_mock_fdopen.error_file = mock_open().return_value
43-
return maybe_mock_fdopen
35+
return cast(Mock, mock_open().return_value)
4436

4537

4638
@patch.dict(
@@ -52,7 +44,7 @@ def maybe_mock_fdopen(fd: int, mode: str) -> Any:
5244
'COMP_TYPE': '33',
5345
},
5446
)
55-
@patch('os.fdopen', side_effect=_make_fdopen_mock())
47+
@patch('os.fdopen', side_effect=ArgcompleteFdopenMock())
5648
@patch('sys.argv', ['packagename'])
5749
@patch('sys.stdout', new_callable=StringIO)
5850
@patch('sys.stderr', new_callable=StringIO)
@@ -96,7 +88,7 @@ def test_argcomplete_dash_options(
9688
'COMP_TYPE': '33',
9789
},
9890
)
99-
@patch('os.fdopen', side_effect=_make_fdopen_mock())
91+
@patch('os.fdopen', side_effect=ArgcompleteFdopenMock())
10092
@patch('sys.argv', ['packagename'])
10193
@patch('sys.stdout', new_callable=StringIO)
10294
@patch('sys.stderr', new_callable=StringIO)

0 commit comments

Comments
 (0)