好的,我一直在做一些测试,所以我每次运行方法都需要检查结果。因为测试无法正常工作。
我做了一个工作正常的例子(不是测试,而是相同的行为)。在我的测试中,结果不会改变,而在示例中,结果会发生变化。
例
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
测试
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
在thread
中,global result
是指定义testSi_Button_clicked
(或者更确切地说,定义testSi_Button_clicked
的类)的模块中名为result
的模块级变量。它不引用您在 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'])