我有一个Python
/ OOP
问题。你们都熟悉C++
中的钻石问题,对吗?这是相似的。我有以下课程
class BaseAuth(TestCase):
def setUp(self):
# create dummy user and client, removing code of that for simplicity.
self.user.save()
self.client.save()
def _get_authenticated_api_client(self):
pass
class TokenAuthTests(BaseAuth):
def _get_authenticated_api_client(self):
super()._get_authenticated_api_client()
print("I AM IN TOKEN AUTH")
api_client = APIClient()
# do stuff with api_client
return api_client
class BasicAuthTests(BaseAuth):
def _get_authenticated_api_client(self):
super()._get_authenticated_api_client()
print("I AM IN BASIC AUTH")
api_client = APIClient()
# do stuff with api client
return api_client
class ClientTestCase(BasicAuthTests, TokenAuthTests):
def test_get_login_response(self):
api_client = self._get_authenticated_api_client()
# login test code
def test_get_clients(self):
api_client = self._get_authenticated_api_client()
# get client test code
def test_get_client_by_id(self):
api_client = self._get_authenticated_api_client()
# get client by id test code
def test_update_client_by_id(self):
api_client = self._get_authenticated_api_client()
# update client test code
def test_add_client(self):
api_client = self._get_authenticated_api_client()
# add client test code
def test_delete_client_by_id(self):
api_client = self._get_authenticated_api_client()
# delete client test code
现在,当我运行代码时,我可以看到它已打印出来:
I AM IN TOKEN AUTH
I AM IN BASIC AUTH
.I AM IN TOKEN AUTH
I AM IN BASIC AUTH
.I AM IN TOKEN AUTH
I AM IN BASIC AUTH
.I AM IN TOKEN AUTH
I AM IN BASIC AUTH
.I AM IN TOKEN AUTH
I AM IN BASIC AUTH
.I AM IN TOKEN AUTH
I AM IN BASIC AUTH
但是如果我认为功能是明智的,则测试仅针对BasicAuthTests
运行。我怎么知道1.测试运行的次数为6
,每个父类应为12
,6
。2.如果将_get_authenticated_api_client()
中的BasicAuthTests
函数更改为错误的return
类型,代码将崩溃,但是如果我在TokenAuthTests
中进行更改,则什么也不会发生,这意味着TokenAuthTests
并没有做任何事情,但是在工作中打印语句,这意味着调用了函数。这太令人困惑了,有人可以帮忙吗?我的最终目标是为每个父类返回的api_client
运行这6个测试。
这里必须提一下,代码运行良好。如果我分开运行它们,那么测试工作就可以了。我想简化代码并删除所有重复,这就是为什么我想尝试将它们合并到一个文件中。
我有一个Python / OOP问题。你们都熟悉C ++中的钻石问题吧?这是相似的。我有以下几个类BaseAuth(TestCase)类:def setUp(self):#...
您被您的MRO卡住了。尽管Python支持Diamond Inheritance,但涉及变量分配时您会陷入困境。