【问题标题】:Asserting if a string is a valid int [duplicate]断言字符串是否是有效的 int [重复]
【发布时间】: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!

【问题讨论】:

  • 该消息用于调试您的测试;如果在处理另一个异常的上下文中引发了一个异常,您通常想知道这一点。
  • “答案不提供assert afaict 的用法” - 是什么让你这么说?所有这些都可以轻松适应测试 - 例如self.assertTrue(n.isdigit())
  • 没有停下来思考答案中所说的内容让我这么说。你是对的。废话。
  • @jonrsharpe: n.strip().isdigit() 然后,int() 将剥离字符串。

标签: python unit-testing python-3.x assert


【解决方案1】:

您可以将断言置于异常处理程序;这样 Python 就不会将 AssertionError 异常连接到正在处理的 ValueError

try:
    intvalue = int(n)
except ValueError:
    intvalue = None

 self.assertIsNotNone(intvalue)

或改为测试 digits

self.assertTrue(n.strip().isdigit())

请注意,这只适用于没有符号的整数字符串。 int() 可以接受前导 +-,但 str.isdigit() 不能接受。但是对于您的具体示例,使用 str.isdigit() 就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2016-09-16
    • 1970-01-01
    • 2021-07-11
    • 2018-07-10
    • 2016-07-04
    相关资源
    最近更新 更多