Unit testing entire project hierarchy in Python using unittest in pydev

与世无争的帅哥 提交于 2019-12-12 11:25:09

问题


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:


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


来源:https://stackoverflow.com/questions/9207748/unit-testing-entire-project-hierarchy-in-python-using-unittest-in-pydev

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