Testing Dependencies Using Python

I would like to write unit tests to check if there is a dependency between two python packages. For instance:.

a/ __init__.py models.py views.py ... b/ __init__.py models.py views.py ... 

a unit test to verify that the modules in package b do not import any of the modules in package a . The only solution I have so far is to scan the files and check if the source code is “from” or “import”. Are there any other ways to do this? One of the requirements is that a/ and b/ must be on the same directory level.

I would like to have this unit test, because I want to be sure that I can use package b in other projects without package a , and also not have other developers write code that will make b dependent on a .

+6
source share
2 answers

Python is too dynamic to do this 100% correctly. Note that you can import modules by calling __import__ , which takes a string argument so that the name of the imported module can be built at run time. In addition, __import__ is a function, so it can be tied to other names, so you can’t even be sure to detect all cases when something is imported.

And it is technically possible for a module to call a function from another module that imports the module and returns it. Therefore, you definitely cannot do this by analyzing only package b .

And then there exec execute arbitrary python code built at runtime ...

Most likely, you can try and perform the unit test b exercise when a is on PYTHONPATH , and also when a not on PYTHONPATH . Still not reliable, as it only means that b completed all tests without a on PYTHONPATH , and not that he would never need a for anything. And if you're really unlucky, b does something really stupid and tinkers with sys.path in flight and somehow manages to import a .

If, however, this is all your own code, and you know that you aren’t doing this kind of stupid shit, then a simple script that scans files for import statements is probably your best bet. This probably worked very often on other people's random code. It is simply impossible to do the job perfectly with complete community.

+4
source
 import sys sys.modules['a'] = None import b # run unit tests for b to try and catch local import statements in b functions 
+1
source

Source: https://habr.com/ru/post/890891/


All Articles