Conflict between Pandas and Unittest? : <p>Consider the following block of code (developed inside a Jupyter notebook), for which it is expected that an <code>AssertionError</code> is raised because a <code>UserWarning</code> is not triggered:</p>

<pre><code>%%writefile Game/tests/tests.py
import unittest
import pandas as pd

class TestGame(unittest.TestCase):
    def test_getters(self):
        print('Just before the critical line.')
        with self.assertWarns(UserWarning):
            print('Just testing...')

suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)
</code></pre>

<p>For those unfamiliar with jupyter notebooks, the first line simply exports all following lines into the specified file.</p>

<p>Now if I execute the command:</p>

<pre><code>python3 tests.py
</code></pre>

<p>from the terminal (I am using Python 3.5.1 on Ubuntu 14.04), I get a <code>Runtime Error</code> - the stack trace follows:</p>

<pre><code>Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 8, in test_getters
    with self.assertWarns(UserWarning):
  File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
    for v in sys.modules.values():
RuntimeError: dictionary changed size during iteration

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)
</code></pre>

<p>Obviously the results are not as expected. However, I notice that either of the following options gets the expected results.</p>

<ol>
<li>Commenting out the first line with <code>%%writefile ...</code> and running the code snippet with the Jupyter notebook (which uses the same python interpreter).</li>
<li>Commenting out the <code>import pandas as pd</code> line and running from terminal with the previously given command.</li>
</ol>

<p>Does anyone understand what's going on here?</p>

<p>For reference, the relevant lines in <code>case.py</code> in the <code>unittest</code> module are</p>

<pre><code>for v in sys.modules.values():
    if getattr(v, '__warningregistry__', None):
        v.__warningregistry__ = {}
</code></pre>

<p>which would seem to be benign code (which I would also presume is tested enough to say that it's not the source of the problem).</p>
