繁体   English   中英

如何分发带有unittests作为可执行入口点的python包?

[英]how to distribute python packages with unittests as executable entry points?

我正在编写一个python程序包,其中包含在'setup.py'中注册的可执行脚本作为入口点。 安装软件包时,这些文件将放置在python软件包安装的“ bin”目录中,而没有“ .py”扩展名。 一旦安装了软件包,我也希望能够以可执行文件的形式运行软件包的单元测试。 单元测试位于setup.py的“ entry_points”中的“ test_package.py”中:运行python包

setup(
  entry_points={
      'console_scripts': [
          'my_exec = mypackage.my_exec:main'
          'test_package = mypackage.test_package.main'],
  }
)

test_package.py脚本从“测试文件”中读取一些文件:

mypackage/
  setup.py
  mypackage/
    my_exec.py
    test_package.py
    # files needed to run tests
    test-files/
    # directory containing files written by 'test_package'
    test-results/

当我运行“test_package.py”包里面它工作正常。 但是,当我安装它并在“ bin”中将“ test_package”创建为可执行文件时,然后运行:

$ test_package

从命令行无法找到测试。 它说“跑了0个测试”。 这个目录结构怎么了? 什么是正确的方式分配单元测试,即使它们创建文件也可以从命令行运行它们? 如果该软件包是为使用sudo特权的人安装的,则我希望是sudo-less用户能够运行这些,而无需对软件包安装位置进行写访问。

test_package.py的结构为:

class TestPackage(unittest.Test):
  def setUp():
     ...
  def test_foo():
     # read stuff from 'test-files/'
     # ...
     # output stuff to 'test-results/'
     # ...

def main():
    unittest.main()


if __name__ == '__main__':
    main()

默认情况下, unittest.main尝试在__main__模块中查找测试。 因为您尝试从入口点运行测试,所以该模块不再是__main__了。

可能如果您尝试将module参数传递给unittest.main函数(即mypackage.test_package则它可能会起作用。

有关更多详细信息,请参见unittest.main的文档:

  • Python3- https: //docs.python.org/3/library/unittest.html#unittest.main
  • Python2- https: //docs.python.org/2/library/unittest.html#unittest.main

暂无
暂无

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

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