简体   繁体   English

如何使用 XML 输出运行 Python 单元测试

[英]How to run Python Unit tests with XML output

I try to run Python unit tests on our continues integration server (Bamboo, running on Debian Jessie) with XML output so we can either mark build as fail or success according to the test results.我尝试使用 XML 输出在我们的持续集成服务器(Bamboo,在 Debian Jessie 上运行)上运行 Python 单元测试,以便我们可以根据测试结果将构建标记为失败或成功。 I am currently struggling with the fact that I just cannot install xmlrunner module.我目前正在为无法安装xmlrunner模块而苦苦挣扎。 This is what I have done这就是我所做的

sudo apt-get install python-xmlrunner
python3 
>>> import xmlrunner 
ImportError: No module named 'xmlrunner'

So I tried pip but it says package is already installed所以我尝试了pip但它说已经安装了包

sudo pip install unittest-xml-reporting
Requirement already satisfied (use --upgrade to upgrade): unittest-xml-reporting in /usr/lib/python2.7/dist-packages

Btw I can import this module with Python 2.7 which probably means that this python-xmlrunner package is installed only for 2.7 version.顺便说一句,我可以用 Python 2.7 导入这个模块,这可能意味着这个python-xmlrunner包只安装在 2.7 版本中。

And I run my test class through python3 -m unittest discover project_name with main method likes this unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))我通过python3 -m unittest discover project_name运行我的测试类,main 方法像这样unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))

You should install the runner using pip , and I think the package is just called xmlrunner (but maybe that is python 2.7)您应该使用pip安装运行器,我认为该包只是称为xmlrunner (但也许是 python 2.7)

pip install xmlrunner

Even better would be to everything inside virtualenv .更好的是virtualenv 中的所有内容。 Then you can pass a requirements.txt with all your dependencies, and you do not need to sudo install anything.然后你可以传递一个包含所有依赖项的requirements.txt ,你不需要sudo install 任何东西。 Then you can choose any python version you like, isolated from your global installation.然后你可以选择任何你喜欢的 python 版本,与你的全局安装隔离。

If you wnat to check if it is installed, and which version, use pip freeze如果您想检查它是否已安装,以及哪个版本,请使用pip freeze

EDIT If pip install xmlrunner does not work, try pip install unittest-xml-reporting .编辑如果pip install xmlrunner不起作用,请尝试pip install unittest-xml-reporting Thanks, @scrutari谢谢, @scrutari

当我遇到这个问题时,我可以通过将以下行放在 import 语句上方来修复它:

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

Usually we run tests using python -m unittest If you used similar approach, it will run your test cases, but it won't generate XML file.通常我们使用python -m unittest运行测试如果您使用类似的方法,它会运行您的测试用例,但不会生成 XML 文件。 So run your code like python test.py .所以像python test.py一样运行你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM