Dav*_*gac 2 python testing assertions
我正在用 Python 编写一些测试,对于其中一个测试,我需要验证一个值是 int 还是可以干净地转换为 int。
应该通过:
0
1
"0"
"123456"
Run Code Online (Sandbox Code Playgroud)
应该失败:
""
"x"
"1.23"
3.14
Run Code Online (Sandbox Code Playgroud)
我怎样才能最好地写出这个断言?
因此,为了 100% 确定,它必须是这样的:
def is_integery(val):
if isinstance(val, (int, long)): # actually integer values
return True
elif isinstance(val, float): # some floats can be converted without loss
return int(val) == float(val)
elif not isinstance(val, basestring): # we can't convert non-string
return False
else:
try: # try/except is better then isdigit, because "-1".isdigit() - False
int(val)
except ValueError:
return False # someting non-convertible
return True
Run Code Online (Sandbox Code Playgroud)
在下面的答案中,有一个检查,使用类型转换和相等检查,但我认为它对于大整数无法正常工作。
也许还有更短的路