我有一个简单的方法,可以根据方法参数将全局变量设置为 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 是否可以解决这个问题。
我将不胜感激。
这是代码:
主要.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()