j4ck j4ck - 3 months ago 10
Python Question

Asserting if a string is a valid int

I'm new to TDD, and I ran into a situation while trying to write a test.

My func:

def nonce():
return str(int(1000 * time.time()))


I've written a test for it - and while it does what I want, it seems like there should be something in the
unittest
module to handle this?:

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)


Is there a way to assert this, without
try/except
?


I have found this SO post, but the answers do not offer usage of
assert
afaict.

What bothers me especially, is that my
failed test
message is not as pretty and clutter free as opposed to using a pure
unittest.TestCase
methods.

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!

Answer

You could make the assertion outside the exception handler; that way Python won't connect the AssertionError exception to the ValueError being handled:

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

 self.assertIsNotNone(intvalue)

or test for digits instead:

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

Note that that'll only work for integer strings without a sign. A leading + or - is acceptable to int() but not to str.isdigit(). But for your specific example, using str.isdigit() would suffice.

Comments