How to run unit tests with "pip install"?

Viewed 6809

At work, we are considering configuring a local pypi repository for internal software deployment. Deploying with "pip install" would be convenient, but I am concerned that unit tests should be executed after adding a new package to ensure proper installation. I had always assumed pip was doing this, but I see nothing related to testing in the pip documentation.

2 Answers

You can pass a parameter to setup.py via pip:

--install-option Extra arguments to be supplied to the setup.py install command (use like –install-option=”–install-scripts=/usr/local/bin”). Use multiple –install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.

pip install --install-option test

will issue

setup.py test

then You need setup.cfg in the same directory as setup.py:

# setup.cfg
[aliases]
test=pytest

sample 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'])

There is a way:

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')]

This will give you a list of tuples which you can then filter and search through to find whether they match with what you require.
Simple examples:

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
Related