python 我如何解决我在unittesting中创建的归档在我运行测试之前被删除的问题

5jvtdoz2  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(101)

我有下面的单元测试代码:

class TestBackup(unittest.TestCase):
    def setUp(self):
        # Create a temporary directory for the test files
        self.temp_dir = tempfile.mkdtemp()
        self.output_dir = os.path.join(self.temp_dir, 'output')
        os.makedirs(self.output_dir)

        # Create a tar archive file for the test
        self.tar_file = os.path.join(self.temp_dir, 'test.tar.gz')
        tar = tarfile.open(self.tar_file, mode='w:gz')
        tar.add(__file__, arcname='test.py')

        # Add two fake files to the tar archive

        ....

        tar.close()

    def test_check_if_tar_file(self):
        # Test with a valid tar archive file
        check_if_tar_file(self.tar_file)

        # Test with a non-existent file
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file('nonexistent.tar.gz')
        self.assertEqual(str(cm.exception), "Error: File nonexistent.tar.gz does not exist or is not a regular file")

        # Test with a file that exists but is not a tar archive file
        with open(os.path.join(self.temp_dir, 'not_a_tar.txt'), 'w') as f:
            f.write('test')
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file(os.path.join(self.temp_dir, 'not_a_tar.txt'))
        self.assertEqual(str(cm.exception), "Error: File not_a_tar.txt is not a tar archive file")

        # Test with a file that exists but the user does not have read permissions
        os.chmod(self.tar_file, 0o000)
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file(self.tar_file)
        self.assertEqual(str(cm.exception), "Error: Permission denied for file test.tar.gz")

    ....

    def tearDown(self):
        # Delete the temporary directory and its contents
        shutil.rmtree(self.temp_dir)

if __name__ == '__main__':
    unittest.main()

我收到的错误是No such file or directory: 'test.tar.gz'
我检查过了,归档文件已经被正确地创建并存储在class属性中。我是单元测试的新手,但是我知道在我运行测试之前文件已经被删除了。
我做错了什么?

e5nqia27

e5nqia271#

很难准确地说出你在问什么,因为你的代码样本是incomplete,包含一个堆栈跟踪也会很有帮助。
也许问题出在你的check_if_tar_file()函数上,当我试图重新创建它时,你的测试工作正常,我在Ubuntu 20.04上用Python 3.10运行了这个函数。

import os
import shutil
import tarfile
import tempfile
import unittest
from pathlib import Path

def check_if_tar_file(filename: str):
    filepath = Path(filename)
    try:
        tarfile.open(filename)
    except FileNotFoundError:
        raise ValueError(f"Error: File {filepath.name} does not exist or is "
                         f"not a regular file")
    except tarfile.ReadError:
        raise ValueError(f"Error: File {filepath.name} is not a tar archive "
                         f"file")
    except PermissionError:
        raise ValueError(f"Error: Permission denied for file {filepath.name}")

class TestBackup(unittest.TestCase):
    def setUp(self):
        # Create a temporary directory for the test files
        self.temp_dir = tempfile.mkdtemp()
        self.output_dir = os.path.join(self.temp_dir, 'output')
        os.makedirs(self.output_dir)

        # Create a tar archive file for the test
        self.tar_file = os.path.join(self.temp_dir, 'test.tar.gz')
        tar = tarfile.open(self.tar_file, mode='w:gz')
        tar.add(__file__, arcname='test.py')

        # TODO: Add two fake files to the tar archive

        tar.close()

    def test_check_if_tar_file(self):
        # Test with a valid tar archive file
        check_if_tar_file(self.tar_file)

        # Test with a non-existent file
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file('nonexistent.tar.gz')
        self.assertEqual(str(cm.exception), "Error: File nonexistent.tar.gz does not exist or is not a regular file")

        # Test with a file that exists but is not a tar archive file
        with open(os.path.join(self.temp_dir, 'not_a_tar.txt'), 'w') as f:
            f.write('test')
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file(os.path.join(self.temp_dir, 'not_a_tar.txt'))
        self.assertEqual(str(cm.exception), "Error: File not_a_tar.txt is not a tar archive file")

        # Test with a file that exists but the user does not have read permissions
        os.chmod(self.tar_file, 0o000)
        with self.assertRaises(ValueError) as cm:
            check_if_tar_file(self.tar_file)
        self.assertEqual(str(cm.exception), "Error: Permission denied for file test.tar.gz")

    def tearDown(self):
        # Delete the temporary directory and its contents
        shutil.rmtree(self.temp_dir)

if __name__ == '__main__':
    unittest.main()

相关问题