如何解决“ ValueError:空模块名称”?

Sha*_*hid 2 python python-unittest

在我的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
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

当我运行命令

python .\test_mymath.py

我得到了结果

在0.000秒内进行了3次测试

但是当我尝试使用

python -m unittest .\test_mymath.py

我得到了错误

ValueError:空模块名称

追溯: 完整回溯

资料夹结构: 在此处输入图片说明

我正在关注这篇文章

我的python版本是Python 3.6.6,我在本地计算机上使用Windows 10。

ama*_*anb 5

使用 python -m unittest test_mymath

  • 根据 [Python 3.6 文档](https://docs.python.org/3.6/library/unittest.html#command-line-interface),@shams-nahid 尝试做的事情是有效的:“测试模块可以是也由文件路径指定:“python -munittesttests/test_something.py”。那么这是Python 中的一个错误,还是文档不正确? (3认同)
  • 注意:当测试位于子文件夹中时,仅删除“./”(而不是完整路径)也有效。例如,“python -m unittest ./tests/test_something.py”**不起作用**,而“python -m unittest测试/test_something.py”****起作用。 (2认同)

Cal*_*iah 5

你几乎明白了。代替:

python -m unittest ./test_mymath.py
Run Code Online (Sandbox Code Playgroud)

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

python -m unittest test_mymath.py
Run Code Online (Sandbox Code Playgroud)

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