【问题标题】:AssertionError when I try to conduct a unit test当我尝试进行单元测试时出现 AssertionError
【发布时间】: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

谢谢。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您收到该错误是因为您的 routes 模块被加载了两次。如您所知,python 只加载一次模块。该规则的例外是当您将模块多次添加到 python 路径中时:

    sys.path.insert(0, 'app/')
    

    如果您删除该行,您将不会多次重新定义您的 main 函数。你可以通过在routes.py 文件的顶层写一个print 来检查我告诉你的内容。您将看到它是如何打印两次的。

    【讨论】:

    • 非常感谢。我认为用这条线我指出在哪里寻找路线模块。你知道如何在不调用 2 次的情况下导入此文件吗?
    • 试试from app import routes
    • 嗯...它不起作用。在我的情况下有效:from app.routes import *。非常感谢。您能解释一下如何查找和修复此类错误吗?
    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多