44import sys
55
66from io import StringIO
7- from typing import Any , Callable
7+ from typing import cast
88from unittest .mock import Mock , mock_open , patch
99
1010from 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