简体   繁体   中英

Using pytest to ensure a file is created and written to

I'm using pytest and want to test that a function writes some content to a file. So I have writer.py which includes:

MY_DIR = '/my/path/'

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

I want to test /my/path/myfile.txt is created and has the correct content:

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'

But I'm stuck with how to do this. Everything I try, such as something like:

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

Generates errors which lead me to suspect I'm not understanding or using tmpdir correctly.

How should I test this? (If the rest of how I'm using pytest is also awful, feel free to tell me that too!)

I've got a test to work by altering the function I'm testing so that it accepts a path to write to. This makes it easier to test. So writer.py is:

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))

And the test:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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