如何对 python 版本开关进行单元测试

How to unit test a python version switch

如何为以下函数编写单元测试:

def version_switch():
    if sys.version_info.major < 3:
        print('not python 3')
    else:
        print('python 3')

我的第一个想法是嘲笑 sys.version_info.major 但由于它是一个只读属性,所以不会这样做。

可以肯定的是:我在 py3 和 py2 下使用 tox 运行 我的测试套件。但是,每个 运行 只会检查一个代码路径。实际功能不使用任何语言特定的功能。我是否应该寻找其他方法来确定版本,更容易模拟的方法?

您可能无法在 sys.version_info 上换出 major 的值,但可以在 sys 上换出 version_info 的值:

Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import mock
>>> with mock.patch.object(sys, 'version_info') as v_info:
...   v_info.major = 3
...   print(sys.version_info.major)
... 
3

请注意,我使用的是 python2.7,但我说服 sys 告诉我我使用的是 python3.x.

however, each run will only check one code path

所以呢?

你不关心 Python 3 代码路径如果你 运行 它在 Python 2 上会做什么,反之亦然反之亦然。没有必要对此进行测试。只需检查输出是否与您 运行 使用的 Python 版本正确对应。