Coverage.py does not discover tests without init.py file in sub directories

☆樱花仙子☆ 提交于 2020-05-29 10:31:30

问题


When I run coverage for python, I always need an empty __init__.py file in the tests sub-directory to get coverage to run the tests. This is a requirement for python2 packages, but not for python3. To reproduce, I did the following (pre-requisites are python3, pip3 and brew):

  1. Run the following terminal command:

    pip3 install coverage
    
  2. Create the following directory structure:

    example\
        example.py
    tests\
        test_example.py
    

example.py:

#!/usr/bin/env python3
class Example:
    value = 3

    def update(self):
        self.value = 4

test_example.py:

#!/usr/bin/env python3

import unittest
from example.example import Example

class TestExample(unittest.TestCase):
    def test_example(self):
        example_object = Example()
        self.assertEqual(3, example_object.value)
        example_object.update()
        self.assertEqual(4, example_object.value)
  1. Run the following terminal command:

    coverage run --branch -m unittest discover -s . && coverage report
    

I should get: Ran 1 test in x.yz seconds, but I always get Ran 0 tests in x.yz seconds, and to fix this, I have to add __init__.py files to both directories. How can I run coverage without needing the init files?

Please let me know if you need anything else from me regarding this question. I would appreciate any help!


回答1:


Although Python 3 doesn't need __init__.py files, omitting them creates namespace packages, which are not a good idea if you don't need them. For example, they are read last, so even directories later in the PYTHONPATH can shadow your files.

You should create the __init__.py files anyway.




回答2:


The exact path to the tests folder from the top has to be specified. For example:'python3 -m unittest discover src/main/python/tests'

Its most likely a bug with 'unittest discovery' where discovery works when you explicitly specify namespace package as a target for discovery.

But it does not recurse into any namespace packages inside namespace_pkg. So when you simply run 'python3 -m unittest discover' it doesn't go under all namespace packages (basically folders) in cwd.

Some PRs are underway(for example:issue35617) to fix this, but are yet to be released



来源:https://stackoverflow.com/questions/47640812/coverage-py-does-not-discover-tests-without-init-py-file-in-sub-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!