Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python mock_open的mock open函数_Python_Django_Python 2.7_Unit Testing_Mocking - Fatal编程技术网

Python mock_open的mock open函数

Python mock_open的mock open函数,python,django,python-2.7,unit-testing,mocking,Python,Django,Python 2.7,Unit Testing,Mocking,因此,我想测试Django应用程序业务逻辑中的函数: def parse_sectors_from_csv(): sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')) sectors_csv_reader = csv.DictReader(sectors_csv) return [ { 'model': 'se

因此,我想测试Django应用程序业务逻辑中的函数:

def parse_sectors_from_csv():
    sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
    sectors_csv_reader = csv.DictReader(sectors_csv)
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(sectors_csv_reader, 1)
    ]
我已经测试了它是否存在文件和是否存在标题行

现在我想嘲笑你

open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
在我的test.py中,我写道

with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
        sectors = service.parse_sectors_from_csv()
        print('Sectors:', sectors)
        self.assertEqual(expected_sectors, sectors)
但据我所知,它在打印
扇区时会将空文件传递给函数:[]

我读了好几遍mock_open dock,但还是搞不懂

>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h: # what's happening here?
...         result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'

模拟的第一条规则:不要在定义对象/方法的地方模拟它们,而要在使用它们的地方模拟它们。因此,没有
\uuuuuuu内置\uuuuuu.open
而是
我的应用程序.我的文件.open

第二,我不知道什么是
mock\u open
,但你可以用普通的模拟方式来做:

with mock.patch('my_app.my_file.open') as mocked_open:
    mocked_open.return_value = StringIO('foo')
不管怎样,这都是有效的

p.S.


在处理文件时始终使用和模拟的第一条规则:不要在定义对象/方法的地方模拟它们,在使用它们的地方模拟它们。因此,没有
\uuuuuuu内置\uuuuuu.open
而是
我的应用程序.我的文件.open

第二,我不知道什么是
mock\u open
,但你可以用普通的模拟方式来做:

with mock.patch('my_app.my_file.open') as mocked_open:
    mocked_open.return_value = StringIO('foo')
不管怎样,这都是有效的

p.S.


在处理文件时总是使用
一起使用

每当我觉得需要模仿时,我首先会问自己是否 按照以下思路重构代码是可行的:

  • 在算法上非常重要的东西,我可能想进行单元测试 用实际的断言

  • 这些东西非常简单,以至于我(a)几乎不需要测试它,或者(b)可以 使用仅执行代码的单个端到端测试进行充分测试 不作任何断言

  • 例如:

    ####
    # Hardly worth testing.
    ####
    
    def parse_sectors_from_csv():
        file_path = sectors_file_path()
        with open(file_path) as fh:
            return do_parse_sectors_from_csv(fh)
    
    ####
    # Easily tested without mocks.
    ####
    
    def do_parse_sectors_from_csv(fh):
        reader = csv.DictReader(fh)
        return do_parse_sectors_from_csv(reader)
    
    def sectors_file_path():
        return os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')
    
    def parse_sectors_from_csv(rows):
        return [
            {
                'model': 'sector.sector',
                'id': index,
                'fields': {
                    'name': row.get('Sector'),
                    'slug': slugify(row['Sector']),
                    'type_id': row.get('Type_Id')
                }
            }
            for index, row in enumerate(rows, 1)
        ]
    

    每当我觉得有必要嘲笑的时候,我首先会问自己这是否 按照以下思路重构代码是可行的:

  • 在算法上非常重要的东西,我可能想进行单元测试 用实际的断言

  • 这些东西非常简单,以至于我(a)几乎不需要测试它,或者(b)可以 使用仅执行代码的单个端到端测试进行充分测试 不作任何断言

  • 例如:

    ####
    # Hardly worth testing.
    ####
    
    def parse_sectors_from_csv():
        file_path = sectors_file_path()
        with open(file_path) as fh:
            return do_parse_sectors_from_csv(fh)
    
    ####
    # Easily tested without mocks.
    ####
    
    def do_parse_sectors_from_csv(fh):
        reader = csv.DictReader(fh)
        return do_parse_sectors_from_csv(reader)
    
    def sectors_file_path():
        return os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')
    
    def parse_sectors_from_csv(rows):
        return [
            {
                'model': 'sector.sector',
                'id': index,
                'fields': {
                    'name': row.get('Sector'),
                    'slug': slugify(row['Sector']),
                    'type_id': row.get('Type_Id')
                }
            }
            for index, row in enumerate(rows, 1)
        ]
    

    谢谢成功了,谢谢!成功了,谢谢你的回答!谢谢你的回答!