【发布时间】:2016-08-10 13:15:34
【问题描述】:
我是 TDD 新手,在尝试编写测试时遇到了情况。
我的功能:
def nonce():
return str(int(1000 * time.time()))
我已经为它编写了一个测试 - 虽然它可以满足我的要求,但似乎 unittest 模块中应该有一些东西来处理这个问题?:
def test_nonce_returns_an_int_as_string(self):
n = 'abc' # I want it to deliberately fail
self.assertIsInstance(n, str)
try:
int(n)
except ValueError:
self.fail("%s is not a stringified integer!" % n)
有没有办法在没有try/except 的情况下断言这一点?
我找到了这个SO post,但答案不提供assert afaict 的用法。
特别困扰我的是,与使用纯 unittest.TestCase 方法相比,我的 failed test 消息并不美观和整洁。
Failure
Traceback (most recent call last):
File "/git/bitex/tests/client_tests.py", line 39, in test_restapi_nonce
int(n)
ValueError: invalid literal for int() with base 10: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "//git/bitex/tests/client_tests.py", line 41, in test_restapi_nonce
self.fail("%s is not a stringified integer!" % n)
AssertionError: a is not a stringified integer!
【问题讨论】:
-
该消息用于调试您的测试;如果在处理另一个异常的上下文中引发了一个异常,您通常想知道这一点。
-
“答案不提供
assertafaict 的用法” - 是什么让你这么说?所有这些都可以轻松适应测试 - 例如self.assertTrue(n.isdigit())。 -
没有停下来思考答案中所说的内容让我这么说。你是对的。废话。
-
@jonrsharpe:
n.strip().isdigit()然后,int()将剥离字符串。
标签: python unit-testing python-3.x assert