简体   繁体   English

为什么在 python 中进行单元测试时,我期望状态代码为 200,但状态代码为 404?

[英]Why am I expecting a status code of 200 but got a status code of 404 while unit testing in python?

I am writing a unit test case in python using unittest and pytest for a file.我正在使用文件的 unittest 和 pytest 在 python 中编写单元测试用例。 Out of the many functions I am unable to understand why doesn't it execute as a successfully passed test case.在众多函数中,我无法理解为什么它不能作为成功通过的测试用例执行。 Here is function which displays a settings page,and upon a successfull call it displays an html page.这是显示设置页面的函数,成功调用后它会显示一个 html 页面。

@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    global application_inst
    if request.method == 'POST':
        print("Setting changed")

    return render_template('settings.html', user=session['user'], application=application_inst)

and the unit testcase for the function is written below as:该函数的单元测试用例写如下:

class MyApp(unittest.TestCase):
    def setUp(self):
        self.app = create_app(db)
        self.client = self.app.test_client(self)

        with self.app.app_context():
            # create all tables
            db.create_all()

    def tearDown(self):
        pass

    def test_settings_passed(self):
        response = self.client.get('/settings', follow_redirects=True)
        self.assertEqual(response.status_code, 200)

The error that I get in the stacktrace is:我在堆栈跟踪中得到的错误是:

test_app.py::MyApp::test_settings_passed FAILED                          [100%]ENV :default
############ INIT ############
############ INIT ############
############ INIT ############

 
200 != 404

Expected :404
Actual   :200
<Click to see difference>

Please help me on this.请帮我解决这个问题。

Try to change so that self.client would be executed within app_context() as eg尝试更改以便self.client将在app_context()执行,例如

class MyApp(unittest.TestCase):
    def setUp(self):
        self.app = create_app(db)
        self.client = self.app.test_client(self)

        with self.app.app_context():
            # create all tables
            db.create_all()

    def tearDown(self):
        pass

    def test_settings_passed(self):
        with self.app.app_context():
            response = self.client.get('/settings', follow_redirects=True)
            self.assertEqual(response.status_code, 200)

I have created the same scenario and it works with and without app_context for me.我创建了相同的场景,它适用于和不app_context对我来说。 Also I have used this command to execute tests:我也使用这个命令来执行测试:

python -m unittest tests/test_the_test.py 

Also it depends of how you have set up the app.这也取决于您如何设置应用程序。 Used python3.7 for example bellow.例如下面使用python3.7

Mine is like this:我的是这样的:

├── app.py
├── index
│   ├── __init__.py
│   └── routes.py
└── tests
    └── test_the_test.py

my app.py is like this:我的app.py是这样的:

from flask import Flask



def create_app():
    app = Flask(__name__)
    from index import bp
    app.register_blueprint(bp)
    return app

My index/__init__.py like this:我的index/__init__.py像这样:

from flask import Blueprint

bp = Blueprint(__name__, '/')

from index import routes

my index/routes.py like this:我的index/routes.py像这样:

from index import bp
from flask import jsonify

@bp.route('/test')
def test():
    print('goes here?')
    return jsonify({'result': True})

my tests/test_the_test.py like this:我的tests/test_the_test.py像这样:

import unittest

from app import create_app


class MyApp(unittest.TestCase):
    def setUp(self):
        self.app = create_app()
        self.client = self.app.test_client(self)

    def tearDown(self):
        pass

    def test_settings_passed(self):
        response = self.client.get('/test', follow_redirects=True)
        self.assertEqual(response.status_code, 200)

    def test_settings_failed(self):
        response = self.client.get('/test_not_exist', follow_redirects=True)
        self.assertEqual(response.status_code, 404)

Executing this command:执行这个命令:

python -m unittest tests/test_the_test.py 

And my setup works properly, does the testing and give a correct result for both when the endpoint exists and when it doesn't exist.我的设置工作正常,进行测试并在端点存在和不存在时给出正确的结果。

result:结果:

python -m unittest tests/test_the_test.py 
.goes here?
.
----------------------------------------------------------------------
Ran 2 tests in 0.006s

OK

暂无
暂无

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

相关问题 期望 404 但得到 200 HTTP 状态码 - Expecting 404 but getting 200 HTTP status code 为什么我在端点后测试、单元测试期间收到 422 状态码? - Why am I getting 422 status code during the post endpoint testing, unit testing? Python json POST请求状态为200,而预期状态为201 - Python json POST request status 200 while expecting status 201 为什么我在 Django 中的测试函数返回状态代码 404 而页面在 chrome 浏览器中正确显示? - Why my testing function in the Django returns status code 404 while the page is shown correctly in the chrome browser? FastAPI POST Pydantic 方法单元测试重定向 status_code 307 而不是 200 - FastAPI POST Pydantic method unit testing redirecting status_code 307 instead of 200 Python请求循环,如果状态码不是200,则重试 - Python request loop, retry if status code not 200 NotFoundError:预期Google存储状态为[200]。 但是在读取文件时状态为404 - NotFoundError: Expect status [200] from Google Storage. But got status 404 while reading a file 当浏览器给出404时,python库中的request模块给出的状态码为200 - request module in python library gives status code as 200 when the browser gives 404 Python POST 请求返回 404 状态代码,但 GET 请求返回 200 - Python POST Request returns 404 status code but GET request returns 200 使用 Python 检查响应时间、长度和 URL 状态(获取代码 200,404 等) - Check Response Time, Length and URL status(get code 200,404 etc ) using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM