I am trying to create a helper function to read a file and mock out all imports for a unit test. I have to read the file vs import since i dont have those things on python path.
Example code:
#module.py
import com.stackoverflow.question
from com.stackoverflow.util import test_func
from com.stackoverflow.util import TestClass
#magic helper: what i want
magic = process('<path_to>/module.py')
for module in magic.modules_as_strings():
#todo would have to recuirsively add each path
# so i would first create com, then com.stackoverflow, etc
setattr(self, module, StubModules(module)
for obj in magic.sink:
#these would be "from" from x import Y
#its basically just creating self.Y = object
setattr(self, object)
Above is the mock code, I am really looking for the best way to just tokenize the file for "from/import statements"
That make sense? I know I could read the file line by line, but I was hoping for a cleaner/concise way.
Let me know if you have any questions.
Using the AST module, it is pretty easy:
For a module like this:
The output is: