使用pytest确保创建和写入文件

时间:2017-06-19 11:35:32

标签: python pytest

我正在使用pytest并希望测试函数是否将某些内容写入文件。所以我writer.py包括:

MY_DIR = '/my/path/'

def my_function():
    with open('{}myfile.txt'.format(MY_DIR), 'w+') as file:
        file.write('Hello')
        file.close()

我想测试/my/path/myfile.txt是否已创建且内容正确无误:

import writer

class TestFile(object):

    def setup_method(self, tmpdir):
        self.orig_my_dir = writer.MY_DIR
        writer.MY_DIR = tmpdir

    def teardown_method(self):
        writer.MY_DIR = self.orig_my_dir

    def test_my_function(self):
        writer.my_function()

        # Test the file is created and contains 'Hello'

但我仍然坚持如何做到这一点。我尝试过的所有东西,例如:

        import os
        assert os.path.isfile('{}myfile.txt'.format(writer.MYDIR))

产生错误,导致我怀疑我没有正确理解或使用tmpdir

我该如何测试? (如果我使用pytest的其余部分也很糟糕,请随时告诉我!)

1 个答案:

答案 0 :(得分:1)

我通过改变我测试的功能来进行测试,以便它接受写入的路径。这使得测试更容易。所以writer.py是:

MY_DIR = '/my/path/'

def my_function(my_path):
    # This currently assumes the path to the file exists.
    with open(my_path, 'w+') as file:
        file.write('Hello')

my_function(my_path='{}myfile.txt'.format(MY_DIR))

测试:

import writer

class TestFile(object):

    def test_my_function(self, tmpdir):

        test_path = tmpdir.join('/a/path/testfile.txt')

        writer.my_function(my_path=test_path)

        assert test_path.read() == 'Hello'