Advertisement
Guest User

#1ZnxLgIt

a guest
Jan 19th, 2023
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. import unittest
  2. from unittest import mock
  3. import sys
  4.  
  5.  
  6. def main():
  7.     with open("path/to/file1", "rb") as f1:
  8.         print(f1.read())
  9.  
  10.     with open("path/to/file2", "rb") as f2:
  11.         print(f2.read())
  12.  
  13.     sys.exit(0)
  14.  
  15.  
  16. class MyUnitTest(unittest.TestCase):
  17.     def test_main(self):
  18.         read_data_map = {
  19.             "path/to/file1": "read from f1",
  20.             "path/to/file2": "read from f2",
  21.         }
  22.         mocker = mock.MagicMock(name="open", spec=open)
  23.  
  24.         mocker.side_effect = lambda *arg: mock.mock_open(
  25.             read_data=read_data_map.get(arg[0])
  26.         )()
  27.         with self.assertRaises(SystemExit) as cm, mock.patch(
  28.             "builtins.open", mocker
  29.         ) as mock_files:
  30.             main()
  31.  
  32.         self.assertListEqual(
  33.             mock_files.call_args_list,
  34.             [mock.call("path/to/file1", "rb"), mock.call("path/to/file2", "rb")],
  35.         ),
  36.  
  37.  
  38. if __name__ == "__main__":
  39.     unittest.main()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement