内置request读取项目的根目录rootdir

写自动化测试项目的时候,经常要用到配置文件,比如读取数据库相关的配置,希望单独放到 config 配置为文件,方便维护。
pytest 的内置 fixture 可以获取到配置相关的信息,request.config.rootdir 用于获取项目的根目录。
 
config 配置文件
在项目下新建一个 config 文件,相关配置信息用 yaml 文件维护数据
 
 
在 conftest.py 下写读取配置文件的fixture, 这里我设置为autouse=True 主要是为了查看打印读取到的目录
import os
import yaml
import pytest
 
@pytest.fixture(scope="session", autouse=True)
def configinfo(request):
    configfile = os.path.join(request.config.rootdir,
                              "config",
                              "config.yaml")
    print("configinfo file path : %s" % configfile)
    with open(configfile) as f:
        cfg = yaml.load(f.read(), Loader=yaml.SafeLoader)
    print(cfg)
    return cfg

 

rootdir 读取
 
打开 cmd 命令行,在项目的根目录运行测试用例
pytest -s
这时候可以看到读取到的配置文件地址:D:\pythonProject\fixture_request\config\config.yaml
在项目根目录运行用例是标准的运行姿势,但是有可能会 cd 到 case 目录,运行单个用例
D:\pythonProject\fixture_request>cd case
  
D:\pythonProject\fixture_request\case>pytest test_03.py
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-3.9.3, py-1.7.0, pluggy-0.12.0
rootdir: D:\pythonProject\fixture_request\case, inifile:
plugins: allure-pytest-2.7.0, forked-0.2, html-1.21.1, metadata-1.8.0, ordering-0.6, repeat-0.8.0, rerunfailures-5.0, xdist-1.24.1
collected 1 item                                                               
 
 
test_03.py E                                                             [100%]
 
 
=================================== ERRORS ====================================
__________________________ ERROR at setup of test_h ___________________________
 
 
request = <SubRequest 'configinfo' for <Function 'test_h'>>
 
 
    @pytest.fixture(scope="session", autouse=True)
    def configinfo(request):
        configfile = os.path.join(request.config.rootdir,
                                  "config",
                                  "config.yaml")
        print("configinfo file path : %s" % configfile)
>       with open(configfile) as f:
E       FileNotFoundError: [Errno 2] No such file or directory: 'D:\\pythonProject\\fixture_request\\case\\config\\config.yaml'
 
 
..\conftest.py:18: FileNotFoundError
---------------------------- Captured stdout setup ----------------------------
configinfo file path : D:\pythonProject\fixture_request\case\config\config.yaml
=========================== 1 error in 0.07 seconds ===========================
 

 

这个时候就会出现报错:FileNotFoundError: [Errno 2] No such file or directory: 'D:\\pythonProject\\fixture_request\\case\\config\\config.yaml'
因为此时的项目根目录就变成 rootdir: D:\pythonProject\fixture_request\case
接下来我们需要解决的问题是,不管在哪个目录下运行,它的项目根目录应该都是我们的工程目录 rootdir: D:\pythonProject\fixture_request
 
pytest.ini
pytest 运行测试用例的时候项目的 rootdir 当没有 pytest.ini 配置文件的时候会根据 conftest.py 找到它的根目录
由于前面没有用到pytest.ini 配置文件,导致不同目录运行测试用例的 rootdir 不一样。
当项目下存在 pytest.ini 配置文件的时候,会认为 pytest.ini 所在的目录是rootdir 目录,所以我们一般会把 pytest.ini 配置文件放到项目的根目录。
如果里面没有内容,放个空的也行
 
这时候不管在哪个目录运行用例都不会有问题了
D:\pythonProject\fixture_request\case>pytest test_03.py
============================================================================================== test session starts ==============================================================================================
platform win32 -- Python 3.7.0, pytest-3.9.3, py-1.7.0, pluggy-0.12.0 -- c:\users\93724\appdata\local\programs\python\python37\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.7.0', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '3.9.3', 'py': '1.7.0', 'pluggy': '0.12.0'}, 'Plugins': {'allure-pytest': '2.7.0', 'forked': '0.2', 'html': '1.21.1'
, 'metadata': '1.8.0', 'ordering': '0.6', 'repeat': '0.8.0', 'rerunfailures': '5.0', 'xdist': '1.24.1'}, 'JAVA_HOME': 'C:\\Program Files\\Java\\jdk1.8.0_131'}
rootdir: D:\pythonProject\fixture_request, inifile: pytest.ini
plugins: allure-pytest-2.7.0, forked-0.2, html-1.21.1, metadata-1.8.0, ordering-0.6, repeat-0.8.0, rerunfailures-5.0, xdist-1.24.1
collected 1 item                                                                                                                                                                                                 
test_03.py::test_h configinfo file path : D:\pythonProject\fixture_request\config\config.yaml
{'logger': {'name': 'automation', 'level': 'WARNING', 'file': 'myLog.txt', 'format': '%(asctime)s, %(levelname)8s [%(filename)s:%(lineno)d] %(message)s'}}
 
读取配置文件的url地址:https://www.cnblogs.com/HandsUp/
用例:https://www.cnblogs.com/HandsUp/
 
PASSED
 
 
=============================================================================================== warnings summary ================================================================================================
case/test_03.py::test_h
  c:\users\93724\appdata\local\programs\python\python37\lib\site-packages\yaml\constructor.py:126: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is depreca
ted, and in 3.8 it will stop working
    if not isinstance(key, collections.Hashable):
 
 
-- Docs: https://docs.pytest.org/en/latest/warnings.html
===================================================================================== 1 passed, 1 warnings in 0.04 seconds ======================================================================================
 
pytest 的配置文件除了 pytest.ini, 还有tox.ini 和 setup.cfg 也可以当配置文件
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2020-12-28 10:20  Janus_Blog  阅读(488)  评论(0编辑  收藏  举报