我一直在制作原型,并不介意分配了一个变量的低质量代码,该变量通过在 argv 上调用 eval() 获取其值,而后者又在包含 API 密钥的外部文件中获取其值。令我惊讶的是,它严重崩溃了单元测试(它们甚至都没有运行)。
这是我认为是罪魁祸首的代码片段:
from sys import argv
from apikeys import *
def setKey(the_key=DCK):
global CK
CK = the_key # Currently used key
if len(argv) == 1:
print('---Executing script. Enter optional arguments if you wish to use special API keys.---')
setKey()
elif len(argv) > 1:
setKey(eval(argv[1]))
TOKEN = rget(DOMAIN+'signin', params={'key':CK}).json['response']['token']
PARAMS = {'signature':TESTSIG, 'token':TOKEN}
# Rest of the code uses unittests which rely on PARAMS.
因此,我将包含 key 的变量之一作为它的值传递给测试我的脚本,它会产生以下回溯:
[gp@imdev1 dv1/tests]# python 2test_api2.py ANDROID_FILMS_KEY
Traceback (most recent call last):
File "2test_api2.py", line 604, in <module>
unittest.main()
File "/usr/lib/python2.6/site-packages/unittest2/main.py", line 97, in __init__
self.parseArgs(argv)
File "/usr/lib/python2.6/site-packages/unittest2/main.py", line 152, in parseArgs
self.createTests()
File "/usr/lib/python2.6/site-packages/unittest2/main.py", line 161, in createTests
self.module)
File "/usr/lib/python2.6/site-packages/unittest2/loader.py", line 148, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.6/site-packages/unittest2/loader.py", line 142, in loadTestsFromName
raise TypeError("don't know how to make test from: %s" % obj)
TypeError: don't know how to make test from: 9b269ac759211de6b3c8b238bd758ccf
9b269ac759211de6b3c8b238bd758ccf 基本上是运行 eval(ANDROID_FILMS_KEY) 并在单独的脚本中运行 setKey 函数的结果,将 API 密钥正确分配给 CK 作为字符串 '9b269ac759211de6b3c8b238bd758ccf'
问题如下:当 CK 和 PARAMS 用于包含应该进行单元测试的方法的类中时,Python 出人意料地引发了一个奇怪的异常,据说该异常告诉 unittest 不认为 9b269ac759211de6b3c8b238bd758ccf 是一个字符串?