How to run unittest discover from “python setup.py test”?

前端 未结 7 2079
不知归路
不知归路 2020-12-12 19:39

I\'m trying to figure out how to get python setup.py test to run the equivalent of python -m unittest discover. I don\'t want to use a run_tests.p

7条回答
  •  悲哀的现实
    2020-12-12 20:07

    One possible solution is to simply extend the test command for distutilsand setuptools/distribute. This seems like a total kluge and way more complicated than I would prefer, but seems to correctly discover and run all the tests in my package upon running python setup.py test. I'm holding off on selecting this as the answer to my question in hopes that someone will provide a more elegant solution :)

    (Inspired by https://docs.pytest.org/en/latest/goodpractices.html#integrating-with-setuptools-python-setup-py-test-pytest-runner)

    Example setup.py:

    try:
        from setuptools import setup
    except ImportError:
        from distutils.core import setup
    
    def discover_and_run_tests():
        import os
        import sys
        import unittest
    
        # get setup.py directory
        setup_file = sys.modules['__main__'].__file__
        setup_dir = os.path.abspath(os.path.dirname(setup_file))
    
        # use the default shared TestLoader instance
        test_loader = unittest.defaultTestLoader
    
        # use the basic test runner that outputs to sys.stderr
        test_runner = unittest.TextTestRunner()
    
        # automatically discover all tests
        # NOTE: only works for python 2.7 and later
        test_suite = test_loader.discover(setup_dir)
    
        # run the test suite
        test_runner.run(test_suite)
    
    try:
        from setuptools.command.test import test
    
        class DiscoverTest(test):
    
            def finalize_options(self):
                test.finalize_options(self)
                self.test_args = []
                self.test_suite = True
    
            def run_tests(self):
                discover_and_run_tests()
    
    except ImportError:
        from distutils.core import Command
    
        class DiscoverTest(Command):
            user_options = []
    
            def initialize_options(self):
                    pass
    
            def finalize_options(self):
                pass
    
            def run(self):
                discover_and_run_tests()
    
    config = {
        'name': 'name',
        'version': 'version',
        'url': 'http://example.com',
        'cmdclass': {'test': DiscoverTest},
    }
    
    setup(**config)
    

提交回复
热议问题