使用Python3.x。
在为以下代码运行测试用例时,我得到了错误-
NameError: name 'TEST_VAR' is not defined
。我附加了要测试的文件、代码正在读取的yaml文件和单元测试文件
FileToTest.py:https://pastebin.com/d9QQiVSD
from os import path
from typing import TextIO
from yaml import load as yload, SafeLoader
TEST_FILE = "test.yaml"
def retreiveFilePath(fpath, fname, write_mode=False) -> TextIO:
filePath = open("%(path)s/%(filename)s" % {
"path": fpath,
"filename": fname
},
"w" if write_mode else "r"
)
return filePath
def methodToTest(val1, val2) -> str:
return "%(base)s/%(name)s/%(version)s.jar" % {
"base": TEST_VAR["var1"]["var12"],
"name": val1,
"version": val2
}
def method1() -> TextIO:
try:
filePath = retreiveFilePath(path.dirname(__file__), TEST_FILE)
configReturn = yload(filePath.read())
return configReturn
except Exception as e:
print("Failure, ", e)
return None
if __name__ == '__main__':
try:
TEST_VAR = method1()
except Exception as err:
exit_code = 1
exit(exit_code)
yaml文件:
var1:
var12: someVal12
var13: someVal13
var2:
var21: someVal21
测试用例:https://pastebin.com/crLymTHb
import unittest
from mock import patch
import FileToTest
class TestFile(unittest.TestCase):
def test__get_artifact_url(self):
val1 = "FName"
val2 = "LName"
resp = "someVal12/FName/LName.jar"
target_resp = FileToTest.methodToTest(val1, val2)
self.assertEqual(resp, target_resp)
if __name__ == '__main__':
unittest.main()
处理这种情况的正确方法是什么?我试着使用补丁,但没有白费
python中有两层变量,局部变量和全局变量。在函数中引用变量时,除非将其设为全局变量,否则该变量仅存在于该函数中。您可以将变量作为参数传递到函数中,也可以引用全局变量。要做到这一点,您可以将TEST_VAR移到main函数之外,或者在上面写入
相关问题 更多 >
编程相关推荐