Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #19134

Re: importing and nose

From Peter Otten <__peter__@web.de>
Subject Re: importing and nose
Date 2012-01-19 18:36 +0100
Organization None
References <4F184EAF.5080603@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.4868.1326994610.27778.python-list@python.org> (permalink)

Show all headers | View raw


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]

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: importing and nose Peter Otten <__peter__@web.de> - 2012-01-19 18:36 +0100

csiph-web