본문 바로가기
파이썬

파이썬 Flask 앱 또는 요청 컨텍스트가 필요한 코드 테스트

by º기록 2021. 1. 14.
반응형

테스트에서 세션 에 액세스하려고 할 때 요청 컨텍스트 외부에서 작동 이 발생합니다. 필요한 것을 테스트 할 때 컨텍스트를 어떻게 설정할 수 있습니까?

import unittest
from flask import Flask, session

app = Flask(__name__)

@app.route('/')
def hello_world():
    t = Test()
    hello = t.hello()
    return hello

class Test:
    def hello(self):
        session['h'] = 'hello'
        return session['h']

class MyUnitTest(unittest.TestCase):
    def test_unit(self):
        t = tests.Test()
        t.hello()

 

해결 방법

 


c = app.test_client()
response = c.get('/test/url')
# test response


with app.app_context():
    # test your app context code


with current_app.test_request_context():
    # test your request context code

앱 및 요청 컨텍스트 모두 수동으로 푸시 할 수 있으므로 인터프리터를 사용할 때 유용합니다.

>>> ctx = app.app_context()
>>> ctx.push()

Flask-Script 또는 새로운 Flask CLI는 shell 명령을 실행할 때 자동으로 앱 컨텍스트를 푸시합니다.


 

참조 페이지 https://stackoverflow.com/questions/17375340

 

 

반응형

댓글