I have a simple method that sets a global variable to either True or False depending on the method parameter.
This global variable is called feedback and has a default value of False.
When I call setFeedback('y') the global variable will be changed to be feedback = True.
When I call setFeedback('n') the global variable will be changed to be feedback = False.
Now I am trying to test this using unittest in Python:
class TestMain(unittest.TestCase):
def test_setFeedback(self):
self.assertFalse(feedback)
setFeedback('y')
self.assertTrue(feedback)
When I run this test I get the following error: AssertionError: False is not true.
Since I know that the method works correctly, I assume that the global variables are reset somehow. However, since I am still very new to the Python environment, I don't know exactly what I am doing wrong.
I have already read an article here about mocking, but since my method changes a global variable, I don't know if mocking can solve this.
I would be grateful for suggestions.
Here is the code:
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()
setFeedbackfunction, including the global variable, and the imports you use in your test?inputandclearConsoledon't belong insetFeedbackat all; they are something that the caller ofsetFeedbackmight want to do aftersetFeedbackreturns.