caren vanderlee
caren vanderlee

Reputation: 195

How to change return value of mocked obj?

I have class with

import pandas as pd

class foo(object):
   def __init__(self):
      self.info = pd.DataFrame()

   def getData(self):
      self.__readCSV()

   def __readCSV(self):
      self.info = pd.read_csv(self.filename)

I have a unit test class with

class test(unittest.TestCase):
   def test(self):
      mock = patch('foo.pandas.read_csv')
      foo().getData()

      ...

How can I change pd.read_csv(self.filename) return value as DataFrame({'column1': Series([1., 2., 3.]),'column2': Series([4., 5., 6.])}) to test whether self.info is assigned, with assertEqual?

Upvotes: 3

Views: 9270

Answers (2)

Shaikhul
Shaikhul

Reputation: 722

Are you using Python 3? Python 3 has a built-in mock library, but for Python 2.x, you need to use third-party library (http://www.voidspace.org.uk/python/mock/index.html).

To mock pd.read_csv you can use following:

import unittest
# for Python 3.x
from unittest.mock import patch

# for Python 2.x
# from mock import patch
import pandas as pd

class test(unittest.TestCase):
    @patch('foo.pd.read_csv')
    def test(self, mock_read_csv):
        mock_read_csv.return_value = pd.DataFrame({'column1': Series([1., 2., 3.]),'column2': Series([4., 5., 6.])})
        assert foo().getData()

Upvotes: 9

Amit K.
Amit K.

Reputation: 609

Mocked objects have property side_effect,

class test(unittest.TestCase):
def test(self):
  mock = patch('foo.pandas.read_csv')
  mock.side_effect = my_data_formatter
  foo().getData()

Now you need to define the my_data_formatter function that reruns the data you want in format needed. for your pd.read_csv(self.filename) it might be,

def my_data_formatter(my_file):
    # formatting for the data you want.
    return DataFrame({'column1': Series([1., 2., 3.]),'column2': Series([4., 5., 6.])})

Upvotes: 1

Related Questions