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

标签 python python-2.7 unit-testing python-3.x pytest

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

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

我的第一个想法是模拟 sys.version_info.major 但因为它是一个只读属性,所以它不会这样做。

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

最佳答案

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

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。

关于python - 如何对 python 版本开关进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38022926/

相关文章:

python - Google App Engine - 从 Aptana Studio 运行 python shell 命令时出现问题

python - 从子类访问 python @property 的值

python - pip安装模块错误

python - 如何在 PyCharm 中禁用添加相对路径?

python - 使用 Python 和 Beautifulsoup 从日历中提取数据

python - Django:allow_tags和short_description如何工作?

python - 如何在 Jupyter Notebook 中的绘图旁边显示数据框

angularjs - Angular 1.5 单元测试组件,同时忽略子组件

java - JUnit : Is there a way to skip a test belonging to a Test class's parent?

python - 使用 Keras 扩充 CSV 文件数据集