【发布时间】:2019-10-31 07:58:11
【问题描述】:
我为使用 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。
谢谢。
【问题讨论】: