如果出现AssertionError

时间:2019-07-08 15:19:51

标签: python python-3.x pytest assertion

我正在测试一个函数,其主要目的是将文件定位到该函数的参数接收的文件夹中。为此,我在根文件夹中创建了一个空文件,并测试了一些不同的路径参数。更明确地说,这是一个示例:

alocate_file('folder1','folder2','folder3', 'file.txt')

此行将导致此分配:

root / Downloads / folder1 / folder2 / folder3 / file.txt

我的函数的一些额外特征:Downloads文件夹是隐式的,它接收一个作为参数的列表,并假定列表中的最后一个字符串是文件。

我的问题

测试此功能后,将删除空文件(仅出于测试目的而创建)以及该功能创建的所有文件夹。这是在断言后的 之后使用shutil.rmtree完成的,这就是问题所在。 测试失败时,它会引发 AssertionError ,并且这些文件夹和文件不会被删除,因为未执行assert后的代码。这也破坏了其他测试,因为我对所有它们使用相同名称的文件和文件夹。然后,我必须手动删除所有这些文件才能再次正确测试。

我考虑使用固定装置,但我认为这不是一个好的解决方案,因为正如我所说,它可以测试不同的路径创建,但它没有通用的情况。我将必须为每个测试创建单独的夹具,这似乎并不是最好的方法。

这是我的一个存在此问题的测试:

def test_alocate_file_three_level_path(root_path):
    # creates files in root
    file_path1 = os.path.join(root_path, 'test1.pdf')
    Path(file_path1).touch()
    # creates path for test
    test_path = os.path.join(root_path, 'Downloads', 'path1', 'path2','path3','test1.pdf')
    # function alocate the file to folders
    func_aux.alocate_file('path1', 'path2', 'path3', 'test1.pdf')
    # check if the file is there
    assert os.path.isfile(test_path) == True
    # remove the created file and folders
    remove_path = os.path.join(root_path, 'Downloads', 'path1')
    shutil.rmtree(remove_path)

我想知道是否可以保证删除我为测试目的创建的所有文件夹和文件的唯一方法是针对每个测试使用especific固定装置,还是我可以始终执行的方法断言后的代码即使具有AssertionError

2 个答案:

答案 0 :(得分:1)

按照@hoefling的建议,我实现了一个创建临时目录的装置。修改我在帖子中提供的代码,如下所示:

@pytest.fixture(scope="module")
def temp_dir(root_path):
    down_path = os.path.join(root_path, 'Downloads', 'temp_dir')
    os.makedirs(down_path)
    yield down_path
    shutil.rmtree(down_path)


def test_alocate_file_three_level_path(root_path, temp_dir):
    # creates files in root
    file_path1 = os.path.join(root_path, 'test1.pdf')
    Path(file_path1).touch()
    # creates path for test
    test_path = os.path.join(temp_dir, 'path1', 'path2','path3','test1.pdf')
    # function alocate the file to folders
    func_aux.alocate_file('temp_dir', 'path1', 'path2', 'path3', 'test1.pdf')
    # check if the file is there
    assert os.path.isfile(test_path) == True

此保证在测试结束时删除了所有辅助文件。对于那些不了解发生了什么的人,执行夹具直到收益。之后,测试将获得其价值并发挥作用。 AssertionError 的独立变量,当测试结束时,它返回到Fixture并在yield之后运行代码。

答案 1 :(得分:0)

您可以使用一个简单的try... except块来管理此问题,因为如果条件为False,assert会引发AssertionError:

x = 1

try:
    assert x == 0
    print("x is equal to 0")
except AssertionError:
    print("x is not equal to 0")
finally:
    print("always run")

但是,正如@roganjosh所提到的,在这里使用简单的if else块似乎更加合乎逻辑...

相关问题