【pytest】内置 fixtures 之 tmpdir:创建临时文件

内置 fixtures 之 tmpdir:

tmpdir 的作用是:在本地生成临时文件夹,并返回文件对象;

代码演示:

先写个测试用例,调用 tmpdir,执行一下看看:

class TestDemoA:    
    def test_A_001(self, tmpdir):
        time.sleep(2)
        print('\n',tmpdir)

if __name__ == '__main__':
    pytest.main(['-s'])
# 执行结果:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 C:\Users\MyPC\AppData\Local\Temp\pytest-of-MyPC\pytest-0\test_A_0010
PASSED

============================== 2 passed in 3.04s ==============================

Process finished with exit code 0

可以看到控制台有打印出生成的临时文件夹的目录,并且电脑本地也生成了文件夹!

然后我们发现临时文件目录是有规律的,改下代码多执行几次看看:

class TestDemoA:    
    def test_A_001(self, tmpdir):
        time.sleep(2)
        print('\n',tmpdir)

    def test_A_002(self, tmpdir):
        time.sleep(2)
        print('\n',tmpdir)


if __name__ == '__main__':
    pytest.main(['-s'])
# 执行结果:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 C:\Users\MyPC\AppData\Local\Temp\pytest-of-MyPC\pytest-8\test_A_0010
PASSED
test_Z.py::TestDemoA::test_A_002 
 C:\Users\MyPC\AppData\Local\Temp\pytest-of-MyPC\pytest-8\test_A_0020
PASSED

============================== 2 passed in 4.04s ==============================

Process finished with exit code 0

总结说明:

通过几次执行我们可以看到,每一次完成的测试活动 tmpdir 会创建一个 pytest-x 的临时目录,并且这个临时目录最多保存3个,超过3个后会删除最老的临时目录,然后在这个测试活动中, tmpdir 每被调用1次就会在 pytest-x 下面生成1个子目录,子目录的文件名是根据测试用例的名称决定;

tmpdir 提供的方法:

    def mkdir(self, *args):
        """ 创建并返回与给定参数拼接的目录;
        """    

    def samefile(self, other):
        """ 对比tmpdir的目录和给定的目录是否相同,相同返回 True,否则返回 False;
        """

    def remove(self, rec=1, ignore_errors=False):
        """ 删除文件或目录(如果rec=1,则删除目录树)。如果ignore_errors为真,则删除目录时的错误将被忽略;
        """

    def computehash(self, hashtype="md5", chunksize=524288):
        """ 返回此文件的哈希值的十六进制摘要。 """

    def dirpath(self, *args, **kwargs):
        """ 返回与所有给定参数拼接的目录路径;
        """

    def join(self, *args, **kwargs):
        """ 返回与所有给定参数拼接的目录路径; 和上面的略有区别,详见源码;
        """

    def open(self, mode='r', ensure=False, encoding=None):
        """ 以给定模式返回打开的文件,如果ensure为True,则在需要时创建父目录;
        """

    def listdir(self, fil=None, sort=None):
        """ 列出目录内容,可能由给定的过滤函数过滤并排序;
        """

    def size(self):
        """ 返回基础文件对象的大小;
        """

    def mtime(self):
        """ 返回路径的最后修改时间;
        """

    def copy(self, target, mode=False, stat=False):
        """ 复制路径到目标;
            如果mode为True,则复制 “文件权限” 到目标;
            如果stat为True,则复制 “权限、上次修改时间、上次访问时间”到目标;
        """

    def rename(self, target):
        """ 将此路径重命名为给定参数; 
        """

    def write_binary(self, data, ensure=False):
        """ write binary data into path.   If ensure is True create
        missing parent directories.
        """

    def write_text(self, data, encoding, ensure=False):
        """ write text data into path using the specified encoding.
        If ensure is True create missing parent directories.
        """

    def write(self, data, mode='w', ensure=False):
        """ write data into path.   If ensure is True create
        missing parent directories.
        """

    def ensure(self, *args, **kwargs):
        """ ensure that an args-joined path exists (by default as
            a file). if you specify a keyword argument 'dir=True'
            then the path is forced to be a directory path.
        """

    def stat(self, raising=True):
        """ Return an os.stat() tuple. """

    def lstat(self):
        """ Return an os.lstat() tuple. """

    def setmtime(self, mtime=None):
        """ set modification time for the given path.  if 'mtime' is None
        (the default) then the file's mtime is set to current time.

        Note that the resolution for 'mtime' is platform dependent.
        """

    def chdir(self):
        """ change directory to self and return old current directory """

    def realpath(self):
        """ return a new path which contains no symbolic links."""

    def atime(self):
        """ return last access time of the path. """

    def chmod(self, mode, rec=0):
        """ change permissions to the given mode. If mode is an
            integer it directly encodes the os-specific modes.
            if rec is True perform recursively.
        """

    def pypkgpath(self):
        """ return the Python package path by looking for the last
        directory upwards which still contains an __init__.py.
        Return None if a pkgpath can not be determined.
        """

    def pyimport(self, modname=None, ensuresyspath=True):
        """ return path as an imported python module.

        If modname is None, look for the containing package
        and construct an according module name.
        The module will be put/looked up in sys.modules.
        if ensuresyspath is True then the root dir for importing
        the file (taking __init__.py files into account) will
        be prepended to sys.path if it isn't there already.
        If ensuresyspath=="append" the root dir will be appended
        if it isn't already contained in sys.path.
        if ensuresyspath is False no modification of syspath happens.
        """

    def sysexec(self, *argv, **popen_opts):
        """ return stdout text from executing a system child process,
            where the 'self' path points to executable.
            The process is directly invoked and not through a system shell.
        """

    def sysfind(cls, name, checker=None, paths=None):
        """ return a path object found by looking at the systems
            underlying PATH specification. If the checker is not None
            it will be invoked to filter matching paths.  If a binary
            cannot be found, None is returned
            Note: This is probably not working on plain win32 systems
            but may work on cygwin.
        """

    def get_temproot(cls):
        """ return the system's temporary directory
            (where tempfiles are usually created in)
        """

    def mkdtemp(cls, rootdir=None):
        """ return a Path object pointing to a fresh new temporary directory
            (which we created ourself).
        """

    def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3,
                          lock_timeout = 172800):   # two days
        """ return unique directory with a number greater than the current
            maximum one.  The number is assumed to start directly after prefix.
            if keep is true directories with a number less than (maxnum-keep)
            will be removed.
        """

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值