Python:global&改变var参考

时间:2015-04-23 15:44:37

标签: python unit-testing global-variables global

好的,我一直在做一些测试,所以每次运行方法时都需要检查结果。因为测试不能正常工作。

我做了一个很好的例子(不是测试,但行为相同)。在我的测试中,结果不会改变,而在示例中它会改变。

示例

def thread():

    global result
    import time
    time.sleep(0.5)
    result = 5/2
    Gtk.main_quit()


import threading
from gi.repository import Gtk
result = None
t = threading.Thread(target=thread, args=())
t.start()
Gtk.main()
print result

OUTPUT: 2

TEST

def testSi_Button_clicked(self):

        def thread(button=self.builder.get_object('Si_Button')):

            import time
            global result
            time.sleep(0.5)
            result = self.esci.Si_Button_clicked(button)
            print 'result ' + str(result)
            #Gtk.main_quit()


        import threading

        self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
        result = None
        t = threading.Thread(target=thread, args=())
        t.start()
        Gtk.main()
        print 'assert'
        print 'result ' + str(result)
        self.assertIsNotNone(result)

OUTPUT:
Home_Window
return true
result True
assert
result None
F
======================================================================
FAIL: testSi_Button_clicked (testC_Esci.tstEsci)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testC_Esci.py", line 78, in testSi_Button_clicked
    self.assertIsNotNone(result)
AssertionError: unexpectedly None

1 个答案:

答案 0 :(得分:0)

thread中,global result引用模块中名为result的模块级变量,其中testSi_Button_clicked(或更确切地说,是定义testSi_Button_clicked的类) 被定义为。它不引用您在testSi_Button_clicked中定义的同名局部变量。

要修复,请将result设为可变对象(例如dict),删除global result语句,然后让thread成为result的封闭}。 (在Python 3中,您可以使用nonlocal关键字来避免这种包装技巧。)

def testSi_Button_clicked(self):

        def thread(button=self.builder.get_object('Si_Button')):
            import time
            time.sleep(0.5)
            result['result'] = self.esci.Si_Button_clicked(button)
            print 'result ' + str(result['result'])
            #Gtk.main_quit()


        import threading

        self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
        result = {'result': None}
        t = threading.Thread(target=thread, args=())
        t.start()
        Gtk.main()
        print 'assert'
        print 'result ' + str(result['result'])
        self.assertIsNotNone(result['result'])