Python 2.6 unittest - 如何设置一个值以用于您正在测试的函数中的全局变量

Python 2.6 unittest - how to set a value to use for a global variable in a function that you're testing

我在为单元测试编写的函数中设置全局变量的值时遇到问题。

该函数可能尚未准备好用于测试。或者至少用于以简单的方式进行测试,但我正在努力解决这个问题。

这是我要测试的函数示例:

def my_func_with_globals(filepath):
  spos=filepath.find(__my_global_var1)
  new_path = filepath[0:spos] + __my_global_var2
  return new_path

def some_function():
  ...
  my_func_with_globals(filepath)
  ...

if __name__ = '__main__':
  global __my_global_var1
  __my_global_var1='value1'  
  global __my_global_var2
  __my_global_var2='value2'
  ...
  some_function()

这是我的测试示例:

import unittest
from my_module import *

class UnitTestMyModule(unittest.TestCase):
  def test_my_func_with_globals(self):
    self.assertEqual(my_func_with_globals('arbitrary/file/path'), 'valid output')

我使用@kdopen 的建议进行测试的另一个例子(给了我同样的错误):

import unittest
import my_module

class UnitTestMyModule(unittest.TestCase):
  def test_my_func_with_globals(self):
      my_module.__my_global_var1='some/value'
      my_module.__my_global_var2='second_val'
      self.assertEqual(my_module.my_func_with_globals('arbitrary/file/path'), 'valid output')

我不断收到错误消息:

NameError: global name '__my_global_var1' is not defined.

我已经尝试了一些不同的东西,但我什么都做不了。使用 unittest.mock.patch 看起来会很完美,但我仍然坚持使用 v2.6.4 目前的功能。

全局变量是用双前导下划线定义的,因此它们不会被 from my_module import * 语句导入。

可以使它们可以通过以下方式访问:

from my_module import __my_global_var1, __my_global_var2

或者,如果您使用 import my_module,您可以使用 my_module.__my_global_var1 等方式访问它们

但我在您的示例测试用例中没有看到任何对全局变量的引用

这是一个简单的例子

a.py

__global1 = 1

def foo():
    return __global1

b.py:

import a

print "global1: %d" % a.__global1
print "foo: %d" % a.foo()
a.__global1 = 2
print "foo: %d" % a.foo()

和运行宁b.py

$ python2.6 b.py 
global1: 1
foo: 1
foo: 2

更新:

该死,错过了显而易见的事情

您在 if 测试中声明变量。该代码不会在 import 上 运行 - 仅当您从命令行执行 python my_module 时。

在导入期间,__name__ 将设置为 my_module,而不是 __main__

所以,是的 - 当您调用单元测试时,它们 未定义。