this beginner question i'm pulling hair out.
i have simple python script "foo":
#!/usr/bin/env python class foo(): def __init__(self): self.do_something() def do_something(self): print "foo" def main(): foo() if __name__ == '__main__': main()
script works fine:
$ python foo.py foo
i want test function "do_something" in unittest , have code:
#!/usr/bin/env python import unittest import foo foo import * class testfoo(unittest.testcase): def test_foo(self): foo() def main(): unittest.main() if __name__ == "__main__": main()
if run tests, however, get:
$ python pyunit/foo.py e ====================================================================== error: test_foo (__main__.testfoo) ---------------------------------------------------------------------- traceback (most recent call last): file "pyunit/foo.py", line 9, in test_foo foo() nameerror: global name 'foo' not defined ---------------------------------------------------------------------- ran 1 test in 0.000s failed (errors=1)
my project structure:
$ tree . ├── foo.py └── pyunit └── foo.py
i have been playing around inspect
, dir()
, python debugger etc i'm getting nowhere.
although import foo
, from foo import *
both execute fine, , see function main
imported file, class foo
doesn't seem imported.
my objective, ultimately, write unit tests functions in class foo
.
what doing wrong?
you shouldn't use same file name (foo.py) in module. change test module test_foo instead. explicit better implicit.
when importing module parent directory, need use from <parent_dir> import <module_name>
, in case should state from <parent_dir> import foo
you encounter importerror: no module named foo
error becuase module not part of sys.path
.
simplest way import local directory python's lookup path:
import sys sys.path.append('.')
before other import statements. append project dir path. if have multiple classes same name, better use sys.path.insert(0, '.')
push path first position
Comments
Post a Comment