This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: exec not woking in unittest
Type: compile error Stage:
Components: Library (Lib) Versions: Python 3.2
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, ezio.melotti, simonsteiner
Priority: normal Keywords:

Created on 2011-09-07 13:16 by simonsteiner, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (5)
msg143672 - (view) Author: simon (simonsteiner) Date: 2011-09-07 13:16
works in 2.6, fails in 3.2.2

import unittest
class MyTest(unittest.TestCase):
    def test_a(self):
        exec(compile("a = 1", '', 'single'))
        assert a == 1
if __name__ == '__main__':
    unittest.main()
msg143673 - (view) Author: simon (simonsteiner) Date: 2011-09-07 13:22
seems i need to use

exec(compile("a = 1", '', 'single'), globals())
msg143674 - (view) Author: simon (simonsteiner) Date: 2011-09-07 13:39
Can't get this one working:

import unittest
class MyTest(unittest.TestCase):
    def test_a(self):
        b = 1
        exec(compile("a = b + 1", '', 'single'))
        assert a == 2
if __name__ == '__main__':
    unittest.main()
msg143725 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2011-09-08 10:12
This doesn't seem related to unittest:

>>> class MyTest:
...     def test_a(self):
...         b = 1
...         exec(compile("a = b + 1", '', 'single'))
...         assert a == 2
... 
>>> t = MyTest()
>>> t.test_a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in test_a
NameError: global name 'a' is not defined

With unittest I get the same error.
msg143726 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2011-09-08 13:52
You're invoking undefined behavior by modifying function locals in exec().
History
Date User Action Args
2022-04-11 14:57:21adminsetgithub: 57137
2011-09-08 13:52:34benjamin.petersonsetstatus: open -> closed

nosy: + benjamin.peterson
messages: + msg143726

resolution: not a bug
2011-09-08 10:12:30ezio.melottisetnosy: + ezio.melotti
messages: + msg143725
2011-09-07 13:39:53simonsteinersetmessages: + msg143674
2011-09-07 13:22:01simonsteinersetmessages: + msg143673
2011-09-07 13:16:26simonsteinercreate