繁体   English   中英

无法在python单元测试代码中使用tempfile库生成的目录

[英]Not able to use the directories generated by tempfile library in python Unit testing Code

我是单元测试我的Python代码,我使用tempfile库创建一个名为temp_dir的临时目录,并将生成的输出文件保存在我的temp_dir中,然后我想将此输出与已存在的正确输出文件进行比较。

我有我的类,在它的设置方法中,我正在创建temp_dir,我将在拆卸方法中删除它,如下所示:

class PrimaryTest(unittest.TestCase):

  def setUp(self):
    self.temp_dir = tempfile.mkdtemp()

  def tearDown(self):
    shutil.rmtree(self.temp_dir)

现在,我想在我的测试函数中使用这个临时目录来保存由我的Binary中的函数生成的文件,我正在测试它。

以下是我使用上述代码的方法:

  def CatalogCmp(self, product_name, actual_file, expected_file):
    doom.getCatalog(self.temp_dir, product_name)
    actual = json.load(open(actual_file))
    expected = json.load(open(expected_file))
    self.assertEqual(actual, expected)

  def testCatalogImage(self):
    expected_path = os.path.join(‘path/testdata/doom’, ’product1.json')
    actual_path = os.path.join(self.temp_dir, ’product1.json')
    self.CatalogCmp(‘product1’, actual_path, expected_path)

我收到以下错误:

IOError: [Errno 2] No such file or directory: '/tmp/tmpGmv_ZR/product1.json'

以下行生成此错误:

actual = json.load(open(actual_file))

我得到了一些提示,这有助于我解决问题:

  1. 实际上,我通过在函数CatalogCmp中调用self.temp_dir并在test函数本身调用之前创建temp目录两次,在actual_path变量创建期间,这为两个调用创建了两个不同的目录,尽管这可能不是直接导致给定错误,但这是错误的。 所以现在我只在test函数中创建一次temp目录并保存变量并将其传递给其他地方。

  2. 还有一件事是错误的,我测试的函数实际上接受列表变量而不仅仅是产品名称。 因此,正在测试的功能可能甚至没有产生任何输出。 对不起,我觉得这里有人肯定有帮助,但我不能把所有的代码都放在这里。 所以当我尝试调用我的函数时:doom.GetCatalog(selftemp_dir,[product_name])。 它现在正在运作。 但我想知道为什么错误与捕获此错误无关。 我怎么会检查函数是否被正确调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM