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

时间:2019-05-16 13:39:25

标签: python unit-testing oop temporary-files

我正在对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 个答案:

答案 0 :(得分:0)

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

  1. 实际上,我通过在CatalogCmp函数中调用self.temp_dir创建两次临时目录,并且在测试函数本身进行调用之前,在Actual_path变量创建过程中,这会为两个调用创建两个不同的目录,尽管这可能不是给定错误的直接原因,但这是错误的。因此,现在我仅在测试函数中创建一次temp目录,然后保存该变量并将其传递到其他位置。

  2. 还有一件错误的事情是,我正在测试的函数实际上接受了list变量,而不仅仅是产品名称。因此,也许正在测试的功能甚至没有生成任何输出。抱歉,我想这里肯定会有帮助,但是我不能在这里放所有代码。因此,当我尝试这样调用函数时:doom.GetCatalog(selftemp_dir,[product_name])。现在正在工作。但我想知道为什么该错误与捕获此错误无关。我将如何检查该函数是否被正确调用。