How to check http status code in python version agnostic way?

205 views Asked by At

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?

1

There are 1 answers

0
Ichimonji10 On BEST ANSWER

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.