我为一个将使用Flask框架处理证书的站点创建了一个web界面。我想学习如何执行单元测试。我创建了一个文件来运行测试并验证routers.py文件
Test.py代码:
import unittest
import sys
sys.path.insert(0, 'app/')
import routes
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_my_file(self):
self.assertTrue(Certificate.IsValid(all_cert[2]))
if __name__ == '__main__':
unittest.main()
我认为错误是由于routers.py中的这部分代码造成的:
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html', title='Home', all_cert = all_cert)
@app.route('/all_certificates')
def all_certificates():
return render_template('all_certificates.html', title='all_certificates', all_cert = all_cert)
当我执行“flask run”命令时,这可以工作,但是如果我输入python3-m unittest test.py,我会得到一个错误:
File "/home/marka/Документы/Practice/test.py", line 4, in <module>
import routes
File "app/routes.py", line 30, in <module>
@app.route('/index')
File "/home/marka/Документы/Practice/venv/lib/python3.5/site-packages/flask/app.py", line 1251, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/home/marka/Документы/Practice/venv/lib/python3.5/site-packages/flask/app.py", line 67, in wrapper_func
return f(self, *args, **kwargs)
File "/home/marka/Документы/Practice/venv/lib/python3.5/site-packages/flask/app.py", line 1222, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: index
我在论坛上发现了一个类似的线程:AssertionError: View function mapping is overwriting an existing endpoint function: main,但我不知道如何在我的代码中应用它。是什么导致了错误?如何使用不同的装饰
我尝试重命名函数索引:
def index():
index.func_name = func.func_name
return render_template('index.html', title='Home', all_cert = all_cert)
然后我得到一个错误:
File "/home/marka/Документы/Practice/test.py", line 4, in <module>
import routes
File "app/routes.py", line 33
return render_template('index.html', title='Home', all_cert = all_cert)
^
IndentationError: unindent does not match any outer indentation level
在测试中,我想检查存储证书的函数并验证其有效性。 我所有的代码都在https://github.com/Butyrate/CertificationCenter
谢谢
您得到这个错误是因为您的
routes
模块被加载了两次。如您所知,python只加载一次模块。该规则的例外情况是,将模块多次添加到python路径中时:如果删除该行,就不会多次重新定义主函数。你可以通过在你的
routes.py
文件的顶层写一个print
来检查我告诉你的。你将看到它如何打印两次相关问题 更多 >
编程相关推荐