Can't catch mocked exception because it doesn't inherit BaseException

后端 未结 6 1644
无人共我
无人共我 2020-12-09 02:35

I\'m working on a project that involves connecting to a remote server, waiting for a response, and then performing actions based on that response. We catch a couple of diff

6条回答
  •  北海茫月
    2020-12-09 03:04

    I faced a similar issue while trying to mock the sh package. While sh is very useful, the fact that all methods and exceptions are defined dynamically make it more difficult to mock them. So following the recommendation of the documentation:

    import unittest
    from unittest.mock import Mock, patch
    
    
    class MockSh(Mock):
        # error codes are defined dynamically in sh
        class ErrorReturnCode_32(BaseException):
            pass
    
        # could be any sh command    
        def mount(self, *args):
            raise self.ErrorReturnCode_32
    
    
    class MyTestCase(unittest.TestCase):
        mock_sh = MockSh()
    
        @patch('core.mount.sh', new=mock_sh)
        def test_mount(self):
            ...
    

提交回复
热议问题