![](/img/trans.png)
[英]Running a single test from unittest.TestCase via the command line
[英]Phantom tests after switching from unittest.TestCase to tf.test.TestCase
以下代碼:
class BoxListOpsTest(unittest.TestCase):
"""Tests for common bounding box operations."""
def test_area(self):
corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
exp_output = [200.0, 4.0]
boxes = box_list.BoxList(corners)
areas = box_list_ops.area(boxes)
with tf.Session() as sess:
areas_output = sess.run(areas)
np.testing.assert_allclose(areas_output, exp_output)
if __name__ == '__main__':
unittest.main()
被解釋為具有單個測試的測試用例:
.
----------------------------------------------------------------------
Ran 1 test in 0.471s
OK
但是,切換到tf.test.TestCase
:
class BoxListOpsTest(tf.test.TestCase):
"""Tests for common bounding box operations."""
def test_area(self):
corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
exp_output = [200.0, 4.0]
boxes = box_list.BoxList(corners)
areas = box_list_ops.area(boxes)
# with self.session() as sess:
with tf.Session() as sess:
areas_output = sess.run(areas)
np.testing.assert_allclose(areas_output, exp_output)
if __name__ == '__main__':
tf.test.main()
介紹一些第二個測試,它被跳過:
.s
----------------------------------------------------------------------
Ran 2 tests in 0.524s
OK (skipped=1)
第二次測試的起源是什么,我應該擔心嗎?
我正在使用 TensorFlow 1.13。
這是tf.test.TestCase.test_session
方法。 由於命名不吉利, unittest
將test_session
方法視為測試並將其添加到測試套件中。 為了防止將test_session
作為測試運行,Tensorflow 必須在內部跳過它,因此會導致“跳過”測試:
def test_session(self,
graph=None,
config=None,
use_gpu=False,
force_gpu=False):
if self.id().endswith(".test_session"):
self.skipTest("Not a test.")
通過使用--verbose
標志運行測試來驗證跳過的測試是test_session
。 您應該會看到與此類似的輸出:
...
test_session (BoxListOpsTest)
Use cached_session instead. (deprecated) ... skipped 'Not a test.'
盡管test_session
自 1.11 以來test_session
被棄用,應替換為cached_session
( 相關提交),但截至目前,它還沒有計划在 2.0 中刪除。 為了擺脫它,您可以對收集的測試應用自定義過濾器。
unittest
您可以定義自定義load_tests
函數:
test_cases = (BoxListOpsTest, )
def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
for test_class in test_cases:
tests = loader.loadTestsFromTestCase(test_class)
filtered_tests = [t for t in tests if not t.id().endswith('.test_session')]
suite.addTests(filtered_tests)
return suite
pytest
在conftest.py
添加一個自定義的pytest_collection_modifyitems
鈎子:
def pytest_collection_modifyitems(session, config, items):
items[:] = [item for item in items if item.name != 'test_session']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.