Download python module not from file

I have python code in a library that is trying to load a simple value from a module that will exist for applications that use this library

from somemodule import simplevalue

Typically, an application using the library will have a module file, and everything works fine. However, in unit tests, the module does not exist for this library. I know that I can create a temporary file and add this file to my path at runtime, but I was curious if there is a way in python to load something into memory that would allow working with this import.

This is more of a curiosity, since "add a module to the test path" is not useful: P

+3
source share
3 answers

. types.ModuleType , sys.modules:

sys.modules["somename"] = types.ModuleType("somename")

import somename. , script :

def myfunc(x, y, z):
    ...

somename.myfunc = myfunc

, : . , , .

, : , , "" _winreg -Windows-. .

+7

. Python , somemodule.simplevalue . somemodule. ?

, :

simplevalue = 42

, try/except, .

try:
    from somemodule import simplevalue
except ImportError:
    simplevalue = 42

, , .

try:
    import somemodule
except ImportError:
    class somemodule(object):
        simplevalue = 42

somemodule.simplevalue , .

, somemodule, --, unit test, :

import sys
sys.modules["somemodule"] = somemodule
+5

Testing your system ( sutin my example) should be able to cope with something that somemodulemay not exist, so you can block ImportError:

#!/usr/bin/env python

try:
    from somemodule import simplevalue
except ImportError, e:
    if 'somemodule' in e:
        '''We expect that to happen in the unittest but you should log something for when
         this happens in production'''

def fn():
    return simplevalue

Then you can enter the value in your unittest:

#!/usr/bin/env python

import unittest
import sut

class T(unittest.TestCase):

    def test_fn(self):
        sut.simplevalue = 42
        self.assertEquals(42, sut.fn())


if __name__ == '__main__':
    unittest.main()
+1
source

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


All Articles