gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:36 25 4
gpt4 key购买 nike

我正在尝试向单元测试测试用例添加属性,但我不断收到以下错误。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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com