Mock os.path.dirname using path



我正在为一个读取Excel文件的Python程序编写测试。

为了有一个工作测试标准,我有所谓的"Working_sheets"。

我的项目结构是

Root/
--->tests
------->golden_sheets/
----------->Desired results
------->src
----------->Python Files
------->Working sheets/
---->main/
---->sheets/

我正在运行的测试是

@patch('os.path.dirname')
def test_ResolutionSLA_Full(self):
datetime.date = MockDate
print(datetime.date.today())
os.path.dirname.return_value = "../working_sheets"
resolutionSLA = ResolutionSLA()
resolutionSLA.run_report()

但是,我收到错误

Traceback (most recent call last):
File "/usr/lib/python3.5/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/lib/python3.5/unittest/case.py", line 601, in run
testMethod()
File "/usr/local/lib/python3.5/dist-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
TypeError: test_ResolutionSLA_Full() takes 1 positional argument but 2 were given

使用"dirname"的方式是

self.dir_path = os.path.dirname(os.path.abspath(__file__)) + "/"

这通常会返回

/home/jphamlett/Documents/Work/ServiceNowReportAutomation/

但是,在测试期间,我希望它返回

../working_sheets/

我什至尝试使用与日期时间相同的技术

import os

class MockOSPath(os.path):
@classmethod
def abspath(cls, file):
return "../working_sheets/MockOSPath.py"

但这给了我错误

Traceback (most recent call last):
File "/home/jphamlett/.jetbrain/pycharm/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module>
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
File "/usr/lib/python3.5/unittest/main.py", line 93, in __init__
self.parseArgs(argv)
File "/usr/lib/python3.5/unittest/main.py", line 140, in parseArgs
self.createTests()
File "/usr/lib/python3.5/unittest/main.py", line 147, in createTests
self.module)
File "/usr/lib/python3.5/unittest/loader.py", line 219, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python3.5/unittest/loader.py", line 219, in <listcomp>
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python3.5/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
File "/home/jphamlett/Documents/Work/ServiceNowReportAutomation/tests/src/ResolutionSLA_Tests.py", line 8, in <module>
from MockOSPath import MockOSPath
File "/home/jphamlett/Documents/Work/ServiceNowReportAutomation/tests/src/MockOSPath.py", line 4, in <module>
class MockOSPath(os.path):
TypeError: module.__init__() takes at most 2 arguments (3 given)

我做错了什么?模拟日期时间工作得很好。

由于测试的错误输出表明您将两个参数传递给测试:

  • self: 测试类
  • @patch('os.path.dirname'(:修补的对象

要修复它,只需在方法签名中添加一个参数,并在测试中实际使用它:

@patch('os.path.dirname')
def test_ResolutionSLA_Full(self, mock_dir):
datetime.date = MockDate
print(datetime.date.today())
mock_dir.return_value = "../working_sheets"
resolutionSLA = ResolutionSLA()
resolutionSLA.run_report()

最新更新