使用 Pydev(Python 和 Eclipse)进行连续单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1015581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Continuous unit testing with Pydev (Python and Eclipse)
提问by Tal Weiss
Is there a way to integrate background unit tests with the Pydev Eclipse environment?
有没有办法将后台单元测试与 Pydev Eclipse 环境集成?
My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and trace log view).
我的单元测试运行良好,但我想将它们集成到基于源文件更改(例如使用鼻子)的后台运行并将结果集成回 Eclipse(当测试失败时,我在想大红色 X 控制台和跟踪日志视图)。
No, a command prompt running nose on the side does not count.
不,在侧面运行鼻子的命令提示符不算数。
I have had this Eclipse integration when developing RoR stuff.
我在开发 RoR 的时候已经有了这个 Eclipse 集成。
Thanks,
谢谢,
Tal.
塔尔。
EDIT:Check out the new Pydev (1.6.4) http://pydev.org/manual_adv_pyunit.html
编辑:查看新的 Pydev (1.6.4) http://pydev.org/manual_adv_pyunit.html
采纳答案by Fabio Zadrozny
This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass a final launch for the whole suite is done (then you can move on to another task).
此功能已添加到 PyDev 2.0.1 中,可选择在 python 文件更改时在上次测试运行中重新启动测试,以及仅重新运行错误的附加选项——尽管如果没有,它将运行完整的测试套件发现了错误,因为我们的想法是您解决错误,并在所有通过的时候完成整个套件的最终启动(然后您可以继续执行另一个任务)。
The current nightly build has this feature incorporated.
当前的每晚构建包含此功能。
回答by Henrik Gustafsson
Pydev does have some unit-test integration, but that's only as a run configuration...so...
Pydev 确实有一些单元测试集成,但这只是作为运行配置......所以......
This is not a very elegant way, but if you:
这不是一种非常优雅的方式,但如果您:
- Enable Project->Build Automatically
- In your project properties, add a new builder of type Program
- Configure it to run your tests and select 'during auto builds'
- 启用项目->自动构建
- 在您的项目属性中,添加类型为 Program 的新构建器
- 配置它以运行您的测试并选择“在自动构建期间”
Then at least you will get something that outputs the test results to the console on resource saves.
那么至少你会得到一些东西,将测试结果输出到资源保存的控制台。
回答by Henrik Gustafsson
I just realized that PyDev has rather powerful scripting support. Unfortunately I don't have the time to do it all for you (but if you complete this, please post it here :)
我刚刚意识到 PyDev 具有相当强大的脚本支持。不幸的是,我没有时间为你做这一切(但如果你完成了这个,请把它张贴在这里:)
If you create a file named pyedit_nose.py
that looks like this in an otherwise empty folder :
如果您pyedit_nose.py
在一个空文件夹中创建一个如下所示的文件:
assert cmd is not None
assert editor is not None
if cmd == 'onSave':
from java.lang import Runtime
from java.io import BufferedReader
from java.io import InputStreamReader
from org.eclipse.core.resources import ResourcesPlugin
from org.eclipse.core.resources import IMarker
from org.eclipse.core.resources import IResource
proc = Runtime.getRuntime().exec('ls -al')
extra_message = BufferedReader(InputStreamReader(proc.inputStream)).readLine()
r = ResourcesPlugin.getWorkspace().getRoot()
for marker in r.findMarkers(IMarker.PROBLEM, False, IResource.DEPTH_INFINITE):
if marker.getAttribute(IMarker.MESSAGE).startsWith("Some test failed!"):
marker.delete()
for rr in r.getProjects():
marker = rr.createMarker(IMarker.PROBLEM)
marker.setAttribute(IMarker.MESSAGE, "Some test failed! " + extra_message)
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH)
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR)
and set up Preferences->PyDev->Scripting Pydev to point to this directory you will get all projects in your workspace marked with an error every time a file is saved.
并设置 Preferences->PyDev->Scripting Pydev 以指向此目录,每次保存文件时,您都会得到工作区中的所有项目都标有错误。
By executing a script that returns the test results in some easy to parse format rather than ls
and parsing the output you should be able to put your markers in the right places.
通过执行以某种易于解析的格式返回测试结果的脚本,而不是ls
解析输出,您应该能够将标记放在正确的位置。
See this for some starting points:
有关一些起点,请参阅此内容:
- Jython Scripting in Pydev
- IMarkeris what represents a marker.
- IResourceis what you attach your markers to. Can be workspaces, projects, files, directories etc.
resource.createMarker(IMarker.PROBLEM)
creates a problem marker. - IProjectis a type of
IResource
that represents a project. Use themembers()
method to get the contents.
- Pydev 中的 Jython 脚本
- IMarker代表一个标记。
- IResource是您将标记附加到的内容。可以是工作区、项目、文件、目录等
resource.createMarker(IMarker.PROBLEM)
创建问题标记。 - IProject是一种
IResource
代表项目的类型。使用members()
方法获取内容。
回答by xverges
I run the test by hand the first time (Run > Run As > Python unit test). After that, I use
Ctrl+Shift+F9
to have the files saved and the tests executed, instead of saving with Ctrl+S
and expecting some magic to happen.
我第一次手动运行测试(运行 > 运行方式 > Python 单元测试)。在那之后,我
Ctrl+Shift+F9
习惯于保存文件并执行测试,而不是保存Ctrl+S
并期待一些魔法发生。
The Ctrl+Shift+F9
key combination relaunches the last run configuration.
该Ctrl+Shift+F9
组合键将重新启动最后一次运行配置。
Disclaimer: I'm new to Eclipse and to PyDev, so I may be suggesting something silly/obvious/wrong
免责声明:我是 Eclipse 和 PyDev 的新手,所以我可能会提出一些愚蠢/明显/错误的建议
回答by leo
回答by GoraKhargosh
I enhanced the "nosy" script to automatically build documentation and runs tests continuously. Nothing stellar, but gets the job done. Posting it here because the original link went down. Unlike the original nosy script, this one scans the directory recursively and allows looking for multiple patterns.
我增强了“nosy”脚本以自动构建文档并连续运行测试。没有什么出色的,但可以完成工作。发在这里是因为原来的链接失效了。与原始的 nosy 脚本不同,这个脚本递归地扫描目录并允许查找多个模式。
import os
import os.path
import sys
import stat
import time
import subprocess
from fnmatch import fnmatch
def match_patterns(pathname, patterns):
"""Returns True if the pathname matches any of the given patterns."""
for pattern in patterns:
if fnmatch(pathname, pattern):
return True
return False
def filter_paths(pathnames, patterns=["*"], ignore_patterns=[]):
"""Filters from a set of paths based on acceptable patterns and
ignorable patterns."""
result = []
if patterns is None:
patterns = []
if ignore_patterns is None:
ignore_patterns = []
for path in pathnames:
if match_patterns(path, patterns) and not match_patterns(path, ignore_patterns):
result.append(path)
return result
def absolute_walker(path, recursive):
if recursive:
walk = os.walk
else:
def walk(path):
return os.walk(path).next()
for root, directories, filenames in walk(path):
yield root
for directory in directories:
yield os.path.abspath(os.path.join(root, directory))
for filename in filenames:
yield os.path.abspath(os.path.join(root, filename))
def glob_recursive(path, patterns=["*"], ignore_patterns=[]):
full_paths = []
for root, directories, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.abspath(os.path.join(root, filename))
full_paths.append(full_path)
filepaths = filter_paths(full_paths, patterns, ignore_patterns)
return filepaths
def check_sum(path='.', patterns=["*"], ignore_patterns=[]):
sum = 0
for f in glob_recursive(path, patterns, ignore_patterns):
stats = os.stat(f)
sum += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
return sum
if __name__ == "__main__":
if len(sys.argv) > 1:
path = sys.argv[1]
else:
path = '.'
if len(sys.argv) > 2:
command = sys.argv[2]
else:
command = "make -C docs html; bin/python tests/run_tests.py"
previous_checksum = 0
while True:
calculated_checksum = check_sum(path, patterns=['*.py', '*.rst', '*.rst.inc'])
if calculated_checksum != previous_checksum:
previous_checksum = calculated_checksum
subprocess.Popen(command, shell=True)
time.sleep(2)
Hope this helps.
希望这可以帮助。
=)
=)