簡體   English   中英

Pytest:無法讓Flask應用程序在測試中運行

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

我正在嘗試找出如何使用pytest測試最基本的Flask應用程序。 (我在Windows 10上)。 這是應用程序代碼myapp.py:

from flask import Flask

api = Flask(__name__)

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

當我在瀏覽器中轉到http://127.0.0.1:5000/時,或者當我使用curl向該URL發出GET請求時,它可以正常工作,我會看到“索引頁”響應文本。

然后,我設置了一個基本的測試腳本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

我添加了第一個瑣碎的test_assert()函數只是為了確保pytest正常工作(我是python的新手)。

現在,當我運行pytest(> pytest -v)時,第一個(瑣碎的)測試通過了,但是test_home_page()測試失敗了。 通過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 ====

我花了幾天的時間閱讀有關如何確定pytest失敗的簡單示例的信息-響應應該為200,但始終給出404。

誰能看到我做錯了什么,或者為什么這樣做不起作用? 謝謝。

嘗試這個:

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