Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.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-模拟操作系统错误异常_Python_Unit Testing_Exception_Mocking - Fatal编程技术网

Python-模拟操作系统错误异常

Python-模拟操作系统错误异常,python,unit-testing,exception,mocking,Python,Unit Testing,Exception,Mocking,尝试使用副作用模拟Python 3.6中的PermissionError异常。看起来调用了我的函数并引发了EPERM异常,但随后它无法运行我的except语句。对于“真实”OS错误异常,运行的代码与预期的相同。我的代码: #my_module.py import os import errno import sys import inspect def open_file(fname): try: with open('./' + fname, 'w') as f:

尝试使用副作用模拟Python 3.6中的PermissionError异常。看起来调用了我的函数并引发了EPERM异常,但随后它无法运行我的except语句。对于“真实”OS错误异常,运行的代码与预期的相同。我的代码:

#my_module.py
import os
import errno  
import sys
import inspect

def open_file(fname):
    try:
        with open('./' + fname, 'w') as f:
            print('never get here')
        return(0)

    except PermissionError as e:
        print('ERROR: \nIn function: ' + inspect.stack()[0][3])
        print('On line: {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
        sys.exit(1)
我的测试:

#OpenFileMockTestCase.py
from unittest import TestCase
from unittest import mock
import errno
import my_module

class OpenFileMockTestCase(TestCase):

    @mock.patch('my_module.os.open')
    def test_2_open_file_mock_oserror(self, mock_oserror):
        with self.assertRaises(SystemExit):
            mock_oserror.my_module.open_file.side_effect = (OSError((errno.EPERM), 'Not Allowed'))
            print('starting open_file with testfile2.txt...')
            mock_oserror.my_module.open_file('testfile2.txt')
当我跑步时:

C:\Users\mylib>coverage3 run -m unittest OpenFileMockTestCase.py -v
test_2_open_file_mock_oserror (OpenFileMockTestCase.OpenFileMockTestCase) ... starting open_file with testfile2.txt...

ERROR

======================================================================
ERROR: test_2_open_file_mock_oserror (OpenFileMockTestCase.OpenFileMockTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\users\xti027\appdata\local\programs\python\python36\lib\unittest\mock.py", line 1179, in patched
    return func(*args, **keywargs)
  File "C:\Users\xti027\Documents\DataTool-Git\DataTool\DataLoaderConfig\OpenFileMockTestCase.py", line 14, in test_2_open_file_mock_oserror
    mock_oserror.my_module.open_file('testfile2.txt')
  File "c:\users\xti027\appdata\local\programs\python\python36\lib\unittest\mock.py", line 939, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "c:\users\xti027\appdata\local\programs\python\python36\lib\unittest\mock.py", line 995, in _mock_call
    raise effect
PermissionError: [Errno 1] Not Allowed

----------------------------------------------------------------------
Ran 1 test in 0.031s

FAILED (errors=1)
我已经阅读了一些关于异常和模仿的问题和回答,并查看了Python文档:
我在正确的地方模仿正确的东西吗

您只需提出
PermissionError
异常:

mock_oserror.side_effect = PermissionError
请注意,我们直接在模拟的
open()
调用上设置了副作用!我还将模拟测试模块中的全局
open()
名称,而不是
os.open

您还应该直接调用被测函数,而不是作为
mock\u oserror
对象的属性:

import my_module

# ....

@mock.patch('my_module.open')
def test_2_open_file_mock_oserror(self, mock_open):
    mock_open.side_effect = PermissionError
    print('starting open_file with testfile2.txt...')
    with self.assertRaises(SystemExit):
        my_module.open_file('testfile2.txt')
我在这里使用了名称
mock\u open
,因为这更好地反映了被嘲笑的内容

演示:


对我来说是完美的结果。感谢您对代码的清理和清晰的解释。
>>> import os
>>> import errno
>>> import sys
>>> import inspect
>>> from unittest import mock
>>> def open_file(fname):
...     try:
...         with open('./' + fname, 'w') as f:
...             print('never get here')
...         return(0)
...     except PermissionError as e:
...         print('ERROR: \nIn function: ' + inspect.stack()[0][3])
...         print('On line: {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
...         sys.exit(1)
...
>>> with mock.patch('__main__.open') as mock_oserror:
...     mock_oserror.side_effect = PermissionError
...     try:
...         open_file('testfile2.txt')
...     except SystemExit:
...         print('test passed, sys.exit() called')
...
ERROR:
In function: open_file
On line: 3 PermissionError
test passed, sys.exit() called