Patrick_Chong
Patrick_Chong

Reputation: 534

How can I use MagicMock to mock an argument and test that my variable is set correctly?

I have the following function on_packet():

 class PacketContext:
    def __init__(self, capture_tstamp=None):
        self.capture_tstamp = capture_tstamp

 class Subparser(): 
    def __init__(self):
        self.subparsers = {}
        self.context = PacketContext()
    
    def parse_er_data(self, bytes_data): 
       parent_file_name = os.path.basename(self.filename or '')
       ....

    def on_packet(self, packet):
        self.context.capture_tstamp = packet.capture_timestamp
        self.parse_er_data(packet.payload)

I want to used MagicMock to mock packet, to test that self.context.capture_tstamp is being set correctly. Here is my test function:

class TestTSE(Subparser, ExchangeTest):
    name = 'TSE'
    data_group = 'equities'
    default_subparser = TSEparser

    def __init__(self, *argv, **kwargs):
        Subparser.__init__(self)
        ExchangeTest.__init__(self, *argv, **kwargs)


    def test_receive_timestamp(self):
        packet = MagicMock(capture_timestamp=123456)
        self.on_packet(packet)
        assert self.context.capture_tstamp == 123456

But I know the self.on_packet(packet) is not correct, because self is referring to a TestTSE object.

I am getting the following error:

self = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>

    def test_receive_timestamp(self):
        """
        test receive_timestamp is passed down correctly from PacketContext to on_packet()
        """
        packet = MagicMock(capture_timestamp=123456)
>       self.on_packet(packet)

tests/unit/exchanges/tse/test_quote_write.py:86: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
exchanges/impl/tse/mixins.py:63: in on_packet
    self.parse_er_data(packet.payload)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>, bytes_data = <MagicMock name='mock.payload' id='139811452485008'>

    def parse_er_data(self, bytes_data):
        """Maps current's file identifier with proper subparser's instance.
    
        Parameters
        ----------
        data: str
            Chunk of the data from file
        """
        # file being parsed
>       parent_file_name = os.path.basename(self.filename or '')
E       AttributeError: 'TestTSE' object has no attribute 'filename'

exchanges/impl/tse/mixins.py:51: AttributeError

Upvotes: 0

Views: 54

Answers (0)

Related Questions