pytest(三十九)--内置request读取项目的根目录 rootdir

前言

写自动化测试项目的时候,经常要用到配置文件,比如读取数据库相关的配置,希望单独放到config配置文件,方便维护。

pytest的内置fixture可以获取到配置相关的信息,request.config.rootdir 用于获取项目的根目录。

config配置文件

在django下操作的大概步骤:New project——>new python package (如,testcase、config)、conftest.py;

在项目下新建一个config文件,相关配置信息用yaml文件维护数据

在conftest.py下写读取配置文件的fixture,这里我设置为autouse=True 主要是为了查看打印读取到的目录

import pytest
import os
import yaml


@pytest.fixture(scope="session",autouse=True)
def dbinfo(request):
    dbfile=os.path.join(request.config.rootdir,
                        "config",
                        "dbinfo.yml")
    print("dbinfo file path:%s"%dbfile)
    with open(dbfile) as f:
        db_config=yaml.load(f.read(),Loader=yaml.SafeLoader)
    print(db_config)
    return db_config

 os.path.join('root','test','a.txt') #将目录和文件名合成一个路径 即root/test/a.txt

 rootdir读取

打开cmd命令行,在项目的根目录运行用例(即project工程下,也就是pytest0102目录下)

pytest -s

#test_1.py
def test1():
    print()

 这时候可以看到读取到的配置文件地址:D:\Python0811\pytest0102\config\dbinfo.yml

注意:项目的根目录即工程下,切换都其它目录(如testcase)下,执行会报错;

 这个时候就会出现报错:No such file or directory

'D:\Python0811\pytest0102\testcase\config\dbinfo.yml'

因为此时的项目跟目录就变成了rootdir:D:\Python0811\pytest0102\testcase

接下来我们需要解决的问题是,不管在哪个目录运行,它的项目根目录应该都是我们的工程目录D:\Python0811\pytest0102

pytest.ini

pytest运行用例的时候,项目的rootdir,当没有pytest.ini配置文件的时候回根据conftest.py找到它的根目录

由于前面没有用到pytest.ini配置文件,导致不同目录运行用例的rootdir不一样。

当项目下存在pytest.ini配置文件的时候,会认为pytest.ini所在的目录是rootdir目录,所以我们一般会把pytest.ini配置文件放到项目的根目录。

如果里面没有内容,放个空的也行

 这时候不管在哪个目录运行用例都不会有问题了

 pytest的配置文件除了pytest.ini,还有tox.ini和setup.cfg也可以当配置文件。

posted on 2021-01-03 15:28  星空6  阅读(523)  评论(0编辑  收藏  举报

导航