guri
guri

Reputation: 1701

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?

Upvotes: 2

Views: 1035

Answers (1)

falsetru
falsetru

Reputation: 369424

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

Upvotes: 2

Related Questions