如何使用“ pip install”运行单元测试?

时间:2019-01-05 19:22:16

标签: python pip

在工作中,我们正在考虑配置用于内部软件部署的本地pypi存储库。使用“ pip install”进行部署会很方便,但是我担心应该在添加新软件包后执行单元测试以确保正确安装。我一直以为pip正在执行此操作,但是在pip文档中没有发现与测试相关的内容。

2 个答案:

答案 0 :(得分:1)

您可以通过pip将参数传递给setup.py:

-安装选项 要提供给setup.py安装命令的其他参数(如–install-option =” – install-scripts = / usr / local / bin”之类的用法)。使用多个–install-option选项可以将多个选项传递给setup.py安装。如果您要使用带有目录路径的选项,请确保使用绝对路径。

pip install --install-option test

将发出

setup.py test

然后您需要在setup.py所在的目录中安装setup.cfg:

# setup.cfg
[aliases]
test=pytest

样本setup.py:

# setup.py
"""Setuptools entry point."""
import codecs
import os

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup


CLASSIFIERS = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Natural Language :: English',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Software Development :: Libraries :: Python Modules'
]

dirname = os.path.dirname(__file__)

long_description = (
    codecs.open(os.path.join(dirname, 'README.rst'), encoding='utf-8').read() + '\n' +
    codecs.open(os.path.join(dirname, 'CHANGES.rst'), encoding='utf-8').read()
)

setup(
    name='your_package',
    version='0.0.1',
    description='some short description',
    long_description=long_description,
    long_description_content_type='text/x-rst',
    author='Your Name',
    author_email='your@email.com',
    url='https://github.com/your_account/your_package',
    packages=['your_package'],
    install_requires=['pytest',
                      'typing',
                      'your_package'],
    classifiers=CLASSIFIERS,
    setup_requires=['pytest-runner'],
    tests_require=['pytest'])

答案 1 :(得分:-2)

有一种方法:

import pkg_resources as pkr
packages = [(v.project_name, v.version) for v in pkr.working_set]
print (packages)
# [('zope.interface', '4.5.0'), ..., ('absl-py', '0.2.2')]

这将为您提供一个元组列表,您可以对其进行过滤和搜索以查找它们是否与您的需求匹配。
简单的例子:

if packages[-1] == ('absl-py', '0.2.2'):
    print ('aye')
#aye

package_dict = dict(packages) 
#this converts the packages into a dictionary format
#However, you can simply open a file via
#with open('packages.txt', 'r') as f:
#process your packages into a dict object here, then use the below code    

for i,v in packages:
    if package_dict[i] == v:
        print ('yay') #will print yay multiple times