Unit testing entire project hierarchy in Python us

2019-06-25 11:53发布

I am using unittest module to unit test some python code that has been created in a hierarchical struture of packages using Pydev. The problem arises as I try to use separate source folders for actual source code and its unit test in pydev.

project
  |----src
  |     |----com
  |     |     |----myself
  |     |     |       |----MyApplication
  |     |     |       |          |----SampleFileToTest.py  => The application file that I want to test
  |----test
  |     |----com
  |     |     |----myself
  |     |     |       |----MyApplication
  |     |     |       |          |----TestTheSampleFileToTest.py  => My test case file

As I am trying to separate the hierarchies, I am getting problems in referencing the application file in the test file. Is it possible to go by the Junit way, i.e. using different source folders but maintaining the same package name ?

1条回答
戒情不戒烟
2楼-- · 2019-06-25 12:29

This is not supported by default in Python itself (i.e.: nothing to do with PyDev) -- I also come from a Java background, so, you may need to forget some of your Java concepts here :)

In Python, whenever a folder with __init__.py is found, that package will no longer be searched in other paths. I think setuptools has some hackery to make that work and I remember vaguely that Python 3 may add some support for it, but so far I don't think it's generally recommended... This differs quite a bit from the Java approach -- in Python, flat is better than nested -- maybe you know, but otherwise, just for fun, start a Python interpreter session and do 'import this' :)

I.e.: In short, once my_app/__init__.py is found, it won't try to resolve my_app subfolders in any other place in the PYTHONPATH

So, you have 2 approaches... Usually what I do is having the tests close to the module in a _tests package. I.e.:

/project
/project/src
/project/src/myapp
/project/src/myapp/__init__.py
/project/src/myapp/_tests
/project/src/myapp/_tests/__init__.py
/project/src/myapp/_tests/test_myapp.py

And the other approach (which I must say I like a little bit less as the tests 'feel' more separate from the code), would be having a separate package for tests:

/project
/project/src
/project/src/myapp
/project/src/myapp/__init__.py
/project/src/myapp_tests/__init__.py
/project/src/myapp_tests/test_myapp.py
查看更多
登录 后发表回答