0

I'm writing python code that should run both with python 2.7 and 3.3+

I'm trying to figure out a way to properly check for http status codes and don't reduce my test coverage %.

if I write something like:

try:
    import http.client as httpclient
except ImportError:
    import urllib as httpclient

the coverage will never be 100%

So my question is: is there a better way to do it?

Giovanni Di Milia
  • 13,480
  • 13
  • 55
  • 67
  • 3
    Add [`# pragma: no cover`](http://nedbatchelder.com/code/coverage/excluding.html)? And don't get too hung up about 100% coverage, that is never practical. – Martijn Pieters Jun 15 '15 at 13:35
  • yeah, I know I can do that, but for most of the problems there is a way to solve without diminish the coverage that actually is also a more pythonic way: just trying to understand if that is the only way in this case – Giovanni Di Milia Jun 15 '15 at 13:40
  • 1
    You could put this import into a separate bridging module perhaps, then `pragma` the hell out of that module. But no, there is no more pythonic solution. – Martijn Pieters Jun 15 '15 at 13:41
  • You could arrange it so that the version you're *testing* with runs over all lines, but that seems unnecessary and a bit awkward. – jonrsharpe Jun 15 '15 at 13:51

1 Answers1

0

You can rarely acheive 100% test coverage when targeting multiple versions of Python. The Python 2 interpreter will follow one execution path, the Python 3 interpreter will follow another execution path, and neither interpreter will hit every line of code. The best solution is to do as Martijn has mentioned and use # pragma: no cover. Here's how I've solved this problem in one of my projects:

from sys import version_info
if version_info.major == 2:  # pragma: no cover
    from httplib import ACCEPTED, NO_CONTENT  # pylint:disable=import-error
else:  # pragma: no cover
    from http.client import ACCEPTED, NO_CONTENT  # pylint:disable=import-error

The solution above will satisfy coverage, flake8 and pylint:

  • Placing # pragma: no cover comments at the end of each conditional prevents coverage from counting either that line or anything within the following block.
  • The # pylint: comments serve a similar purpose.
  • Placing two spaces before each comment makes the flake8 style checker happy.

I pulled the above code from SatelliteQE/nailgun nailgun/entities.py.

Ichimonji10
  • 344
  • 1
  • 3
  • 9