【问题标题】:How to resolve "ValueError: Empty module name"?如何解决“ValueError:空模块名称”?
【发布时间】:2019-01-06 08:20:39
【问题描述】:

在我的UnitTest 目录中,我有两个文件,mymath.pytest_mymath.py

mymath.py文件:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(numerator, denominator):
    return float(numerator) / denominator

test_mymath.py 文件是:

import mymath
import unittest

class TestAdd(unittest.TestCase):
    """
    Test the add function from the mymath library
    """

    def test_add_integer(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(1, 2)
        self.assertEqual(result, 3)

    def test_add_floats(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(10.5, 2)
        self.assertEqual(result, 12.5)

    def test_add_strings(self):
        """
        Test that the addition of two strings returns the two strings as one
        concatenated string
        """
        result = mymath.add('abc', 'def')
        self.assertEqual(result, 'abcdef')

if __name__ == '__main__':
    unittest.main()

当我运行命令时

python .\test_mymath.py

我得到了结果

在 0.000 秒内运行 3 次测试

好的

但是当我尝试使用

运行测试时

python -m unittest .\test_mymath.py

我收到了错误

ValueError:空模块名称

追溯:

文件夹结构:

我正在关注这个article

我的python版本是Python 3.6.6,我在本地机器上使用的是windows 10。

【问题讨论】:

标签: python python-unittest


【解决方案1】:

使用python -m unittest test_mymath

【讨论】:

  • 根据Python 3.6 documentation,@shams-nahid 尝试做的是有效的:“测试模块也可以通过文件路径指定:python -m unittest tests/test_something.py”。那么这是 Python 中的一个错误,还是文档不正确?
  • 尝试将(空的)init.py 添加到包含测试的文件夹中。即使在 python3.3+ 中不需要它,但在 python3.7+ 中对我来说仍然需要它......
  • 注意:当测试位于子文件夹中时,删除./(而不是完整路径)也有效。例如python -m unittest ./tests/test_something.py有效,而python -m unittest tests/test_something.py有效有效。
【解决方案2】:

你几乎明白了。而不是:

python -m unittest ./test_mymath.py

不要添加./,所以你现在有:

python -m unittest test_mymath.py

您的单元测试现在应该运行了。

【讨论】:

  • 我在 github 操作中遇到了这个错误,我需要能够将./ 作为路径的一部分。还有其他解决方法吗?
  • @szeitlin 你能引用你得到的确切错误吗?
  • ImportError:导入测试模块失败:test_gopher_changes Traceback(最近一次调用):文件“/opt/hostedtoolcache/Python/3.7.10/x64/lib/python3.7/unittest/loader. py”,第 154 行,在 loadTestsFromName 模块 = __import__(module_name) 文件“/home/runner/work/data-lake/data-lake/automated/gopher_changes/test_gopher_changes.py”,第 1 行,在 中来自 gopher_changes 导入更新程序 ModuleNotFoundError:没有名为“gopher_changes”的模块
  • FWIW 我通过使用python -m unittest discover更改到测试所在的目录来解决这个问题
  • Windows powershell(出于某种原因)在按下Tab后添加前导./