1

I have this little test.py script I needs to get it running on our CI. In our local machines, most people use python 2.7, so import unittest works. But in the CI, the environment is python 2.6, which means import unittest2.

Currently, I'm invoking the script via

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
    import xmlrunner
    unittest2.main(testRunner=xmlrunner.XMLTestRunner(output='xml-reports'))
zjk
  • 2,043
  • 3
  • 28
  • 45
  • Possible duplicate of [Detect Python version at runtime](http://stackoverflow.com/questions/9079036/detect-python-version-at-runtime) – Colonel Thirty Two Jan 18 '16 at 02:55
  • 1
    Rather than clutter your script, just have it use `unittest2` and make your development environment match your CI environment (which just involves installing the redundant `unittest2` module). If and when you switch to Python 2.7 in your CI, *then* modify your script to use `unittest`. – chepner Jan 18 '16 at 03:00
  • Thanks, I've found a more closely duplicate http://stackoverflow.com/questions/13344380/what-is-the-most-pythonic-way-to-support-unittest2-features-across-a-range-of-py – zjk Jan 18 '16 at 03:00

2 Answers2

1

You can check your python version at runtime and assign which import you want.

import sys

if sys.version_info[0] == 2 and sys.version_info[1] < 7:
    import unittest2
elif sys.version_info[0] == 2 and sys.version_info[1] == 7:
    import unittest
Rick
  • 191
  • 1
  • 8
0

Another option is to use try/except:

try:
    import unittest2 as unittest
except ImportError:
    import unittest

This should result in the best option for unittest being available for the python you are using, but consistently imported as unittest in all cases.

jgstew
  • 131
  • 2
  • 9