如何使用 __enter__ / __exit__ 方法对类进行单元测试?

Kal*_*ape 5 python unit-testing with-statement python-unittest

我是单元测试的新手,我试图找到一种方法来测试with关键字在我的对象中是否正常工作。

在这种情况下,我的对象有一个__enter__方法可以创建一个临时目录和__exit__应该销毁它的方法。(它还有一个do_stuff方法,我只包含用于测试写入临时目录的方法。)

我不完全确定如何进行测试。我已经检查了该unittest模块,之前甚至为基本方法编写了一些测试,但我不确定在这种情况下最好的方法是什么......或者这是否有意义。无论如何,这是我的对象代码:

import shutil
import tempfile
import os
import glob

class MyObj(object):
    def __enter__(self):
        self.tmpdir = tempfile.mkdtemp(dir='.')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        shutil.rmtree(self.tmpdir)

    def do_stuff(self):
        new = os.path.join(self.tmpdir, 'new_file.txt')
        with open(new, 'w') as nf:
            nf.write('testing')
        print(glob.glob(self.tmpdir + '/*'))

myobj = MyObj()
with myobj as x:
    x.do_stuff()
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 4

如果您想测试MyObjwithwith语句是否有效,以及它创建/删除临时目录,请with在测试方法中使用该语句:

import unittest


class TestMyObj(unittest.TestCase):

    def test_myobj_with_statement__should_create_delete_temp_directory(self):
        with MyObj() as obj:
            # Directory is created
            self.assertTrue(os.path.isdir(obj.tmpdir))
        # Directory is gone
        self.assertFalse(os.path.isdir(obj.tmpdir))

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)