简体   繁体   English

Pytest:无法让Flask应用程序在测试中运行

[英]Pytest: cannot get Flask app to behave in test

I am trying to work out how to use pytest to test the most basic Flask app. 我正在尝试找出如何使用pytest测试最基本的Flask应用程序。 (I'm on Windows 10). (我在Windows 10上)。 Here is the app code, myapp.py: 这是应用程序代码myapp.py:

from flask import Flask

api = Flask(__name__)

@api.route('/', methods=['GET'])
def index():
    return 'Index Page'

When I go to http://127.0.0.1:5000/ in a browser, or when I use curl to issue a GET request to that URL it works correctly, I see the 'Index Page' response text. 当我在浏览器中转到http://127.0.0.1:5000/时,或者当我使用curl向该URL发出GET请求时,它可以正常工作,我会看到“索引页”响应文本。

Then I set up a basic test script, test_app.py: 然后,我设置了一个基本的测试脚本test_app.py:

import pytest
from flask import Flask

def test_assert():
    assert True

def test_home_page(client):
  response = client.get('/')
  assert response.status_code == 200

@pytest.fixture
def client():
  flask_app = Flask(__name__) 
  client = flask_app.test_client()
  return client

I added the first trivial test_assert() function just to ensure pytest was working (I'm v new to python). 我添加了第一个琐碎的test_assert()函数只是为了确保pytest正常工作(我是python的新手)。

Now, when I run pytest (>pytest -v) the first (trivial) test passes, but the test_home_page() test fails. 现在,当我运行pytest(> pytest -v)时,第一个(琐碎的)测试通过了,但是test_home_page()测试失败了。 The app returns status code 404 when run through pytest. 通过pytest运行时,该应用返回状态代码404。

collected 2 items

test_app.py::test_assert PASSED                                                                                  [ 50%]
test_app.py::test_home_page FAILED                                                                               [100%]

====================================================== FAILURES =======================================================
___________________________________________________ test_home_page ____________________________________________________

client = <FlaskClient <Flask 'test_app'>>

    def test_home_page(client):
      response = client.get('/')
>     assert response.status_code == 200
E     assert 404 == 200
E       -404
E       +200

test_app.py:10: AssertionError
========================================= 1 failed, 1 passed in 0.28 seconds ====

I've spent a couple of days reading around trying to determine why pytest fails for this simple example -- the response should be 200, but it keeps giving 404. 我花了几天的时间阅读有关如何确定pytest失败的简单示例的信息-响应应该为200,但始终给出404。

Can anyone see what I've done wrong or why this won't work? 谁能看到我做错了什么,或者为什么这样做不起作用? Thanks. 谢谢。

try this: 尝试这个:

from YOUR_MODULE import api 

def test_assert():
    assert True

def test_home_page(client):
  response = client.get('/')
  assert response.status_code == 200

@pytest.fixture
def client():
  client = api.test_client()
  return client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM