我有一个简单的方法,根据方法参数将全局变量设置为True或False。
这个全局变量叫做feedback
,默认值是False
。
当我调用setFeedback('y')
时,全局变量将被改为feedback = True
。
当我调用setFeedback('n')
时,全局变量将被改为feedback = False
。
现在我正在尝试使用Python中的unittest进行测试:
class TestMain(unittest.TestCase):
def test_setFeedback(self):
self.assertFalse(feedback)
setFeedback('y')
self.assertTrue(feedback)
当我运行这个测试时,我会得到以下错误:
AssertionError: False is not true
。因为我知道这个方法是正确的,所以我假设全局变量被以某种方式重置了。然而,由于我还是Python环境中的新手,我不确定自己做错了什么。
我已经在这里阅读了一篇关于mocking的文章,但由于我的方法改变了一个全局变量,我不知道mocking是否能解决这个问题。
我将感激任何建议。
这是代码:
main.py:
#IMPORTS
from colorama import init, Fore, Back, Style
from typing import List, Tuple
#GLOBAL VARIABLE
feedback = False
#SET FEEDBACK METHOD
def setFeedback(feedbackInput):
"""This methods sets the feedback variable according to the given parameter.
Feedback can be either enabled or disabled.
Arguments:
feedbackInput {str} -- The feedback input from the user. Values = {'y', 'n'}
"""
#* ACCESS TO GLOBAL VARIABLES
global feedback
#* SET FEEDBACK VALUE
# Set global variable according to the input
if(feedbackInput == 'y'):
feedback = True
print("\nFeedback:" + Fore.GREEN + " ENABLED\n" + Style.RESET_ALL)
input("Press any key to continue...")
# Clear the console
clearConsole()
else:
print("\nFeedback:" + Fore.GREEN + " DISABLED\n" + Style.RESET_ALL)
input("Press any key to continue...")
# Clear the console
clearConsole()
test_main.py:
import unittest
from main import *
class TestMain(unittest.TestCase):
def test_setFeedback(self):
self.assertFalse(feedback)
setFeedback('y')
self.assertTrue(feedback)
if __name__ == '__main__':
unittest.main()
setFeedback
函数,包括全局变量和测试中使用的导入吗? - MrBean BremensetFeedback
中调用input
和clearConsole
并不合适;它们是在setFeedback
返回后,setFeedback
的调用者可能想要执行的操作。 - chepner