j4ck j4ck - 1 year ago 80
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
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)
except ValueError:
self.fail("%s is not a stringified integer!" % n)

Is there a way to assert this, without

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

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

Traceback (most recent call last):
File "/git/bitex/tests/client_tests.py", line 39, in test_restapi_nonce
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 Source

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

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


or test for digits instead:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download