如何 运行 在 python 中进行单元测试?

How to run unit tests in python?

我很难理解如何在 Python 的单元测试中使用断言。

原代码:

class A:
   def method(file):
       if file:
          <do something>
       else:
          raise Exception("file not found")

现在创建它的测试。假设我不想传递文件并对其进行测试。

t1 = A()
class Test(TestCase):
    def test_method_no_path(self):
         t1.method(' ') #passed no file
         <Now do what> ?? 
         self.assert ?? 
# tests/test_ex.py    
from os import path
from unittest import TestCase


class Error(Exception):
    pass


class FileChecker:
    def process_file(self, f_path: str):
        if path.exists(f_path) and path.isfile(f_path):
            # just an example
            return 'result'
        raise Error(f_path)


class TestFileChecker(TestCase):
    _CHECKER = FileChecker()

    def test_done(self):
        # check method result
        self.assertTrue(self._CHECKER.process_file('/tmp/1.txt') == 'result')

    def test_error(self):
        # check method exception
        with self.assertRaises(Error):
            self._CHECKER.process_file('/tmp/1.txt')

运行 我们的测试(nosetests tests/test_ex.py)。 test_done 失败,因为 /tmp/1.txt 文件不存在:

======================================================================
ERROR: test_done (tests.test_ex.TestFileChecker)

让我们创建一个文件(echo 'test' >> /tmp/1.txt)并运行再测试一次:

======================================================================
FAIL: test_error (tests.test_ex.TestFileChecker)

如您所见,test_done 工作正常,因为我们得到了预期的结果,但现在我们遇到了 test_error 的问题(因为 Error 没有被引发)。