When I made changes to the legacy scripts, I required a test, but if I was writing unittest code for a script with only functions without a class, I encountered a function test using a global variable and could not declare it globally. Let's go! I got the error.
※ Python2.7
Run
test_aaa.py
import aaa_module
class TestAAA(unittest.TestCase):
def test_aaa
aaa_module.aaa_func()
error
...
NameError: global name 'logger' is not defined
There is no logger. There is.
aaa_module.py
if __name__ == '__main__':
logger = logging.getLogger('...')
Declared with global. There is.
I couldn't help it, so I tried the following on the unittest side.
Run
test_aaa.py
import aaa_module
class TestAAA(unittest.TestCase):
def test_aaa
global logger
logger = logging.getLogger('...')
aaa_module.aaa_func()
error
...
NameError: global name 'logger' is not defined
does not change. Why ...
Reference: In Python, there are no global variables, to be exact, in-module variables. is it?
module.global variable = value
Run
test_aaa.py
import aaa_module
class TestAAA(unittest.TestCase):
def test_aaa
aaa_module.logger = logging.getLogger('...')
aaa_module.aaa_func()
There are still many unknowns in Python
Recommended Posts