Mocking open(file_name) in unit tests

前端 未结 8 1829
慢半拍i
慢半拍i 2020-12-05 00:37

I have a source code that opens a csv file and sets up a header to value association. The source code is given below:

def ParseCsvFile(source): 
  \"\"\"Pa         


        
8条回答
  •  生来不讨喜
    2020-12-05 00:57

    There are two ways that I like to do this, depending on the situation.

    If your unit test is going to call ParseCsvFile directly I would add a new kwarg to ParseCsvFile:

    def ParseCsvFile(source, open=open): 
        # ...
        rack_type_file = open(rack_file)  # Need to mock this line.
    

    Then your unit test can pass a different open_func in order to accomplish the mocking.

    If your unit test calls some other function that in turn calls ParseCsvFile then passing around open_func just for tests is ugly. In that case I would use the mock module. This lets you alter a function by name and replace it with a Mock object.

    # code.py
    def open_func(name):
        return open(name)
    
    def ParseCsvFile(source):
        # ...
        rack_type_file = open_func(rack_file)  # Need to mock this line.
    
    # test.py
    import unittest
    import mock
    from StringIO import StringIO
    
    @mock.patch('code.open_func')
    class ParseCsvTest(unittest.TestCase):
        def test_parse(self, open_mock):
            open_mock.return_value = StringIO("my,example,input")
            # ...
    

提交回复
热议问题