-2

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!
Community
  • 1
  • 1
deepbrook
  • 2,523
  • 4
  • 28
  • 49
  • The message is there for debugging your tests; if one exception is raised in the context of handling another, you *usually* want to know about this. – Martijn Pieters Aug 10 '16 at 13:20
  • *"the answers do not offer usage of `assert` afaict"* - what makes you say that? All of them can trivially be adapted into a test - `self.assertTrue(n.isdigit())`, for example. – jonrsharpe Aug 10 '16 at 13:21
  • Not stopping to think about what it says in the answer makes me say that. You're right. shucks. – deepbrook Aug 10 '16 at 13:23
  • @jonrsharpe: `n.strip().isdigit()` then, as `int()` will strip the string. – Martijn Pieters Aug 10 '16 at 13:23

1 Answers1

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343