简体   繁体   中英

python::how to return Mock variable value?

 def m():
   cnx = mysql.connector.connect(**config)
   cursor = cnx.cursor()
   cnx.database = database_name
   cursor.execute('''SELECT COUNT(1) FROM URLlookup where malicious = '{0}' '''.format(new_URL))
   Malware = cursor.fetchone()[0]
   if Malware:
     do something
   else:
      do something

This i basic code to find values from database.If value exists then Malware =True otherwise False

I am writing a unit test by using Mock library and mocked the Mysql connection but not able to return value True or False bool for Malware.

  with patch ('mysql.connector.connect') as mock_db:
    connection = mock_db.return_value
    cursor = connection.cursor.return_value

After ward how to return True or False for "Malware" so that IF else statement can executed accordingly?

You need to mock cursor.fetchone to return a tuple of a single number. Then call m() then check whether expected thing happened.

with patch ('mysql.connector.connect') as mock_db:
    connection = mock_db.return_value
    cursor = connection.cursor.return_value
    cursor.fetchone.return_value = (1,)  # or (0,)    # <-----
    # TODO  call m()
    # TODO  assert that something is done or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM