python - unittest.TestCase 获取 `TypeError: Error when calling the metaclas bases __init__() takes exactly 2 arguments (4 given)`

标签 python python-unittest

我正在尝试向单元测试测试用例添加属性,但我不断收到以下错误。 TypeError:调用元类基类 __init__() 时出错,恰好需要 2 个参数(给定 4 个参数) 我正在用 Nose 运行测试。

但我只传递一个参数。 self 使其成为两个。所以我不知道第三个和第四个参数来自哪里。单元测试中有什么我应该注意的吗?还是 Nose ?

Base_Test.py

import unittest
from logUtils import logger

class Base_Test(unittest.TestCase):
    def __init__(self, p4rev):
        self.p4rev = p4rev

    def setUp(self):
        logger.critical(p4rev)
        triggerSomething(p4rev)

My_test.py

from Base_Test import Base_Test

rev = '12345'

class check_error_test(Base_Test(rev)):
    dosomething()

最佳答案

当从 super 类的子类继承时,Python 语法如下:

类子类名( super 类名): #子类主体

但是在你的编码中,

class check_error_test(Base_Test(rev)):
    dosomething()

您正在解析 Base_Test 类的实例,但不是该类。 Base_Test(rev) 将创建 Base_Test 类的实例。

您可以按如下方式修改代码。

class check_error_test(Base_Test):
    def __init__(p4rev):
        super(check_error_test).__init__(p4rev)

Base_Test也是继承自unittest.TestCase的类,所以需要在Base_Test.py中添加:

class Base_Test(unittest.TestCase):
    def __init__(self, methodName='runTest', p4rev=None):
        super(Base_Test, self).__init__(methodName)
        self.p4rev = p4rev

    def runTest(self):
        pass

在 BaseTest 类中添加 runTest() 只是为了避免 unittest.TestCase 类引发 ValueError 。如果没有通过传递给 methodName 参数的名称找到方法,unittest.TestCase 会引发此错误。

Bellow 是引发 ValueError 的代码段,可在 unittest.TestCase.init()

中找到
def __init__(self, methodName='runTest'):
        """Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.
        """
        self._testMethodName = methodName
        self._resultForDoCleanups = None
        try:
            testMethod = getattr(self, methodName)
        except AttributeError:
            raise ValueError("no such test method in %s: %s" %
                  (self.__class__, methodName))

关于python - unittest.TestCase 获取 `TypeError: Error when calling the metaclas bases __init__() takes exactly 2 arguments (4 given)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25066836/

相关文章:

python - 如何使用 Tornado 网络服务器进行点对点视频聊天

python - 在 openCV 3 python 2.7 中打开 ffmpeg/mpeg-4 avi

python - Chromedriver 测试后关闭

javascript - 如何将 JSON 值发送到 FullCalendar 并在日历中显示事件

python - 值错误 : total size of new array must be unchanged

python - Django 2.1 的完整性错误

python-unittest - 类型错误 : assertEqual() missing 1 required positional argument: 'second'

python - 单元测试 - ImportError : Start directory is not importable

python - 模拟函数调用实际函数

python - 子类的元类是如何确定的?