I'm testing a script that mainly consists of an object Foo
, which imports a library bar
.
import bar
class Foo():
*do stuff*
f = Foo()
*do stuff*
Now I create a unittest class to test Foo.
import foo
class FooTest(unittest.TestCase):
def setUp(self):
self.foo = foo.Foo()
*do tests*
Later, it has a line like:
bar.method(...)
This fails with 'bar not defined', but shouldn't it be imported via import foo
? How do automatically load whatever is required by the script under test?
CodePudding user response:
The importer model indeed imports everything from the other file, but under the imported model name as a namespace. See an example:
so_imported.py
import json
class Test:
def __init__(self) -> None:
self.text = "A phrase"
so_import.py
import so_imported
class Test2:
def __init__(self) -> None:
self.inner = {"test": so_imported.Test().text}
print(so_imported.json.dumps(self.inner))
Test2()
So you see the json
library imported under the module's namespace ?
If you want to import everything from the imported file without any namespaces, you can use: from foo import *
. Then the objects will be merged into the importer namespace.