Unittesing stringified JSON
<p>I have a function that looks something like</p>

<pre><code>def function_to_test(data):
    data = some_operations_inline(data)
    return stringify_json(data)
</code></pre>

<p>where</p>

<pre><code>def stringify_json(data):
    return json.dumps(data, encoding='utf-8')
</code></pre>

<p>I want to unit test <code>function_to_test</code> (with <code>tox</code> + <code>nose</code>). The problem is that ordering of the elements inside the string changes with the <code>PYTHONHASHSEED</code>. </p>

<p>I tried to change the function to:</p>

<pre><code>def stringify_json(data):
    sorted_dict = OrderedDict([[k, v] for k, v in sorted(data.items())])
    return json.dumps(sorted_dict, encoding='utf-8')
</code></pre>

<p>But this does not help if the <code>data</code> contains another <code>dict</code>.</p>

<p>How do I test it? The obvious thing would be to do compare the json values, and not their string versions:</p>

<pre><code>self.assertEqual(
    json.loads(expected),
    json.loads(computed)
)
</code></pre>

<p>Would that be acceptable? Even if I am not testing the real function output? I guess we can assume that <code>json.dumps</code> was already tested.
Note: I wrapped <code>json.dumps</code> so I could make sure that all the dumps are done consistently. </p>