Python unit test that uses an external data file

前端 未结 4 1371
执念已碎
执念已碎 2021-02-06 22:29

I have a Python project that I\'m working on in Eclipse and I have the following file structure:

/Project
    /projectname
        module1.py
        module2.py          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 23:10

    Unit test that access the file system are generally not a good idea. This is because the test should be self contained, by making your test data external to the test it's no longer immediately obvious which test the csv file belongs to or even if it's still in use.

    A preferable solution is to patch open and make it return a file-like object.

    from unittest import TestCase
    from unittest.mock import patch, mock_open
    
    from textwrap import dedent
    
    class OpenTest(TestCase):
        DATA = dedent("""
            a,b,c
            x,y,z
            """).strip()
    
        @patch("builtins.open", mock_open(read_data=DATA))
        def test_open(self):
    
            # Due to how the patching is done, any module accessing `open' for the 
            # duration of this test get access to a mock instead (not just the test 
            # module).
            with open("filename", "r") as f:
                result = f.read()
    
            open.assert_called_once_with("filename", "r")
            self.assertEqual(self.DATA, result)
            self.assertEqual("a,b,c\nx,y,z", result)
    

提交回复
热议问题