otsukare Thoughts after a day of work

Print Messages With Nosetests

Let's clear something out print in the code is bad. But sometimes it is useful when you need to quickly debug or understand what is happening. Just do not forget to remove them before committing.

On development, we use unittest and nose for testing the code. Running one set of tests is as easy as

nosetests tests/

and the result is:

Ran 3 tests in 0.175s


Though usually I prefer to run:

nosetests -v tests/

which reveals our inconsistency in naming. Probably my own mistake.

Check Cache-Control for issues. ... ok
Check ETAG for issues. ... ok
Checks if we receive a 304 Not Modified. ... ok

Ran 3 tests in 0.173s


But there is something which was bothering me for a long time. Let's say I put a print statement in the code anywhere, be in the test or in the application code. Even when tests are valid, I want to know the content of some variables. I want to make double sure I'm testing the right thing.

    def test_cache_control(self):
        '''Check Cache-Control for issues.'''
        rv ='/issues/100', environ_base=html_headers)
        print '\n\n{what}:\n{this}\n'.format(what="Headers", this=rv.headers)
        self.assertIn('cache-control', rv.headers)
        self.assertEqual(rv.cache_control.max_age, 0)

nose will swallow everything except when the test fails. I finally discover the right parameter (and it's probably obvious to others): --nocapture. This will make it possible to get the print messages.

nosetests -v --nocapture tests/
('secrets', '/Users/karl/code/')
Check Cache-Control for issues. ... 

Content-Type: text/html; charset=utf-8
Content-Length: 9981
Cache-Control: must-revalidate, private, max-age=0
ETag: "39a3c7d6fda546253a02927272a360db"
Date: Wed, 29 Mar 2017 07:49:19 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Content-Security-Policy-Report-Only: default-src 'none'; connect-src 'self'; font-src 'self'; img-src 'self' https://*; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; report-uri /csp-report

Check ETAG for issues. ... ok
Checks if we receive a 304 Not Modified. ... ok

Ran 3 tests in 0.190s


Hope it is useful for someone else. It was in the documentation but was not obvious to me when I read it a couple of times.

Don’t capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE]

And yes I'm removing this print right away before I forget.