【发布时间】:2022-11-10 01:44:13
【问题描述】:
我正在接受 python 测试,但不清楚测试中出现的内容。该测试使用了测试驱动开发,因此我们得到了一个包含 unittest 断言的文件,该文件调用了我们需要创建的模块。因此,我无法更改在测试文件中进行调用的方式。
以下是关注我的问题的两个文件的基础知识:
test_yahtzee.py:
from yahtzee import Roll, Type
import yahtzee
class TestYahtzee(unittest.TestCase):
# ...
# tests
# ...
def testFindUpperBest(self):
'''Finds best scoring opportunity from upper part of scorepad'''
self.assertEqual(Type.SIXES, Roll(1, 6, 1, 2, 3).up_best)
在 yahtzee.py 中:
class Type(Enum):
SIXES = 1
#...
# more enum values
#
class Roll():
def __init__(self, d1, d2, d3, d4, d5) -> None:
pass
@property # BUT WHAT IF THIS WEREN'T HERE?
def up_best(self) -> Type:
print('Found me!')
## Will return a Type later ...
这是让我感到困惑的部分:
请注意,test_yahtzee.py 文件没有使用 Roll 的实例,而是看起来 unittest 模块必须将 <Class.fun> 方法(即 Roll(...).up_best)绑定到它可以调用的东西上。 . 再次我无法更改此文件。
我不明白这种语法如何与我定义类方法的方式相互作用。以下是使用 python3 -m unittest test_yahtzee.py 时的四种可能
有人可以解释这四种情况下发生了什么,以便我更好地理解细微差别吗?
| yahtzee.py | test_yahtze.py | result |
|---|---|---|
| with @property as above | Roll(...).up_best | 'Found me', test passes |
| no @property | Roll(...).up_best | AssertionError: <Type.SIXES> != <bound method Roll.up_best of ... |
| with @property as above | Roll(...).up_best() | 'Found me', but 'Type' object is not callable |
| no @property | Roll(...).up_best() | 'Found me', test passes |
编写测试文件的方式......似乎假设这必须是具有@property 属性的getter,因为这是唯一可行的可能性?
【问题讨论】:
-
up_best是什么?您只向我们展示了best_upper。 -
抱歉,编辑没有我想象的那么完成。
标签: python python-3.x unit-testing properties