设置烧瓶test_client

时间:2018-04-26 14:32:49

标签: unit-testing flask

我正在尝试测试我的烧瓶应用,但我收到此错误

  

RuntimeError:在应用程序上下文之外工作。   这通常意味着您尝试使用所需的功能   以某种方式与当前应用程序对象进行交互。要解决   这与app.app_context()建立了一个应用程序上下文。见   文档以获取更多信息。

我已经尝试了解错误但我知道的是有一个客户端实例应该被实例化以用于测试。救命。 我的代码:

import unittest

from flask import jsonify


class TestAuth(unittest.TestCase):
"""Class for testing all the API endpoints"""
def setUp(self):
    """Initializing a test client and making the environment a testing one"""
    app.app.config['TESTING'] = True
    self.app = app.app.test_client()
    self.app.testing = True

def sign_in(self, email='user@gmail.com', password='testpass'):
    user_data = jsonify({"email": email, "password": password})
    return self.app.post('/api/v1/auth/signup/', data=user_data)

def log_in(self, email='user@gmail.com', password='testpass'):
    user_data = jsonify({"email": email, "password": password})
    return self.app.post('/api/v1/auth/login/', data=user_data)

def test_home_status_code(self):

    result = self.app.get('/api/v1/')
    self.assertEqual(result.status_code, 200)

def test_signin_status_code(self):
    result = self.sign_in()
    self.assertEqual(result.status_code, 200)

def test_login_correct_login(self):
    """test login after signing in"""
    self.sign_in()
    result = self.log_in()
    self.assertEqual(result.status_code, 200)
    self.assertIn(b'Success', result.message)

def test_login_with_wrong_credentials(self):
    """test successful login"""
    self.sign_in()  # must sign in first for successful login
    result = self.log_in(email='wrong@mail', password='wrongpass')
    self.assertIn(b'Wrong Username or Password', result.message)


if __name__ == "__main__":
unittest.main()

1 个答案:

答案 0 :(得分:0)

试试这个:

def test_home_status_code(self):

    with self.app as client:
        result = client.get('/api/v1/')
        self.assertEqual(result.status_code, 200)