gpt4 book ai didi

python-3.x - Pandas 和单元测试之间的冲突?

转载 作者:行者123 更新时间:2023-12-03 14:44:49 27 4
gpt4 key购买 nike

考虑以下代码块(在 Jupyter 笔记本中开发),预计 AssertionError被提出是因为 UserWarning未触发:

%%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)

对于那些不熟悉 jupyter notebooks 的人,第一行只是将以下所有行导出到指定的文件中。

现在,如果我执行命令:
python3 tests.py

从终端(我在 Ubuntu 14.04 上使用 Python 3.5.1),我得到一个 Runtime Error - 堆栈跟踪如下:
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)

显然结果并不如预期。但是,我注意到以下任一选项都可以获得预期的结果。
  • %%writefile ... 注释掉第一行并使用 Jupyter 笔记本(使用相同的 python 解释器)运行代码片段。
  • 注释掉 import pandas as pd行并使用先前给出的命令从终端运行。

  • 有谁明白这里发生了什么?

    供引用, case.py 中的相关行在 unittest模块是
    for v in sys.modules.values():
    if getattr(v, '__warningregistry__', None):
    v.__warningregistry__ = {}

    这似乎是良性代码(我也认为它已经过足够的测试,可以说它不是问题的根源)。

    最佳答案

    此错误已提交至 Python's bug tracker .

    The problem is in the iteration over sys.modules in unittest.case._AssertWarnsContext.__enter__() and accessing every module's __warningregistry__ attribute. On this access, the module-like objects may perform arbitrary actions including importing of further modules which extends sys.modules.



    sys.modules 是一个将模块名称映射到已加载模块的字典。

    这个问题很难重现,因为有“ something platform dependent”关于测试运行者如何排序测试。

    关于python-3.x - Pandas 和单元测试之间的冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38754889/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com