importing and nose
Peter Otten
__peter__ at web.de
Thu Jan 19 12:36:27 EST 2012
Andrea Crotti wrote:
> I'm writing some code to analyse pstats statistics, and I'm trying to
> have some working unit tests.
> Suppose I have in the test directory another directory 'profiling',
> which contains 'x.py', and 'b.py'.
>
> Now running the following code in a script works perfectly,
I don't believe you.
> class TestStatParser(unittest.TestCase):
>
> def setUp(self):
> self.temp_file = tempfile.mktemp()
> prof_path = path.join(path.dirname(__file__), 'profiling')
> sys.path.append(prof_path)
> import x
> profile.run('x.f1()', filename=self.temp_file)
>
>
> But running it within nose I get the following
>
> exec cmd in globals, locals
> File "<string>", line 1, in <module>
> NameError: name 'x' is not defined
>
>
> Which doesn't make sense to me, because the import doesn't actually
> fails, so
> how can x not be defined???
>
> Any clue?
profile.run() doesn't have access to the setUp() method's local namespace,
it looks into the global (module) namespace.
A stripped-down example:
>>> import profile
>>> def demo():
... def foo(): print "local"
... profile.run("foo()")
...
>>> demo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo
File "/usr/lib/python2.6/profile.py", line 70, in run
prof = prof.run(statement)
File "/usr/lib/python2.6/profile.py", line 456, in run
return self.runctx(cmd, dict, dict)
File "/usr/lib/python2.6/profile.py", line 462, in runctx
exec cmd in globals, locals
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
>>> def foo():
... print "global"
...
>>> demo()
global
4 function calls in 0.000 CPU seconds
[snip]
More information about the Python-list
mailing list