在请求后单元测试中模拟flask.g

时间:2020-01-16 22:17:56

标签: python python-3.x flask python-unittest

这里是test.py,其中使用mock_service来模拟游标和db,但是每次我得到'function' object has no attribute 'cursor'时都可以。如何正确模拟flask.g对象。我提到了这个article

test.py
def not_a_db_hit():
     print('I did not hit the DB')
     return object()

class MyTestCase(unittest.TestCase):

@mock.patch('utils.configure_db') #configure_db returns database
@mock.patch('Service.g')
def test_insert_cricket_data(self, mock_service, mock_db):
    with app.app_context():
        body = {
            'key1': 'value1'
        }
        headers = {
            'Content-Type': 'application/json',
        }

        mock_db.return_value = not_a_db_hit
        mock_service.cursor.return_value = not_a_db_hit
        mock_service.cursor.execute.return_value = None
        mock_service.db.commit.return_value = None
        response = self.app.post('/insertvalue', headers=headers.items(), data=json.dumps(body))
        print(response)

这是我的Service.py文件

from flask import g 

@service.before_request
def before_request():
    g.db = configure_db()
    g.cursor = g.db.cursor()

@service.route('/insertvalue', methods=['POST'])
def in_request():
    ....
    try:
        g.cursor.execute(sql, main_values)
        g.db.commit()
        return make_response("Created", 201)

任何帮助,感激不尽。 谢谢

0 个答案:

没有答案