开发者

Mock: How to mock my sqlalchemy database?

This is the function I am trying to test.

def user_register():
    
    request_data = request.get_json()
  
    insert = service_register(request_data)
    
    print(type(insert))
    return insert

in this through service_register it passes to run_insert function for executing database query

def service_register(request_data):
    
    print("Into Register")
   
    data = ({"user_name": user_name, "password": password,
                "email_address": email_address, "dob": dob, "address": address, "uid": uid})
    

    try: 
       
       insert = run_insert(data) 
    #    开发者_JAVA技巧print(insert)
       return make_response(jsonify({'Message': 'New user Created'}),201)

    except sqlalchemy.exc.IntegrityError:
        return make_response({'message':'User already exist with this email address!'}, 409)

So I want to know do I need to mock run_insert(data) or connection inside it and how? because I don't want that data to be inserted into my database.

CONST_INSERT = "INSERT INTO user (user_name, password, email_address, dob, address, uid ) VALUES(:user_name , :password, :email_address, :dob, :address, :uid)"

def connection():

    engine = create_engine('mysql://root:admin@172.17.0.2:3306/flask',poolclass = NullPool)
    conn = engine.connect()
    return conn
def run_insert(data):
    conn = connection()
    sql = text(CONST_INSERT)
    
    print(sql)
    conn.execute(sql, data)
    conn.close()
    return ("executed")

This is what I've tried in my test function I'm not able to get i. How to use multiple mocks ii. How to mock database

  def test_service_reg_return_correct_data(self):
        data = {                                                              
            "user_name": "testuser53",
            "password": "123456",
            "email_address": "testuser53@example.com",
            "dob": "2022-06-07 00:00:00",
            "address": "Ahmedabad",
            
        }
        
     
        m1 = mock.MagicMock()
        m1.get_json.return_value = data

        m2 = mock.MagicMock()  ----> for database ?????
        
        print("m", m1)
        with mock.patch("backened.routes.register.request", m1):
            response =user_register()

            self.assertEqual(response.json, {'Message': 'New user Created'},201) 
        

this is what I've implemented

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜