3

A unit tests passes in a list of objects into a method. The method uses jsonpickle.encode on the objects.

Well and good, but what to do when unit test sends list of mocked objects and runs into infinite recursion?

Here is an example of the code:

import jsonpickle
from mock.mock import MagicMock


class Foo(object):
    def __init__(self):
        pass


def encodeFoos(list_of_foos):
    [jsonpickle.encode(x) for x in list_of_foos]


def works():
    list_of_foos = [Foo()]
    encodeFoos(list_of_foos=list_of_foos)


def unit_test_doesnt_work():
    list_of_mock_foos = [MagicMock()]
    encodeFoos(list_of_mock_foos)

unit_test_doesnt_work()

The error that is thrown is: RuntimeError: maximum recursion depth exceeded since jsonpickle apparently travels down an infinite tree in the mocked object.

how can I keep the production code as is (encodeFoos) and not run into maximum recursion when passing in mock objects?

Thanks!

Nahum Timerman
  • 151
  • 1
  • 9
  • 1
    `jsonpickle.encode(mock_obj, unpicklable=False)`? – Gang Aug 30 '18 at 00:39
  • 1
    or `jsonpickle.encode(mock.mock.MagicMock(), max_depth=2)`? – Gang Aug 30 '18 at 00:44
  • 1
    I think your suggestion max depth parameter is useful, and I could use it to solve the issue. However, ideally I would want to make a change just in the test code. In my case, I decided on creating real version of the object instead of using mock. – Nahum Timerman Aug 30 '18 at 06:54
  • 1
    I believe it is a bug of `jsonpickle` when encode a deep, deep object. I am surprised that it is so popular based on github feedback. It is worth to file a bug report to see what they will respond. – Gang Aug 30 '18 at 22:55

0 Answers0