Coverage for src/gitlabracadabra/tests/patchfuncs.py: 100%

1#

2# Copyright (C) 2019-2022 Mathieu Parent <math.parent@gmail.com>

3#

4# This program is free software: you can redistribute it and/or modify

5# it under the terms of the GNU Lesser General Public License as published by

6# the Free Software Foundation, either version 3 of the License, or

7# (at your option) any later version.

8#

9# This program is distributed in the hope that it will be useful,

10# but WITHOUT ANY WARRANTY; without even the implied warranty of

11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

12# GNU Lesser General Public License for more details.

13#

14# You should have received a copy of the GNU Lesser General Public License

15# along with this program. If not, see <http://www.gnu.org/licenses/>.

16

17 from contextlib import contextmanager

18 from io import StringIO

19 from unittest.mock import patch

20

21

22# Inspired by https://mapleoin.github.io/perma/mocking-python-file-open

23@contextmanager

24 def patch_open(contents_map):

25 def mock_open(*args, **kwargs): # noqa: ARG001

26 if args[0] in contents_map:

27 f = StringIO(contents_map[args[0]])

28 f.name = args[0]

29 else:

30 mocked_open.stop()

31 try:

32 f = open(*args) # noqa: SIM115

33 finally:

34 mocked_open.start()

35 return f

36

37 mocked_open = patch("builtins.open", mock_open)

38 mocked_open.start()

39 yield

40 mocked_open.stop()