【问题标题】:Adding a parameter to the flask unittest向烧瓶单元测试添加参数
【发布时间】:2020-10-10 12:18:07
【问题描述】:

我正在尝试在烧瓶中对我的应用程序进行单元测试,但我有点卡住了这个。我想在我的应用程序路由中添加一个参数,但我不知道该怎么做。有人可以帮帮我吗?

我现在在测试中设置了硬编码的空缺 id,但我将向数据库添加一个连接和一个查询。但我首先想让它工作

这是路线:

@app.route('/add_application/<vacancy_id>')
def add_application(vacancy_id):
   return render_template(
        'addapplication.html')

这是我目前的测试:

VACANCY_ID = '5f67bc3643f71774b981ebfc'

def test_addapplicationFromVacancy(self):
    tester = app.test_client(self)
    tester.post(
        '/login',
        data=dict(username=USERNAME_USER, password=SPW_TWO),
        follow_redirects=True
    )
    response = tester.get(
        '/add_application/',
        data={'vacancy_id': VACANCY_ID},
        content_type='html/text'
    )
    print()
    self.assertEqual(response.status_code, 200)

【问题讨论】:

  • 你能解释一下按原样运行测试的结果吗?如果它抛出错误,请在你的问题中发布堆栈跟踪
  • 我收到了一个 500 错误,原因是缺少 id 参数。 Grzegorz Redlicki 的解决方案效果很好!

标签: python unit-testing flask parameter-passing


【解决方案1】:

我不了解您的整个应用程序,但我看到至少有两件事可以帮助您:

  1. 在创建客户端时不应使用self,因为这是unittest.TestCase 类的对象,而不是Flask 应用程序的对象。并且会自动通过。
    tester = app.test_client() 
    
  2. 您的端点使用 URL 参数,因此 get 请求应该或多或少如下所示:
    tester.get(f"/add_application/{VACANCY_ID}", ...)
    
    *我在这里使用了 f-string,如果你没有使用 >=3.6 版本的 Python,请随意更改它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-15
    • 2021-09-07
    • 2017-12-07
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多