Note that there are some explanatory texts on larger screens.

plurals
  1. POGlobal name is not defined for second unittest
    primarykey
    data
    text
    <p>Eclipse platform, Python 3.3.</p> <p>I've created the code below to demonstrate a problem when using global variables and python unittest. I'd like to know why the second unit test (a direct repeat of the first) results in a </p> <pre><code>NameError: global name '_fred' is not defined </code></pre> <p>try commenting out the second test and it'll all pass ok.<br> (Note: I've added a brief digest of what the real code is is attempting to achieve after the example, hopefully it'll be less obtrusive there as it's not really relevant to the issue)</p> <pre class="lang-python prettyprint-override"><code>''' Global Problem ''' import unittest _fred = None def start(): global _fred if _fred is None: _fred = 39 _fred += 3 def stop(): global _fred if _fred is not None: del _fred class Test(unittest.TestCase): def setUp(self): start() def tearDown(self): stop() def test_running_first_time(self): assert(_fred == 42) def test_running_second_time(self): assert(_fred == 42) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() </code></pre> <p>In the real code _fred is variable referencing an instance of a class derived from Thread (see what I did there) and gets assigned in the start method.<br> _fred = MyThreadClass()<br> There is a second global for a synchronized queue.<br> The methods start and stop control processing queue items on the dedicated thread. 'stop' stops the processing while allowing items to be added.<br> The API for Thread only permits a single call to start. So to restart processing I need a new instance of Thread. Hence the use of</p> <pre><code>if _fred is None: </code></pre> <p>and</p> <pre><code>del _fred </code></pre> <p>No prizes for guessing my primary language</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload