【问题标题】:"No tests were found" when running unittest.main()运行 unittest.main() 时“未找到测试”
【发布时间】:2017-10-05 11:13:25
【问题描述】:

我有一个测试文件和一个主模块文件,其中有一个我正在测试的函数。在我的测试文件末尾,我有unittest.main() 来运行单元测试。但是,当我运行测试文件时,即使我的文件中有 2 个单元测试(参见下面的屏幕截图和最后的源代码),控制台也会显示 "No tests were found" 。 当我:

(1) unittest.main() 括在if __name__ == "__main__" (切题:我有点理解这个子句是如何工作的,但在这种情况下,unittest.main() 模块在有 if 子句时正常运行,而不是在根本没有附加条件时,这对我来说毫无意义),或者

(2) 当我在 Spyder 中运行我的测试程序时(我目前正在使用 Pycharm)

因此,我不太确定这是我的 IDE 或我的代码所特有的问题。我已经尝试过这个问答中的recommended fix,但没有一个奏效。如果您对我应该做什么/配置以使unittest.main 正常运行有任何想法,我将不胜感激!


供您参考,这是我程序中的两个文件;我的测试文件没有返回任何测试,而不是我为其编写的 2 个测试。

---主文件:city_functions.py---

def print_city_country(city, country, population=""):
    """Print 'city, country' from input city and country"""
    if population:
        formatted_city_country = city + ", " + country + " - population " + str(population)
    else:
        formatted_city_country = city + ", " + country
    return formatted_city_country

---测试文件:test_cities.py---

import unittest
from city_functions import print_city_country


class TestCaseCityCountry(unittest.TestCase):
    """Test function city_country from city_functions module"""

    def test_city_country_pair(self):
        """Test for names like Santiago, Chile without population input"""
        formatted_city_country = print_city_country("Santiago", "Chile")
        self.assertEqual(formatted_city_country, "Santiago, Chile")

    def test_city_country_population(self):
        """Test for names like Santiago, Chile, 5000000"""
        formatted_city_country_population = print_city_country("Santiago", "Chile", 5000000)
        self.assertEqual(formatted_city_country_population, "Santiago, Chile - population 5000000")


unittest.main()

【问题讨论】:

  • 如何在 Pycharm 中运行测试?
  • 完美的问题!我使用了 Ctrl + Shift + F10 (就像 tutorial 显示的那样),但我只是返回并使用 Alt + Shift + F10 (Pycharm 的通用运行热键),它起作用了(尽管没有你看到的花哨的 Pycharm 测试状态我的屏幕截图的左侧,只是控制台结果)。你知道为什么会有这样的差异吗?我查找了 Ctrl + Shift + 10 但几乎没有找到它的参考,只是备忘单说它代表“从编辑器运行上下文配置”,不管是什么意思。
  • 我将我的应用程序文件和测试分成两个不同的同级文件夹。然后我可以右键单击测试文件夹并选择Run Notestests in tests。 (其中 tests 是我的测试文件夹的名称)。
  • 顺便说一句,严格来说,您的文件中根本不应该包含unittest.main()。只是测试本身,然后像这样运行文件:python -m unittest myfile.py
  • @YamMarcovic 感谢您的提示! Pycharm也有人用类似的想法回答了我的问题,并解释了Alt + Shift + F10Ctrl + Shift + F10的区别(intellij-support.jetbrains.com/hc/en-us/community/posts/…

标签: python python-3.x unit-testing pycharm


【解决方案1】:

作为使用 Pycharm 的初学者,Don Kirkby 的 answer 对我帮助最大。

至少对我来说,解决方案是从文件中完全删除unittest.main()。看来 Pycharm 在运行测试时默认使用命令 python -m unittest 并且 unittest.main() 方法会弄乱语法。

我希望这可以帮助遇到同样问题的其他人。

【讨论】:

    【解决方案2】:

    有两种方法可以启动unittest 测试。一种是使用您正在使用的unittest.main() 方法,但我总是使用command-line interfacepython -m unittest discover 命令将在一堆文件中查找测试并一起运行它们。

    我不确定为什么unittest.main() 不适合你,但我还是建议使用其他方法。

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2019-07-29
      • 1970-01-01
      • 2012-05-23
      • 2021-02-15
      • 2011-01-20
      相关资源
      最近更新 更多